vault

package
v1.20220411.3 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2022 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package vault implements a high throughput vault client.

It also provides helpers for reading and writing objects to vault key value stores.

Mock and Testing Examples

Very often you will need to mock the vault client in your code so you don't reach out to and actual vault instance during tests. Before writing tests, however, you should make sure that any references to the vault client do so through the `vault.Client` interface, not a concrete type like `*vault.APIClient`.

Then, in your tests, you can create a new mock:

type clientMock struct {
	vault.Client // embed the vault client interface to satisfy the interface requirements.
}
// implement a specific method you need to mock
func (clientMock) Get(_ context.Context, path string, opts ...vault.CallOption) (vault.Values, error) {
	return vault.Values{ "foo": "bar"}, nil
}

This will then let you pass `new(clientMock)` to anywhere you need to set a `vault.Client`

Index

Constants

View Source
const (
	// DefaultAddr is the default addr.
	DefaultAddr = "http://127.0.0.1:8200"
	// DefaultTimeout is the default timeout.
	DefaultTimeout = time.Second
	// DefaultMount is the default kv mount.
	DefaultMount = "/secret"
)
View Source
const (
	// EnvVarVaultAddr is the environment variable for the vault address.
	EnvVarVaultAddr = "VAULT_ADDR"
	// EnvVarVaultMount is the environment variable for the vault mount.
	EnvVarVaultMount = "VAULT_MOUNT"
	// EnvVarVaultToken is the environment variable for the vault token.
	EnvVarVaultToken = "VAULT_TOKEN"
	// EnvVarVaultCertAuthorityPath is the environment variable for the vault certificate authority.
	EnvVarVaultCertAuthorityPath = "VAULT_CACERT"
	// EnvVarVaultTimeout is the environment variable for how long to wait for vault to timeout. The values here
	// are parsed by time.ParseDuration. Examples (5s = five seconds, 100ms = 100 milliseconds, etc.)
	EnvVarVaultTimeout = "VAULT_TIMEOUT"
)
View Source
const (
	// MethodGet is a request method.
	MethodGet = "GET"
	// MethodPost is a request method.
	MethodPost = "POST"
	// MethodPut is a request method.
	MethodPut = "PUT"
	// MethodDelete is a request method.
	MethodDelete = "DELETE"
	// MethodList is a request method.
	MethodList = "LIST"

	// HeaderVaultToken is the vault token header.
	HeaderVaultToken = "X-Vault-Token"
	// HeaderContentType is the content type header.
	HeaderContentType = "Content-Type"
	// ContentTypeApplicationJSON is a content type.
	ContentTypeApplicationJSON = "application/json"

	// DefaultBufferPoolSize is the default buffer pool size.
	DefaultBufferPoolSize = 1024

	// ReflectTagName is a reflect tag name.
	ReflectTagName = "secret"

	// Version1 is a constant.
	Version1 = "1"
	// Version2 is a constant.
	Version2 = "2"
)
View Source
const (
	TypeAES256GCM96      = "aes256-gcm96"
	TypeCHACHA20POLY1305 = "chacha20-poly1305"
	TypeED25519          = "ed25519"
	TypeECDSAP256        = "ecdsa-p256"
	TypeRSA2048          = "rsa-2048"
	TypeRSA4096          = "rsa-4096"
)

These types are encryption algorithms that can be used when creating a transit key

View Source
const (
	// STSURL is the url of the sts call
	STSURL = "https://sts.amazonaws.com"
	// STSGetIdentityBody is the body of the post request
	STSGetIdentityBody = "Action=GetCallerIdentity&Version=2011-06-15"
)

These constants are used to sign the get identity request

View Source
const (
	ErrNotFound                 ex.Class = "vault; not found"
	ErrUnauthorized             ex.Class = "vault; not authorized"
	ErrServerError              ex.Class = "vault; remote error"
	ErrBatchTransitEncryptError ex.Class = "vault; batch encryption error"
	ErrBatchTransitDecryptError ex.Class = "vault; batch decryption error"
)

Common error codes.

View Source
const (
	// AWSAuthLoginPath is the login path for aws iam auth
	AWSAuthLoginPath = "/v1/auth/aws/login"
)

constants required for login /v1/auth/aws/login

View Source
const (
	// Flag is the logger flag.
	Flag = "vault"
)
View Source
const (
	StructTag = "secret"
)

Constants

Variables

This section is empty.

Functions

func DecomposeJSON

func DecomposeJSON(obj interface{}) (map[string]string, error)

DecomposeJSON decomposes an object into json fields marked with the `secret` struct tag. Top level fields will get their own keys. Nested objects are serialized as json.

func ErrClassForStatus

func ErrClassForStatus(statusCode int) ex.Class

ErrClassForStatus returns the exception class for a given remote status code.

func GetIAMAuthCredentials added in v1.20210517.3

func GetIAMAuthCredentials(roleARN string) (*credentials.Credentials, error)

GetIAMAuthCredentials is a credential provider to be passed in as input into the AWSAuth struct

func NewEventListener

func NewEventListener(action func(context.Context, Event)) logger.Listener

NewEventListener returns a new logger listener for a given event.

func RestoreJSON

func RestoreJSON(data map[string]string, obj interface{}) error

RestoreJSON restores an object from a given data bag as JSON.

func WithClient

