vault

package module
v0.0.7-0...-4c1f3df Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2020 License: MIT Imports: 12 Imported by: 0

README

Golang Library for HashiCorp vault

Go Doc Release Go

This is yet another golang vault client. It uses the official vault go client but adds some requests and responses types and some convenient methods for an improved Developing experience.

Typing every request and response is rather time consuming, only a few vault APIs are implemented at the moment. If there is demand for us to use other APIs, they will be added. We are also always open to Pull Requests :)

Supported APIs

Currently, these APIs are implemented:

  • Transit(mountPoint)

Authentication

Token-based and Kubernetes Auth are supported as of now.

Token-Based

Initialize a new Vault Client using your token and endpoint:

Example

Kubernetes In-Cluster Example

Example

Usage

Once the Vault Client is created, instanciate new clients for each engine:

TransitList Example

Transit Encrypt/Decrypt Example

Run Tests

Tests require a running docker daemon. The test will automatically create a vault container.

> make test

Documentation

Overview

Example (EncryptDecryptType)
const rsa4096 = "rsa-4096"
c, err := NewClient("https://vault:8200/", WithCaPath(""), WithAuthToken("test"))
if err != nil {
	log.Fatal(err)
}

fmt.Println(c.Token())

transit := c.Transit()

key := "test123bacd"

err = transit.Create(key, &TransitCreateOptions{
	Exportable: null.BoolFrom(true),
	Type:       rsa4096,
})
if err != nil {
	log.Fatal(err)
}

res, err := transit.Read(key)
if err != nil {
	log.Fatal(err)
} else {
	log.Printf("%+v\n", res.Data)
}

exportRes, err := transit.Export(key, TransitExportOptions{
	KeyType: "encryption-key",
})
if err != nil {
	log.Fatal(err)
}
log.Printf("%v+", exportRes.Data.Keys[1])

encryptResponse, err := transit.Encrypt(key, &TransitEncryptOptions{
	Plaintext: "plaintext",
})
if err != nil {
	log.Fatalf("Error occurred during encryption: %v", err)
}
log.Println("Ciphertext: ", encryptResponse.Data.Ciphertext)

decryptResponse, err := transit.Decrypt(key, &TransitDecryptOptions{
	Ciphertext: encryptResponse.Data.Ciphertext,
})
if err != nil {
	log.Fatalf("Error occurred during decryption: %v", err)
}
log.Println("Plaintext: ", decryptResponse.Data.Plaintext)
Output:

Example (K8sInCluster)
c, err := NewClient("https://vault:8200/", WithCaPath(""), WithKubernetesAuth("myrole"))
if err != nil {
	log.Fatal(err)
}

log.Println(c.Address())
Output:

Example (TokenBased)
c, err := NewClient("https://vault:8200/",
	WithCaPath(""),
	WithAuthToken("SECRET"),
)
if err != nil {
	log.Fatal(err)
}

log.Println(c.Address())
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrEncKeyNotFound = errors.New("encryption key not found")
)

Functions

This section is empty.

Types

type AuthProvider

type AuthProvider interface {
	Auth() (*AuthResponse, error)
}

func NewAwsAuth

func NewAwsAuth(c *Client, mountpoint, role, header string) (AuthProvider, error)

func NewKubernetesAuth

func NewKubernetesAuth(c *Client, role string, opts ...KubernetesAuthOpt) (AuthProvider, error)

type AuthResponse

type AuthResponse struct {
	Auth struct {
		ClientToken   string   `json:"client_token"`
		Accessor      string   `json:"accessor"`
		Policies      []string `json:"policies"`
		LeaseDuration int      `json:"lease_duration"`
		Renewable     bool     `json:"renewable"`
		Metadata      struct {
			Role                     string `json:"role"`
			ServiceAccountName       string `json:"service_account_name"`
			ServiceAccountNamespace  string `json:"service_account_namespace"`
			ServiceAccountSecretName string `json:"service_account_secret_name"`
			ServiceAccountUID        string `json:"service_account_uid"`
		} `json:"metadata"`
	} `json:"auth"`
}

type Client