func WithClient(ctx context.Context, client Client) context.Context

WithClient sets the vault client on a given context.

Types

type APIClient

type APIClient struct {
	Timeout    time.Duration
	Transport  *http.Transport
	Remote     *url.URL
	Token      string
	Mount      string
	Log        logger.Log
	BufferPool *bufferutil.Pool
	KV1        *KV1
	KV2        *KV2
	Transit    TransitClient
	Client     HTTPClient
	CertPool   *x509.CertPool
	Tracer     Tracer
	AWSAuth    *AWSAuth
}

APIClient is a client to talk to vault.

func New

func New(options ...Option) (*APIClient, error)

New creates a new vault client with a default set of options.

func (*APIClient) BatchDecrypt added in v1.20210517.3

func (c *APIClient) BatchDecrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([][]byte, error)

BatchDecrypt batch decrypts a given set of data.

func (*APIClient) BatchEncrypt added in v1.20210517.3

func (c *APIClient) BatchEncrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([]string, error)

BatchEncrypt batch encrypts a given set of data.

func (*APIClient) ConfigureTransitKey

func (c *APIClient) ConfigureTransitKey(ctx context.Context, key string, options ...UpdateTransitKeyOption) error

ConfigureTransitKey configures a transit key path

func (*APIClient) CreateTransitKey

func (c *APIClient) CreateTransitKey(ctx context.Context, key string, options ...CreateTransitKeyOption) error

CreateTransitKey creates a transit key path

func (*APIClient) Decrypt

func (c *APIClient) Decrypt(ctx context.Context, key string, context []byte, ciphertext string) ([]byte, error)

Decrypt decrypts a given set of data.

func (*APIClient) Delete

func (c *APIClient) Delete(ctx context.Context, key string, options ...CallOption) error

Delete puts a key.

func (*APIClient) DeleteTransitKey

func (c *APIClient) DeleteTransitKey(ctx context.Context, key string) error

DeleteTransitKey deletes a transit key path

func (*APIClient) Encrypt

func (c *APIClient) Encrypt(ctx context.Context, key string, context, data []byte) (string, error)

Encrypt encrypts a given set of data.

func (*APIClient) Get

func (c *APIClient) Get(ctx context.Context, key string, options ...CallOption) (Values, error)

Get gets a value at a given key.

func (*APIClient) List

func (c *APIClient) List(ctx context.Context, path string, options ...CallOption) ([]string, error)

List returns a slice of key and subfolder names at this path.

func (*APIClient) Put

func (c *APIClient) Put(ctx context.Context, key string, data Values, options ...CallOption) error

Put puts a value.

func (*APIClient) ReadInto

func (c *APIClient) ReadInto(ctx context.Context, key string, obj interface{}, options ...CallOption) error

ReadInto reads a secret into an object.

func (*APIClient) ReadTransitKey

func (c *APIClient) ReadTransitKey(ctx context.Context, key string) (map[string]interface{}, error)

ReadTransitKey returns data about a transit key path

func (*APIClient) TransitHMAC added in v1.20210815.2

func (c *APIClient) TransitHMAC(ctx context.Context, key string, input []byte) ([]byte, error)

TransitHMAC decrypts a given set of data.

func (*APIClient) WriteInto

func (c *APIClient) WriteInto(ctx context.Context, key string, obj interface{}, options ...CallOption) error

WriteInto writes an object into a secret at a given key.

type AWSAuth added in v1.20210517.3

type AWSAuth struct {
	CredentialProvider CredentialProvider
}

AWSAuth defines vault aws auth methods

func NewAWSAuth added in v1.20210517.3

func NewAWSAuth(opts ...AWSAuthOption) (*AWSAuth, error)

NewAWSAuth creates a new AWS struct

func (*AWSAuth) AWSIAMLogin added in v1.20210517.3

func (a *AWSAuth) AWSIAMLogin(ctx context.Context, client HTTPClient, baseURL url.URL, roleName, roleARN, service, region string) (string, error)

AWSIAMLogin returns a vault token given the instance role which invokes this function

func (*AWSAuth) GetCallerIdentitySignedRequest added in v1.20210603.3

func (a *AWSAuth) GetCallerIdentitySignedRequest(roleARN, service, region string) (*http.Request, error)

GetCallerIdentitySignedRequest gets a signed caller identity request

type AWSAuthOption added in v1.20210517.3

type AWSAuthOption func(*AWSAuth) error

AWSAuthOption mutates an AWSAuth instance

func OptAWSAuthCredentialProvider added in v1.20210517.3

func OptAWSAuthCredentialProvider(cp CredentialProvider) AWSAuthOption

OptAWSAuthCredentialProvider sets the credential provider

type AWSAuthResponse added in v1.20210517.3

type AWSAuthResponse struct {
	LeaseID       string                 `json:"lease_id,omitempty"`
	Renewable     bool                   `json:"renewable,omitempty"`
	LeaseDuration int64                  `json:"lease_duration,omitempty"`
	Data          map[string]interface{} `json:"data,omitempty"`
	Warnings      map[string]interface{} `json:"warnings,omitempty"`
	Auth          struct {
		ClientToken string   `json:"client_token,omitempty"`
		Accessor    string   `json:"accessor,omitempty"`
		Policies    []string `json:"policies,omitempty"`
		Metadata    struct {
			RoleTagMaxTTL string `json:"role_tag_max_ttl,omitempty"`
			InstanceID    string `json:"instance_id,omitempty"`
			AMIID         string `json:"ami_id,omitempty"`
			Role          string `json:"role,omitempty"`
			AuthType      string `json:"auth_type,omitempty"`
		} `json:"metadata"`
	} `json:"auth"`
	Errors []string `json:"errors,omitempty"`
}

AWSAuthResponse is a response for github auth.

type BatchTransitInput added in v1.20210517.3

type BatchTransitInput struct {
	BatchTransitInputItems []BatchTransitInputItem `json:"batch_input"`
}

BatchTransitInput is the structure of batch encrypt / decrypt requests

type BatchTransitInputItem added in v1.20210517.3

type BatchTransitInputItem struct {
	Context    []byte `json:"context,omitempty"`
	Ciphertext string `json:"ciphertext,omitempty"`
	Plaintext  []byte `json:"plaintext,omitempty"`
}

BatchTransitInputItem is a single item in a batch encrypt / decrypt request

type BatchTransitResult added in v1.20210517.3

type BatchTransitResult struct {
	Data struct {
		BatchTransitResult []struct {
			// Error, if set represents a failure encountered while encrypting/decrypting a
			// corresponding batch request item
			Error      string `json:"error"`
			Ciphertext string `json:"ciphertext"`
			Plaintext  string `json:"plaintext"`
		} `json:"batch_results"`
	} `json:"data"`
}

BatchTransitResult is the structure returned by vault for batch transit requests

type Buffer

type Buffer struct {
	*bytes.Buffer
	// contains filtered or unexported fields
}

Buffer is a bytes.Buffer with a reference back to the buffer pool. It returns itself to the pool on close.

func (*Buffer) Close

func (b *Buffer) Close() error

Close returns the buffer to the pool.

type BufferPool

type BufferPool struct {
	sync.Pool
}

BufferPool is a sync.Pool of bytes.Buffer.

func NewBufferPool

func NewBufferPool(bufferSize int) *BufferPool

NewBufferPool returns a new BufferPool. bufferSize is the size of the returned buffers pre-allocated size in bytes. Typically this is something between 256 bytes and 1kb.

func (*BufferPool) Get

func (bp *BufferPool) Get() *Buffer

Get returns a pooled bytes.Buffer instance.

func (*BufferPool) Put

func (bp *BufferPool) Put(b *Buffer)

Put returns the pooled instance.

type CallOption

type CallOption = webutil.RequestOption

CallOption a thing that we can do to modify a request.

func OptList

func OptList() CallOption

OptList adds a list parameter to the request.

func OptVersion

func OptVersion(version int) CallOption

OptVersion adds a version to the request.

type Client

type Client interface {
	KVClient
	TransitClient
}

Client is the general interface for a Secrets client

func GetClient

func GetClient(ctx context.Context) Client

GetClient gets a vault client on a context.

type Config

type Config struct {
	// Addr is the remote address of the secret store.
	Addr string `json:"addr" yaml:"addr" env:"VAULT_ADDR"`
	// Mount is the default mount path, it prefixes any paths.
	Mount string `json:"mount" yaml:"mount" env:"VAULT_MOUNT"`
	// Token is the authentication token used to talk to the secret store.
	Token string `json:"token" yaml:"token" env:"VAULT_TOKEN"`
	// Timeout is the dial timeout for requests to the secrets store.
	Timeout time.Duration `json:"timeout" yaml:"timeout" env:"VAULT_TIMEOUT"`
	// RootCAs is a list of certificate authority paths.
	RootCAs []string `json:"rootCAs" yaml:"rootCAs" env:"VAULT_CA_CERT,csv"`
}

Config is the secrets config object.

func (Config) AddrOrDefault

func (c Config) AddrOrDefault() string

AddrOrDefault returns the client addr.

func (Config) IsZero

func (c Config) IsZero() bool

IsZero returns if the config is set or not.

func (Config) MountOrDefault

func (c Config) MountOrDefault() string

MountOrDefault returns secrets mount or a default.

func (*Config) Resolve

func (c *Config) Resolve(ctx context.Context) error

Resolve reads the environment into the config on configutil.Read(...)

func (Config) TimeoutOrDefault

func (c Config) TimeoutOrDefault() time.Duration

TimeoutOrDefault returns the client timeout.

type CreateTransitKeyConfig

type CreateTransitKeyConfig struct {
	// Convergent - If enabled, the key will support convergent encryption, where the same plaintext creates the same
	// ciphertext. This requires derived to be set to true. When enabled, each encryption(/decryption/rewrap/datakey)
	// operation will derive a nonce value rather than randomly generate it.
	Convergent bool `json:"convergent_encryption,omitempty"`
	// Derived - Specifies if key derivation is to be used. If enabled, all encrypt/decrypt requests to this named key
	// must provide a context which is used for key derivation.
	Derived bool `json:"derived,omitempty"`
	// Exportable - Enables keys to be exportable. This allows for all the valid keys in the key ring to be exported.
	// Once set, this cannot be disabled.
	Exportable bool `json:"exportable,omitempty"`
	// AllowPlaintextBackup - If set, enables taking backup of named key in the plaintext format. Once set, this cannot
	// be disabled.
	AllowPlaintextBackup bool `json:"allow_plaintext_backup,omitempty"`
	// Type specifies the type of key to create. The default type is "aes256-gcm96":
	//   aes256-gcm96 – AES-256 wrapped with GCM using a 96-bit nonce size AEAD (symmetric, supports derivation and
	//      convergent encryption)
	//   chacha20-poly1305 – ChaCha20-Poly1305 AEAD (symmetric, supports derivation and convergent encryption)
	//   ed25519 – ED25519 (asymmetric, supports derivation). When using derivation, a sign operation with the same
	//      context will derive the same key and signature; this is a signing analog to convergent_encryption.
	//   ecdsa-p256 – ECDSA using the P-256 elliptic curve (asymmetric)
	//   rsa-2048 - RSA with bit size of 2048 (asymmetric)
	//   rsa-4096 - RSA with bit size of 4096 (asymmetric)
	Type string `json:"type,omitempty"`
}