type Client struct {
	*api.Client
	// contains filtered or unexported fields
}

func NewClient

func NewClient(addr string, tlsConf *TLSConfig, opts ...ClientOpts) (*Client, error)

func (*Client) Delete

func (c *Client) Delete(path []string, body, response interface{}, opts *RequestOptions) error

func (*Client) List

func (c *Client) List(path []string, body, response interface{}, opts *RequestOptions) error

func (*Client) Read

func (c *Client) Read(path []string, response interface{}, opts *RequestOptions) error

func (*Client) Request

func (c *Client) Request(method string, path []string, body, response interface{}, opts *RequestOptions) error

func (*Client) Transit

func (c *Client) Transit() *Transit

func (*Client) TransitWithMountPoint

func (c *Client) TransitWithMountPoint(mountPoint string) *Transit

func (*Client) Write

func (c *Client) Write(path []string, body, response interface{}, opts *RequestOptions) error

type ClientOpts

type ClientOpts func(c *Client) error

func WithAuthToken

func WithAuthToken(token string) ClientOpts

func WithAwsAuth

func WithAwsAuth(mountpoint, role, header string) ClientOpts

func WithKubernetesAuth

func WithKubernetesAuth(role string, opts ...KubernetesAuthOpt) ClientOpts

type KubernetesAuthOpt

type KubernetesAuthOpt func(k *kubernetesAuth) error

func WithJwt

func WithJwt(jwt string) KubernetesAuthOpt

func WithJwtFromFile

func WithJwtFromFile(path string) KubernetesAuthOpt

func WithMountPoint

func WithMountPoint(mountPoint string) KubernetesAuthOpt

type RequestOptions

type RequestOptions struct {
	Parameters url.Values

	// SkipRenewal defines if the client should retry this Request with a new Token if it fails because of
	// 403 Permission Denied
	// The default behavior of the client is to always Request a new Token on 403
	// Only if this is explicitly set to true, the client will continue processing the first failed request
	// and skip the renewal
	// This should generally only be disabled for TokenAuth requests (a failed TokenAuth request can't be fixed by
	// doing another TokenAuth request, this would lead to infinite recursion)
	SkipRenewal bool
}

type Service

type Service struct {
	MountPoint string
	// contains filtered or unexported fields
}

type TLSConfig

type TLSConfig struct {
	*api.TLSConfig
}

func WithCaCert

func WithCaCert(cert string) *TLSConfig

func WithCaPath

func WithCaPath(path string) *TLSConfig

type Transit

type Transit struct {
	Service
}

func (*Transit) Create

func (t *Transit) Create(key string, opts *TransitCreateOptions) error

func (*Transit) Decrypt

func (*Transit) DecryptBatch

func (*Transit) Delete

func (t *Transit) Delete(key string) error

func (*Transit) Encrypt

func (*Transit) EncryptBatch

func (*Transit) Export

func (*Transit) ForceDelete

func (t *Transit) ForceDelete(key string) error

func (*Transit) KeyExists

func (t *Transit) KeyExists(key string) (bool, error)

func (*Transit) List

func (t *Transit) List() (*TransitListResponse, error)
Example
c, err := NewClient("https://vault:8200/",
	WithCaPath(""),
	WithAuthToken("SECRET"),
)
if err != nil {
	log.Fatal(err)
}

l, err := c.TransitWithMountPoint("transit").List()
if err != nil {
	log.Fatal()
}

log.Println(l)
Output:

func (*Transit) Read

func (t *Transit) Read(key string) (*TransitReadResponse, error)

func (*Transit) Rotate

func (t *Transit) Rotate(key string) error

func (*Transit) Update

func (t *Transit) Update(key string, opts TransitUpdateOptions) error

type TransitBatchCiphertext

type TransitBatchCiphertext struct {
	Ciphertext string      `json:"ciphertext"`
	Context    null.String `json:"context"`
}

type TransitBatchPlaintext

type TransitBatchPlaintext struct {
	Plaintext string      `json:"plaintext"`
	Context   null.String `json:"context"`
}

type TransitCreateOptions