CreateTransitKeyConfig is the configuration data for creating a TransitKey

type CreateTransitKeyOption

type CreateTransitKeyOption func(tkc *CreateTransitKeyConfig) error

CreateTransitKeyOption is an option type for transit key creation

func OptCreateTransitAllowPlaintextBackup

func OptCreateTransitAllowPlaintextBackup() CreateTransitKeyOption

OptCreateTransitAllowPlaintextBackup - If set, enables taking backup of named key in the plaintext format. Once set, this cannot be disabled.

func OptCreateTransitConfig

func OptCreateTransitConfig(config CreateTransitKeyConfig) CreateTransitKeyOption

OptCreateTransitConfig is a creation option for when you have a pre-defined struct

func OptCreateTransitConvergent

func OptCreateTransitConvergent() CreateTransitKeyOption

OptCreateTransitConvergent - If enabled, the key will support convergent encryption, where the same plaintext creates the same ciphertext. This also sets derived to true (which is required). When enabled, each encryption (or decryption or rewrap or datakey) operation will derive a nonce value rather than randomly generate it.

func OptCreateTransitDerived

func OptCreateTransitDerived() CreateTransitKeyOption

OptCreateTransitDerived - Specifies if key derivation is to be used. If enabled, all encrypt/decrypt requests to this named key must provide a context which is used for key derivation.

func OptCreateTransitExportable

func OptCreateTransitExportable() CreateTransitKeyOption

OptCreateTransitExportable - Enables keys to be exportable. This allows for all the valid keys in the key ring to be exported. Once set, this cannot be disabled.

func OptCreateTransitType

func OptCreateTransitType(keyType string) CreateTransitKeyOption

OptCreateTransitType - specifies the type of key to create. The default type is "aes256-gcm96":

  aes256-gcm96 – AES-256 wrapped with GCM using a 96-bit nonce size AEAD (symmetric, supports derivation and
     convergent encryption)
  chacha20-poly1305 – ChaCha20-Poly1305 AEAD (symmetric, supports derivation and convergent encryption)
  ed25519 – ED25519 (asymmetric, supports derivation). When using derivation, a sign operation with the same
     context will derive the same key and signature; this is a signing analog to convergent_encryption.
	 ecdsa-p256 – ECDSA using the P-256 elliptic curve (asymmetric)
	 rsa-2048 - RSA with bit size of 2048 (asymmetric)
  rsa-4096 - RSA with bit size of 4096 (asymmetric)

type CredentialProvider added in v1.20210517.3

type CredentialProvider func(roleARN string) (*credentials.Credentials, error)

CredentialProvider defines the credential provider func interface

type Event

type Event struct {
	Remote     string
	Method     string
	Path       string
	StatusCode int
	Elapsed    time.Duration
}

Event is an event.

func NewEvent

func NewEvent(req *http.Request) *Event

NewEvent returns a new event from a request.

func (*Event) Decompose

func (e *Event) Decompose() map[string]interface{}

Decompose impements logger.JSONWritable.

func (Event) GetFlag

func (e Event) GetFlag() string

GetFlag implements logger.Event.

func (*Event) WriteText

func (e *Event) WriteText(tf logger.TextFormatter, wr io.Writer)

WriteText writes text for the event.

type GitHubAuthResponse added in v1.20210517.3

type GitHubAuthResponse struct {
	LeaseID       string                 `json:"lease_id,omitempty"`
	Renewable     bool                   `json:"renewable,omitempty"`
	LeaseDuration int64                  `json:"lease_duration,omitempty"`
	Data          map[string]interface{} `json:"data,omitempty"`
	Warnings      map[string]interface{} `json:"warnings,omitempty"`
	Auth          struct {
		ClientToken string   `json:"client_token,omitempty"`
		Accessor    string   `json:"accessor,omitempty"`
		Policies    []string `json:"policies,omitempty"`
		Metadata    struct {
			Username string `json:"username,omitempty"`
			Org      string `json:"org,omitempty"`
		} `json:"metadata"`
	} `json:"auth"`
}

GitHubAuthResponse is a response for github auth.

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient is a client that can send http requests.

type IsZeroable

type IsZeroable interface {
	IsZero() bool
}

IsZeroable is useful to test if we need to set a config field or not.

type KV

type KV interface {
	Put(ctx context.Context, path string, data Values, options ...CallOption) error
	Get(ctx context.Context, path string, options ...CallOption) (Values, error)
	Delete(ctx context.Context, path string, options ...CallOption) error
	List(ctx context.Context, path string, options ...CallOption) ([]string, error)
}

KV is a basic key value store.

type KV1

type KV1 struct {
	Client *APIClient
}

KV1 defines key value version 1 interactions

func (KV1) Delete

func (kv1 KV1) Delete(ctx context.Context, path string, options ...CallOption) error

Delete puts a key.

func (KV1) Get

func (kv1 KV1) Get(ctx context.Context, path string, options ...CallOption) (Values, error)

Get gets a value at a given key.

func (KV1) List

func (kv1 KV1) List(ctx context.Context, path string, options ...CallOption) ([]string, error)

List returns a slice of key and subfolder names at this path.

func (KV1) Put

func (kv1 KV1) Put(ctx context.Context, path string, data Values, options ...CallOption) error

Put puts a value.

type KV2

type KV2 struct {
	Client *APIClient
}

KV2 defines key value version 2 interactions

func (KV2) Delete

func (kv2 KV2) Delete(ctx context.Context, path string, options ...CallOption) error

Delete deletes a secret.

func (KV2) Get

func (kv2 KV2) Get(ctx context.Context, path string, options ...CallOption) (Values, error)

Get gets a value at a given key.

func (KV2) List

func (kv2 KV2) List(ctx context.Context, path string, options ...CallOption) ([]string, error)

List returns a slice of key and subfolder names at this path.

func (KV2) Put

func (kv2 KV2) Put(ctx context.Context, path string, data Values, options ...CallOption) error

Put puts a value.

type KVClient

type KVClient = KV

KVClient is a basic key value store client.

type KeyData

type KeyData struct {
	Keys []string `json:"keys"`
}

KeyData is used for lists.

type MockHTTPClient

type MockHTTPClient struct {
	// contains filtered or unexported fields
}

MockHTTPClient is a mock http client. It is used to test the vault client iself, and should not be used for your own mocks.

func NewMockHTTPClient

func NewMockHTTPClient() *MockHTTPClient

NewMockHTTPClient returns a new mock http client. MockHTTPClient is used to test VaultClient itself, and should not be used for your own mocks.

func (*MockHTTPClient) Do

func (mh *MockHTTPClient) Do(req *http.Request) (*http.Response, error)

Do implements HTTPClient.

func (*MockHTTPClient) With

func (mh *MockHTTPClient) With(verb string, url *url.URL, response *http.Response) *MockHTTPClient

With adds a mocked endpoint.

func (*MockHTTPClient) WithString

func (mh *MockHTTPClient) WithString(verb string, url *url.URL, contents string) *MockHTTPClient

WithString adds a mocked endpoint.

type MockTransitClient added in v1.20210216.2

type MockTransitClient struct {
	Client
}

MockTransitClient skips interactions with the vault for encryption/decryption

func (MockTransitClient) BatchDecrypt added in v1.20210517.3

func (m MockTransitClient) BatchDecrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([][]byte, error)

BatchDecrypt just returns the input

func (MockTransitClient) BatchEncrypt added in v1.20210517.3

func (m MockTransitClient) BatchEncrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([]string, error)

BatchEncrypt just returns the input

func (MockTransitClient) Decrypt added in v1.20210216.2

func (m MockTransitClient) Decrypt(ctx context.Context, key string, context []byte, ciphertext string) ([]byte, error)

Decrypt just returns the input in the mock

func (MockTransitClient) Encrypt added in v1.20210216.2

func (m MockTransitClient) Encrypt(ctx context.Context, key string, context, data []byte) (string, error)

Encrypt just returns the input in the mock

func (MockTransitClient) TransitHMAC added in v1.20210815.2

func (m MockTransitClient) TransitHMAC(ctx context.Context, key string, input []byte) ([]byte, error)

TransitHMAC just returns the input

type Mount

type Mount struct {
	Type        string            `json:"type"`
	Description string            `json:"description"`
	Accessor    string            `json:"accessor"`
	Config      MountConfig       `json:"config"`
	Options     map[string]string `json:"options"`
	Local       bool              `json:"local"`
	SealWrap    bool              `json:"seal_wrap" mapstructure:"seal_wrap"`
}

Mount is a vault mount.

type MountConfig

type MountConfig struct {
	DefaultLeaseTTL           int      `json:"default_lease_ttl" mapstructure:"default_lease_ttl"`
	MaxLeaseTTL               int      `json:"max_lease_ttl" mapstructure:"max_lease_ttl"`
	ForceNoCache              bool     `json:"force_no_cache" mapstructure:"force_no_cache"`
	PluginName                string   `json:"plugin_name,omitempty" mapstructure:"plugin_name"`
	AuditNonHMACRequestKeys   []string `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"`
	AuditNonHMACResponseKeys  []string `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"`
	ListingVisibility         string   `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"`
	PassthroughRequestHeaders []string `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"`
}

MountConfig is a vault mount config.

type MountConfigInput