type TransitCreateOptions struct {
	ConvergentEncryption null.Bool `json:"convergent_encryption,omitempty"`
	Derived              null.Bool `json:"derived,omitempty"`
	Exportable           null.Bool `json:"exportable,omitempty"`
	AllowPlaintextBackup null.Bool `json:"allow_plaintext_backup,omitempty"`
	Type                 string    `json:"type,omitempty"`
}

type TransitDecryptOptions

type TransitDecryptOptions struct {
	Ciphertext string      `json:"ciphertext"`
	Context    null.String `json:"context"`
	Nonce      null.String `json:"nonce"`
}

type TransitDecryptOptionsBatch

type TransitDecryptOptionsBatch struct {
	BatchInput []TransitBatchCiphertext `json:"batch_input"`
}

type TransitDecryptResponse

type TransitDecryptResponse struct {
	Data struct {
		Plaintext string `json:"plaintext"`
	} `json:"data"`
}

type TransitDecryptResponseBatch

type TransitDecryptResponseBatch struct {
	Data struct {
		BatchResults []TransitBatchPlaintext `json:"batch_results"`
	} `json:"data"`
}

type TransitEncryptOptions

type TransitEncryptOptions struct {
	Plaintext            string      `json:"plaintext"`
	Context              null.String `json:"context"`
	KeyVersion           null.Int    `json:"key_version"`
	Nonce                null.String `json:"nonce"`
	Type                 null.String `json:"type"`
	ConvergentEncryption null.String `json:"convergent_encryption"`
}

type TransitEncryptOptionsBatch

type TransitEncryptOptionsBatch struct {
	BatchInput           []TransitBatchPlaintext `json:"batch_input"`
	KeyVersion           null.Int                `json:"key_version"`
	Type                 null.String             `json:"type"`
	ConvergentEncryption null.String             `json:"convergent_encryption"`
}

type TransitEncryptResponse

type TransitEncryptResponse struct {
	Data struct {
		Ciphertext string `json:"ciphertext"`
	} `json:"data"`
}

type TransitEncryptResponseBatch

type TransitEncryptResponseBatch struct {
	Data struct {
		BatchResults []TransitBatchCiphertext `json:"batch_results"`
	} `json:"data"`
}

type TransitExportOptions

type TransitExportOptions struct {
	KeyType string `json:"key_type"`
	Version string `json:"version"`
}

type TransitExportResponse

type TransitExportResponse struct {
	Data struct {
		Name string         `json:"name"`
		Keys map[int]string `json:"keys"`
		Type string         `json:"type"`
	} `json:"data"`
}

type TransitListResponse

type TransitListResponse struct {
	Data struct {
		Keys []string `json:"keys"`
	} `json:"data"`
}

type TransitReadResponse

type TransitReadResponse struct {
	Data TransitReadResponseData `json:"data"`
}

type TransitReadResponseData

type TransitReadResponseData struct {
	Name                 string              `json:"name"`
	Type                 string              `json:"type"`
	Keys                 map[int]interface{} `json:"keys"`
	MinDecryptionVersion int                 `json:"min_decrytion_version"`
	MinEncryptionVersion int                 `json:"min_encryption_version"`
	LatestVersion        int                 `json:"latest_version"`
	DeletionAllowed      bool                `json:"deletion_allowed"`
	Derived              bool                `json:"derived"`
	Exportable           bool                `json:"exportable"`
	AllowPlaintextBackup bool                `json:"allow_plaintext_backup"`
	SupportsEncryption   bool                `json:"supports_encryption"`
	SupportsDecryption   bool                `json:"supports_decryption"`
	SupportsDerivation   bool                `json:"supports_derivation"`
	SupportsSigning      bool                `json:"supports_signing"`
}

type TransitUpdateOptions

type TransitUpdateOptions struct {
	MinDecryptionVersion int       `json:"min_decrytion_version"`
	MinEncryptionVersion int       `json:"min_encryption_version"`
	DeletionAllowed      null.Bool `json:"deletion_allowed"`
	Exportable           null.Bool `json:"exportable"`
	AllowPlaintextBackup null.Bool `json:"allow_plaintext_backup"`
}

Jump to

Keyboard shortcuts

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