type MountConfigInput struct {
	Options                   map[string]string `json:"options" mapstructure:"options"`
	DefaultLeaseTTL           string            `json:"default_lease_ttl" mapstructure:"default_lease_ttl"`
	MaxLeaseTTL               string            `json:"max_lease_ttl" mapstructure:"max_lease_ttl"`
	ForceNoCache              bool              `json:"force_no_cache" mapstructure:"force_no_cache"`
	PluginName                string            `json:"plugin_name,omitempty" mapstructure:"plugin_name"`
	AuditNonHMACRequestKeys   []string          `json:"audit_non_hmac_request_keys,omitempty" mapstructure:"audit_non_hmac_request_keys"`
	AuditNonHMACResponseKeys  []string          `json:"audit_non_hmac_response_keys,omitempty" mapstructure:"audit_non_hmac_response_keys"`
	ListingVisibility         string            `json:"listing_visibility,omitempty" mapstructure:"listing_visibility"`
	PassthroughRequestHeaders []string          `json:"passthrough_request_headers,omitempty" mapstructure:"passthrough_request_headers"`
}

MountConfigInput is a vault mount config input.

type MountInput

type MountInput struct {
	Type        string            `json:"type"`
	Description string            `json:"description"`
	Config      MountConfigInput  `json:"config"`
	Options     map[string]string `json:"options"`
	Local       bool              `json:"local"`
	PluginName  string            `json:"plugin_name,omitempty"`
	SealWrap    bool              `json:"seal_wrap" mapstructure:"seal_wrap"`
}

MountInput is a vault mount input.

type MountResponse

type MountResponse struct {
	RequestID string `json:"request_id"`
	Data      Mount  `json:"data"`
}

MountResponse is the result of a call to a mount.

type Option

type Option func(*APIClient) error

Option is an option for a vault client.

func OptAddr

func OptAddr(addr string) Option

OptAddr is an alias to OptRemote.

func OptConfig

func OptConfig(cfg Config) Option

OptConfig sets the vault client from a given configuration.

func OptConfigFromEnv

func OptConfigFromEnv() Option

OptConfigFromEnv sets the vault client from a given configuration read from the environment.

func OptLog

func OptLog(log logger.Log) Option

OptLog sets the logger on the vault client.

func OptMount

func OptMount(mount string) Option

OptMount sets the vault client mount.

func OptRemote

func OptRemote(addr string) Option

OptRemote sets the client remote.

func OptRootCAs

func OptRootCAs(rootCAs ...string) Option

OptRootCAs sets the root ca pool for client requests.

func OptTimeout

func OptTimeout(timeout time.Duration) Option

OptTimeout sets the timeout to vault

func OptToken

func OptToken(token string) Option

OptToken sets the vault client token.

func OptTracer

func OptTracer(tracer Tracer) Option

OptTracer allows you to configure a tracer on the vault client

type SecretAuth

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

SecretAuth is the structure containing auth information if we have it.

type SecretData

type SecretData struct {
	Data Values `json:"data"`
}

SecretData is used for puts.

type SecretListV1

type SecretListV1 struct {
	// The request ID that generated this response
	RequestID     string `json:"request_id"`
	LeaseID       string `json:"lease_id"`
	LeaseDuration int    `json:"lease_duration"`
	Renewable     bool   `json:"renewable"`
	// Data is the list of keys and subfolders at this path. Subfolders end with a slash, keys do not
	Data KeyData `json:"data"`
	// Warnings contains any warnings related to the operation. These
	// are not issues that caused the command to fail, but that the
	// client should be aware of.
	Warnings []string `json:"warnings"`
	// Auth, if non-nil, means that there was authentication information
	// attached to this response.
	Auth *SecretAuth `json:"auth,omitempty"`
	// WrapInfo, if non-nil, means that the initial response was wrapped in the
	// cubbyhole of the given token (which has a TTL of the given number of
	// seconds)
	WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"`
}

SecretListV1 is the structure returned for a list of secret keys in vault

type SecretListV2

type SecretListV2 struct {
	// The request ID that generated this response
	RequestID     string `json:"request_id"`
	LeaseID       string `json:"lease_id"`
	LeaseDuration int    `json:"lease_duration"`
	Renewable     bool   `json:"renewable"`
	// Data is the list of keys and subfolders at this path. Subfolders end with a slash, keys do not
	Data KeyData `json:"data"`
	// Warnings contains any warnings related to the operation. These
	// are not issues that caused the command to fail, but that the
	// client should be aware of.
	Warnings []string `json:"warnings"`
	// Auth, if non-nil, means that there was authentication information
	// attached to this response.
	Auth *SecretAuth `json:"auth,omitempty"`
	// WrapInfo, if non-nil, means that the initial response was wrapped in the
	// cubbyhole of the given token (which has a TTL of the given number of
	// seconds)
	WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"`
}

SecretListV2 is the structure returned for every secret within Vault.

type SecretTraceConfig

type SecretTraceConfig struct {
	VaultOperation string
	KeyName        string
}

SecretTraceConfig are the options for sending trace messages for the secrets package

type SecretV1

type SecretV1 struct {
	// The request ID that generated this response
	RequestID     string `json:"request_id"`
	LeaseID       string `json:"lease_id"`
	LeaseDuration int    `json:"lease_duration"`
	Renewable     bool   `json:"renewable"`
	// Data is the actual contents of the secret. The format of the data
	// is arbitrary and up to the secret backend.
	Data Values `json:"data"`
	// Warnings contains any warnings related to the operation. These
	// are not issues that caused the command to fail, but that the
	// client should be aware of.
	Warnings []string `json:"warnings"`
	// Auth, if non-nil, means that there was authentication information
	// attached to this response.
	Auth *SecretAuth `json:"auth,omitempty"`
	// WrapInfo, if non-nil, means that the initial response was wrapped in the
	// cubbyhole of the given token (which has a TTL of the given number of
	// seconds)
	WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"`
}

SecretV1 is the structure returned for every secret within Vault.

type SecretV2

type SecretV2 struct {
	// The request ID that generated this response
	RequestID     string `json:"request_id"`
	LeaseID       string `json:"lease_id"`
	LeaseDuration int    `json:"lease_duration"`
	Renewable     bool   `json:"renewable"`
	// Data is the actual contents of the secret. The format of the data
	// is arbitrary and up to the secret backend.
	Data SecretData `json:"data"`
	// Warnings contains any warnings related to the operation. These
	// are not issues that caused the command to fail, but that the
	// client should be aware of.
	Warnings []string `json:"warnings"`
	// Auth, if non-nil, means that there was authentication information
	// attached to this response.
	Auth *SecretAuth `json:"auth,omitempty"`
	// WrapInfo, if non-nil, means that the initial response was wrapped in the
	// cubbyhole of the given token (which has a TTL of the given number of
	// seconds)
	WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"`
}

SecretV2 is the structure returned for every secret within Vault.

type SecretWrapInfo

type SecretWrapInfo struct {
	Token           string    `json:"token"`
	Accessor        string    `json:"accessor"`
	TTL             int       `json:"ttl"`
	CreationTime    time.Time `json:"creation_time"`
	CreationPath    string    `json:"creation_path"`
	WrappedAccessor string    `json:"wrapped_accessor"`
}

SecretWrapInfo contains wrapping information if we have it. If what is contained is an authentication token, the accessor for the token will be available in WrappedAccessor.

type TraceFinisher

type TraceFinisher interface {
	Finish(ctx context.Context, statusCode int, vaultError error)
}

TraceFinisher is a finisher for traces.

type TraceOption

type TraceOption func(config *SecretTraceConfig) error

TraceOption is an option type for secret trace

func OptTraceConfig

func OptTraceConfig(providedConfig SecretTraceConfig) TraceOption

OptTraceConfig allows you to provide the entire secret trace configuration

func OptTraceKeyName

func OptTraceKeyName(keyName string) TraceOption

OptTraceKeyName allows you to specify the name of the key being interacted with

func OptTraceVaultOperation

func OptTraceVaultOperation(path string) TraceOption

OptTraceVaultOperation allows you to set the VaultOperation being hit

type Tracer

type Tracer interface {
	Start(ctx context.Context, options ...TraceOption) (TraceFinisher, error)
}

Tracer is a tracer for requests.

type Transit

type Transit struct {
	Client *APIClient
}

Transit defines vault transit interactions

func (Transit) BatchDecrypt added in v1.20210517.3

func (vt Transit) BatchDecrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([][]byte, error)

BatchDecrypt batch decrypts a given set of data It is required to create the transit key *before* you use it to encrypt or decrypt data.

func (Transit) BatchEncrypt added in v1.20210517.3

func (vt Transit) BatchEncrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([]string, error)

BatchEncrypt batch encrypts a given set of data It is required to create the transit key *before* you use it to encrypt or decrypt data.

func (Transit) ConfigureTransitKey

func (vt Transit) ConfigureTransitKey(ctx context.Context, key string, options ...UpdateTransitKeyOption) error

ConfigureTransitKey configures a transit key path

func (Transit) CreateTransitKey

func (vt Transit) CreateTransitKey(ctx context.Context, key string, options ...CreateTransitKeyOption) error

CreateTransitKey creates a transit key path

func (Transit) Decrypt

func (vt Transit) Decrypt(ctx context.Context, key string, context []byte, ciphertext string) ([]byte, error)

Decrypt decrypts a given set of data.

It is required to create the transit key *before* you use it to encrypt or decrypt data.

func (Transit) DeleteTransitKey

func (vt Transit) DeleteTransitKey(ctx context.Context, key string) error

DeleteTransitKey deletes a transit key path

func (Transit) Encrypt

func (vt Transit) Encrypt(ctx context.Context, key string, context, data []byte) (string, error)

Encrypt encrypts a given set of data

It is required to create the transit key *before* you use it to encrypt or decrypt data.

func (Transit) ReadTransitKey

func (vt Transit) ReadTransitKey(ctx context.Context, key string) (map[string]interface{}, error)

ReadTransitKey returns data about a transit key path

func (Transit) TransitHMAC added in v1.20210815.2

func (vt Transit) TransitHMAC(ctx context.Context, key string, input []byte) ([]byte, error)

TransitHMAC batch encrypts a given set of data It is required to create the transit key *before* you use it to encrypt or decrypt data.

type TransitClient

type TransitClient interface {
	CreateTransitKey(ctx context.Context, key string, options ...CreateTransitKeyOption) error
	ConfigureTransitKey(ctx context.Context, key string, options ...UpdateTransitKeyOption) error
	ReadTransitKey(ctx context.Context, key string) (map[string]interface{}, error)
	DeleteTransitKey(ctx context.Context, key string) error

	Encrypt(ctx context.Context, key string, context, data []byte) (string, error)
	Decrypt(ctx context.Context, key string, context []byte, ciphertext string) ([]byte, error)

	TransitHMAC(ctx context.Context, key string, input []byte) ([]byte, error)

	BatchEncrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([]string, error)
	BatchDecrypt(ctx context.Context, key string, batchInput BatchTransitInput) ([][]byte, error)
}

TransitClient is an interface for an encryption-as-a-service client

type TransitHmacResult added in v1.20210815.2

type TransitHmacResult struct {
	Data struct {
		Hmac string `json:"hmac"`
	} `json:"data"`
}

TransitHmacResult is the structure returned by vault for transit hmac requests

type TransitKey

type TransitKey struct {
	// The request ID that generated this response
	RequestID     string `json:"request_id"`
	LeaseID       string `json:"lease_id"`
	LeaseDuration int    `json:"lease_duration"`
	Renewable     bool   `json:"renewable"`
	// Data is the data associated with a transit key
	Data map[string]interface{} `json:"data"`
	// Warnings contains any warnings related to the operation. These
	// are not issues that caused the command to fail, but that the
	// client should be aware of.
	Warnings []string `json:"warnings"`
	// Auth, if non-nil, means that there was authentication information
	// attached to this response.
	Auth *SecretAuth `json:"auth,omitempty"`
	// WrapInfo, if non-nil, means that the initial response was wrapped in the
	// cubbyhole of the given token (which has a TTL of the given number of
	// seconds)
	WrapInfo *SecretWrapInfo `json:"wrap_info,omitempty"`
}

TransitKey is the structure returned for every transit key within Vault.

type TransitResult

type TransitResult struct {
	Data struct {
		Ciphertext string `json:"ciphertext"`
		Plaintext  string `json:"plaintext"`
	} `json:"data"`
}

TransitResult is the structure returned by vault for transit requests

type UpdateTransitKeyConfig

type UpdateTransitKeyConfig struct {
	// MinDecryptionVersion -  Specifies the minimum version of ciphertext allowed to be decrypted. Adjusting this as
	// part of a key rotation policy can prevent old copies of ciphertext from being decrypted, should they fall into
	// the wrong hands. For signatures, this value controls the minimum version of signature that can be verified
	// against. For HMACs, this controls the minimum version of a key allowed to be used as the key for verification.
	MinDecryptionVersion int `json:"min_decryption_version,omitempty"`
	// MinEncryptionVersion - Specifies the minimum version of the key that can be used to encrypt plaintext, sign
	// payloads, or generate HMACs. Must be 0 (which will use the latest version) or a value greater or equal to
	// min_decryption_version.
	MinEncryptionVersion int `json:"min_encryption_version,omitempty"`
	// DeletionAllowed - Specifies if the key is allowed to be deleted.
	DeletionAllowed *bool `json:"deletion_allowed,omitempty"`
	// Exportable - Enables keys to be exportable. This allows for all the valid keys in the key ring to be exported.
	// Once set, this cannot be disabled.
	Exportable bool `json:"exportable,omitempty"`
	// AllowPlaintextBackup - If set, enables taking backup of named key in the plaintext format. Once set, this cannot
	// be disabled.
	AllowPlaintextBackup bool `json:"allow_plaintext_backup,omitempty"`
}

UpdateTransitKeyConfig is the configuration data for modifying a TransitKey

type UpdateTransitKeyOption

type UpdateTransitKeyOption func(tkc *UpdateTransitKeyConfig) error

UpdateTransitKeyOption is an option type for transit key creation

func OptUpdateTransitAllowPlaintextBackup

func OptUpdateTransitAllowPlaintextBackup() UpdateTransitKeyOption

OptUpdateTransitAllowPlaintextBackup - If set, enables taking backup of named key in the plaintext format. Once set, this cannot be disabled.

func OptUpdateTransitConfig

func OptUpdateTransitConfig(config UpdateTransitKeyConfig) UpdateTransitKeyOption

OptUpdateTransitConfig is an update option for when you have a pre-defined struct

func OptUpdateTransitDeletionAllowed

func OptUpdateTransitDeletionAllowed(deletionAllowed bool) UpdateTransitKeyOption

OptUpdateTransitDeletionAllowed - Specifies if the key is allowed to be deleted.

func OptUpdateTransitExportable

func OptUpdateTransitExportable() UpdateTransitKeyOption

OptUpdateTransitExportable - Enables keys to be exportable. This allows for all the valid keys in the key ring to be exported. Once set, this cannot be disabled.

func OptUpdateTransitMinDecryptionVer

func OptUpdateTransitMinDecryptionVer(minDecryptionVersion int) UpdateTransitKeyOption

OptUpdateTransitMinDecryptionVer - Specifies the minimum version of ciphertext allowed to be decrypted. Adjusting this as part of a key rotation policy can prevent old copies of ciphertext from being decrypted, should they fall into the wrong hands. For signatures, this value controls the minimum version of signature that can be verified against. For HMACs, this controls the minimum version of a key allowed to be used as the key for verification.

func OptUpdateTransitMinEncryptionVer

func OptUpdateTransitMinEncryptionVer(minEncryptionVersion int) UpdateTransitKeyOption

OptUpdateTransitMinEncryptionVer - Specifies the minimum version of the key that can be used to encrypt plaintext, sign payloads, or generate HMACs. Must be 0 (which will use the latest version) or a value greater or equal to min_decryption_version.

type Values

type Values = map[string]interface{}

Values is a bag of values.

Jump to

Keyboard shortcuts

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