forest

package module
v0.0.0-...-b9a3117 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2021 License: Apache-2.0 Imports: 13 Imported by: 0

README

forest

forthebadge made-with-Go

What?

A simplified vault request. Taylored to Bareksa's paradigm.

What Does it Do?

  1. Gets key value store from vault.
  2. Creates token from vault
  3. Handles policy creation

Why?

  1. You (the user) don't need to research how to use Vault much, and example is given directly in code description.
package main

import (
	"context"
	"fmt"
	"gitlab.bareksa.com/backend/forest"
)

func main() {
	client := forest.NewClient("s.token") // This token is an example
	conf, err := forest.GetKeyValue(context.Background(), "some-conf")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(conf))
}

Also you can use custom http clients

httpClient := &http.Client{Timeout: 10 * time.Second}
client := forest.NewClient("s.token", forest.WithHttpClient(httpClient))

Integration with Viper Example

package main

import (
	"bytes"
	"context"
	"fmt"
	"os"

	"github.com/Bareksa/forest"
	"github.com/spf13/viper"
)

func main() {
	vaultHost := os.Getenv("VAULT_HOST")
	vaultToken := os.Getenv("VAULT_TOKEN")

	forest.Init(vaultToken, forest.WithHost(vaultHost))

	conf, err := forest.GetKeyValue(context.Background(), "some-conf")
	if err != nil {
		fmt.Printf("Failed to read configuration from vault : %v", err)
		os.Exit(1)
	}

	viper.SetConfigType("json") // Need to explicitly set this to json
	viper.ReadConfig(bytes.NewBuffer(conf))

	fmt.Printf("Using configuration file from : %s \n", vaultHost)

}

Running Test for this Library Package

Please note integration test have to be modified for own use until vault dev is ready.

$ go test -token [token] -host [host] -v ./...
API Usage Documentation
Package Method Documentation

Contributor

Documentation

Index

Constants

View Source
const (
	// PathTokenLookupSelf Used for Policy Creation
	PathTokenLookupSelf = "auth/token/lookup-self"
	// PathTokenRevokeSelf Used for Policy Creation
	PathTokenRevokeSelf = "auth/token/revoke-self"
	// PathSysCapabilitiesSelf Used for Policy Creation
	PathSysCapabilitiesSelf = "sys/capabilities-self"
	// PathTokenRevoke Used for Policy Creation
	PathTokenRevoke = "auth/token/revoke"
	// PathTokenRoot Used for checking if token is root. *Untested*
	PathTokenRoot = "auth/token/root"
)

Variables

This section is empty.

Functions

func GetConfig

func GetConfig(ctx context.Context, path string) (data []byte, err error)
DEPRECATED. USE GetKeyValue instead.

GetConfig returns config from vault. The path format is '/{secret engine name}/{secret name}'

Example: `data, err := vault.GetConfig(context.Background(), "/kv/foo")`

func GetConfigLoad

func GetConfigLoad(ctx context.Context, path string, model interface{}) (err error)
DEPRECATED. USE GetKeyValueLoad instead.

GetConfigLoad returns config and loaded into a variable The path format is '/{secret engine name}/{secret name}'

func GetEngineKeys

func GetEngineKeys(ctx context.Context, engine string) (configs []string, err error)

GetEngineKeys returns list of keys for given engine

func GetKVEngine

func GetKVEngine() string

GetKVEngine returns the engine name used for the instance

func GetKeyValue

func GetKeyValue(ctx context.Context, key string) (data []byte, err error)

GetKeyValue returns key value store from vault. 'Key' is the key name. Like for example 'ms-order-conf'

func GetKeyValueLoad

func GetKeyValueLoad(ctx context.Context, key string, model interface{}) (err error)

GetKeyValueLoad returns config and loaded into a variable 'Key' is the key name. Like for example 'ms-order-conf'

func GetTransitEngine

func GetTransitEngine() string

GetTransitEngine returns the engine name used for the instance

func Init

func Init(token string, opts ...OptionFunc) (err error)

Init enables global top level functions

func RenewTokenOther

func RenewTokenOther(ctx context.Context, token string) (err error)

RenewTokenOther attempts to renew passed token using self's token

func RenewTokenOverride

func RenewTokenOverride(ctx context.Context, token string) (err error)

RenewTokenOverride attempts to renew passed token with passed token as auth

func RenewTokenSelf

func RenewTokenSelf(ctx context.Context) (err error)

RenewTokenSelf attempts to renew token registered to self

func RevokeToken

func RevokeToken(ctx context.Context, token string) (err error)

RevokeToken revokes given token string. Cannot revoke root token if instance token is not root If getting permission denied error, then it's most likely that reason.

func TransitDecrypt

func TransitDecrypt(ctx context.Context, key, cipherText string) (data []byte, err error)

TransitDecrypt decrypts a transit encrypted payload

func TransitDecryptStream

func TransitDecryptStream(ctx context.Context, key string, cipher io.Reader) (payload io.Reader, err error)

TransitDecryptStream decrypts a transit encrypted payload in streaming manner. Best usage is if you expect a big ciphertext from whatever your source is.

func TransitEncrypt

func TransitEncrypt(ctx context.Context, key string, payload []byte) (cipherText string, err error)

TransitEncrypt will encrypt payload for sending somewhere else. 'key' is the encryptor name.

func TransitEncryptStream

func TransitEncryptStream(ctx context.Context, key string, payload io.Reader) (cipher io.Reader, err error)

TransitEncryptStream will encrypt payload in stream manner to prevent memory overload on huge number of operation. Use this function for big files. The returned io Reader is a stream of pure encoded vault data.

func UpsertKeyValue

func UpsertKeyValue(ctx context.Context, key string, data interface{}) (err error)

UpsertKeyValue creates / updates secret of `key`. Key here means the config.

func UpsertPolicy

func UpsertPolicy(ctx context.Context, policy string, permissions map[string][]Capability) (err error)

UpsertPolicy creates/updates a policy. Token used in the instance must have the permission to even update policy itself. Root token have all permissions

Types

type APIVersion

type APIVersion string

APIVersion the base type is string

const (
	// V2 Version is not supported until Hashicorp says otherwise
	V2 APIVersion = "v2"
	// V1 Default version used
	V1 APIVersion = "v1"
)

type Capability

type Capability string

Capability s

const (
	// CapabilityRead Determines if the token will be able to access the resource. Used for Policy Creation
	CapabilityRead Capability = "read"
	// CapabilityUpdate Determines if the token will be able to update the resource. Used for Policy Creation
	CapabilityUpdate Capability = "update"
	// CapabilityList Determines if the token will be able to LIST resources (not access them). Implicitly allows Cabality of Create.
	// Used for Policy Creation
	CapabilityList Capability = "list"
	// CapabilityDelete Determines if the token can delete a resource. Used for Policy Creation
	CapabilityDelete Capability = "delete"
	// CapabilityCreate Determines if the token used can create a resource.
	CapabilityCreate Capability = "create"
)

type Config

type Config struct {
	Token               string       // Required
	Host                string       // Optional. Defaults to https://127.0.0.1:8200. Make sure to not add '/' in last character
	NoRenew             bool         // Optional. Defaults to false, so it will attempt to renew token every time Renew Timing passes.
	NoRenewOnInitialize bool         // Optional. Defaults to false, which will indeed renew on initiazlie. Will not renew if NoRenew is set to true
	RenewTiming         string       // Optional. Defaults to 0 0 * * * (Every midnight). Uses cron tab syntax.
	VaultAPIVersion     APIVersion   // Optional. Defaults to v1
	HTTPClient          *http.Client // Uses default http client if nil
	KeyValueEngine      string
	TransitEngine       string
}

Config struct

func GetConfigInstance

func GetConfigInstance() Config

GetConfigInstance returns the config used by this instance

type ConfigResponse

type ConfigResponse struct {
	RequestID     string          `json:"request_id"`
	LeaseID       string          `json:"lease_id"`
	Renewable     bool            `json:"renewable"`
	LeaseDuration int             `json:"lease_duration"`
	WrapInfo      interface{}     `json:"wrap_info"`
	Warnings      []string        `json:"warnings"`
	Data          json.RawMessage `json:"data"`
}

ConfigResponse struct

type CreateTokenInstance

type CreateTokenInstance struct {
	ID              string            `json:"id,omitempty"`
	RoleName        string            `json:"role_name,omitempty"`
	Policies        []string          `json:"policies,omitempty"`
	Meta            map[string]string `json:"meta,omitempty"`
	NoParent        bool              `json:"no_parent,omitempty"`
	NoDefaultPolicy bool              `json:"no_default_policy,omitempty"`
	Renewable       bool              `json:"renewable,omitempty"`
	TTL             string            `json:"ttl,omitempty"`
	Type            string            `json:"type,omitempty"`
	ExplicitMaxTTL  string            `json:"explicit_max_ttl,omitempty"`
	DisplayName     string            `json:"display_name,omitempty"`
	NumUses         int               `json:"num_uses,omitempty"`
	EntityAlias     string            `json:"entity_alias,omitempty"`
	Period          string            `json:"period,omitempty"`
	// contains filtered or unexported fields
}

CreateTokenInstance struct to create token

func CreateNewToken

func CreateNewToken() *CreateTokenInstance

CreateNewToken creates an instance of Token override. Call “.Do(ctx)“ on the instance to actually create new token. Default value for instance follows vault token documentation, on here: https://www.vaultproject.io/api/auth/token#parameters

Which means the new token will be renewable by default and has display name of 'token'

func (*CreateTokenInstance) Do

func (c *CreateTokenInstance) Do(ctx context.Context) (token string, err error)

Do creates the token.

func (*CreateTokenInstance) DoOverride

func (c *CreateTokenInstance) DoOverride(ctx context.Context, authToken string) (token string, err error)

DoOverride creates the token, with passed token as auth and parent if orphan status is false (or no parent is true)

func (*CreateTokenInstance) WithCurrentTokenAsParent

func (c *CreateTokenInstance) WithCurrentTokenAsParent(b bool) *CreateTokenInstance

WithCurrentTokenAsParent Uses instance token as parent. Default true. If using DoOverride(token), the override token will be set as parent instead.

func (*CreateTokenInstance) WithDefaultPolicy

func (c *CreateTokenInstance) WithDefaultPolicy(b bool) *CreateTokenInstance

WithDefaultPolicy replaces instance default policy. by default true

func (*CreateTokenInstance) WithDisplayName

func (c *CreateTokenInstance) WithDisplayName(s string) *CreateTokenInstance

WithDisplayName replaces token display name

func (*CreateTokenInstance) WithEntityAlias

func (c *CreateTokenInstance) WithEntityAlias(s string) *CreateTokenInstance

WithEntityAlias replaces instance entity alias. MUST BE USED alongside WithRoleName and Role name must exist within vault.

func (*CreateTokenInstance) WithExplicitMaxTTL

func (c *CreateTokenInstance) WithExplicitMaxTTL(t time.Duration) *CreateTokenInstance

WithExplicitMaxTTL replaces instance explicit time to live, which by default will depends on Vault's default lease TTL If this method is called, duration will be rounded down to the nearest hour argument passed with minimum value of 1 hour

func (*CreateTokenInstance) WithID

WithID replaces instance ID. Make sure there's no character '.' in the argument string

func (*CreateTokenInstance) WithMeta

func (c *CreateTokenInstance) WithMeta(metadata map[string]string) *CreateTokenInstance

WithMeta replaces instance metadata

func (*CreateTokenInstance) WithNumberOfUses

func (c *CreateTokenInstance) WithNumberOfUses(i int) *CreateTokenInstance

WithNumberOfUses replaces token's allowed number of usage. Signing in to vault using UI with the token is considered used one time. By default 0, which is infinite.

func (*CreateTokenInstance) WithPeriod

WithPeriod replaces token period. Token that is not renewed in this set of time cannot be renewed again. By default, if unset will follow's Vault's default lease TTL. Has minimum value of 1 hour. Only hourly is supported in this package.

func (*CreateTokenInstance) WithPolicies

func (c *CreateTokenInstance) WithPolicies(policies ...string) *CreateTokenInstance

WithPolicies replaces instance policies

func (*CreateTokenInstance) WithRenewableStatus

func (c *CreateTokenInstance) WithRenewableStatus(b bool) *CreateTokenInstance

WithRenewableStatus replaces instance renewable. default true.

func (*CreateTokenInstance) WithRoleName

func (c *CreateTokenInstance) WithRoleName(rolename string) *CreateTokenInstance

WithRoleName replaces instance rolename.

func (*CreateTokenInstance) WithSetAsBatchToken

func (c *CreateTokenInstance) WithSetAsBatchToken() *CreateTokenInstance

WithSetAsBatchToken replaces instance token type

func (*CreateTokenInstance) WithSetAsServiceToken

func (c *CreateTokenInstance) WithSetAsServiceToken() *CreateTokenInstance

WithSetAsServiceToken replaces instance token type

func (*CreateTokenInstance) WithTimeToLive

func (c *CreateTokenInstance) WithTimeToLive(t time.Duration) *CreateTokenInstance

WithTimeToLive replaces instance time to live, which by default will depends on Vault's default lease TTL If this method is called, duration will be rounded down to the nearest hour argument passed with minimum value of 1 hour Only hourly is supported in this package.

type LookupToken

type LookupToken struct {
	Data struct {
		Accessor       string            `json:"accessor"`
		CreationTime   int64             `json:"creation_time"`
		CreationTTL    int64             `json:"creation_ttl"`
		DisplayName    string            `json:"display_name"`
		EntityID       string            `json:"entity_id"`
		ExpireTime     interface{}       `json:"expire_time"`
		ExplicitMaxTTL int64             `json:"explicit_max_ttl"`
		ID             string            `json:"id"` // This is the token auth
		Meta           map[string]string `json:"meta"`
		NumUses        int64             `json:"num_uses"`
		Orphan         bool              `json:"orphan"`
		Path           string            `json:"path"`
		Policies       []string          `json:"policies"`
		TTL            int64             `json:"ttl"`
		Type           string            `json:"type"`
	} `json:"data"`
	RequestID     string      `json:"request_id"`
	LeaseID       string      `json:"lease_id"`
	Renewable     bool        `json:"renewable"`
	LeaseDuration int64       `json:"lease_duration"`
	WrapInfo      interface{} `json:"wrap_info"`
	Warnings      []string    `json:"warnings"`
	Auth          interface{} `json:"auth"`
}

LookupToken token lookup

func LookupOther

func LookupOther(ctx context.Context, token string) (lookup LookupToken, err error)

LookupOther lookup information on current token used in the instance

func LookupSelf

func LookupSelf(ctx context.Context) (token LookupToken, err error)

LookupSelf lookup information on current token used in the instance

type OptionFunc

type OptionFunc func(options *Config)

OptionFunc opts

func WithAPIVersion

func WithAPIVersion(version APIVersion) OptionFunc

WithAPIVersion f

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) OptionFunc

WithHTTPClient f

func WithHost

func WithHost(hostname string) OptionFunc

WithHost f

func WithKeyValueEngine

func WithKeyValueEngine(engine string) OptionFunc

WithKeyValueEngine f

func WithTransitEngine

func WithTransitEngine(engine string) OptionFunc

WithTransitEngine f

type Options

type Options struct {
	Host            string       // Optional. Defaults to https://127.0.0.1:8200. Make sure to not add '/' in last character
	VaultAPIVersion APIVersion   // Optional. Defaults to v1
	HTTPClient      *http.Client // Uses default http client if nil
}

Options struct

type PolicyData

type PolicyData struct {
	Name   string `json:"name"`
	Policy string `json:"policy"`
}

PolicyData struct

func CheckPolicy

func CheckPolicy(ctx context.Context, policy string) (d PolicyData, err error)

CheckPolicy checks if policy exists and gets it's data

type PolicyResponse

type PolicyResponse struct {
	RequestID     string      `json:"request_id"`
	LeaseID       string      `json:"lease_id"`
	Renewable     bool        `json:"renewable"`
	LeaseDuration int         `json:"lease_duration"`
	WrapInfo      interface{} `json:"wrap_info"`
	Warnings      []string    `json:"warnings"`
	Data          PolicyData  `json:"data"`
}

PolicyResponse struct

type Vault

type Vault struct {
	BaseURL string
	Config  Config
}

Vault struct

func NewClient

func NewClient(token string, opts ...OptionFunc) (*Vault, error)

NewClient creates a new vault instance

func (*Vault) CheckPolicy

func (v *Vault) CheckPolicy(ctx context.Context, policy string) (d PolicyData, err error)

CheckPolicy checks if policy exists and gets it's data

func (*Vault) CreateNewToken

func (v *Vault) CreateNewToken() *CreateTokenInstance

CreateNewToken creates an instance of Token override. Call “.Do(ctx)“ on the instance to actually create new token. Default value for instance follows vault token documentation, on here: https://www.vaultproject.io/api/auth/token#parameters

Which means the new token will be renewable by default and has display name of 'token'

func (*Vault) GetConfig

func (v *Vault) GetConfig(ctx context.Context, path string) (data []byte, err error)
DEPRECATED. USE GetKeyValue instead.

GetConfig returns config from vault. The path format is '/{secret engine name}/{secret name}'

Example: `data, err := vault.GetConfig(context.Background(), "/kv/foo")`

func (*Vault) GetConfigLoad

func (v *Vault) GetConfigLoad(ctx context.Context, path string, model interface{}) (err error)
DEPRECATED. USE GetKeyValueLoad instead.

GetConfigLoad returns config and loaded into a variable The path format is '/{secret engine name}/{secret name}'

func (*Vault) GetEngineKeys

func (v *Vault) GetEngineKeys(ctx context.Context, engine string) (configs []string, err error)

GetEngineKeys returns list of keys for given engine

func (*Vault) GetKVEngine

func (v *Vault) GetKVEngine() string

GetKVEngine returns the engine name used for the instance

func (*Vault) GetKeyValue

func (v *Vault) GetKeyValue(ctx context.Context, key string) (data []byte, err error)

GetKeyValue returns key value store from vault. 'Key' is the key name. Like for example 'ms-order-conf'

func (*Vault) GetKeyValueLoad

func (v *Vault) GetKeyValueLoad(ctx context.Context, key string, model interface{}) (err error)

GetKeyValueLoad returns config and loaded into a variable 'Key' is the key name. Like for example 'ms-order-conf'

func (*Vault) GetTransitEngine

func (v *Vault) GetTransitEngine() string

GetTransitEngine returns the engine name used for the instance

func (*Vault) LookupOther

func (v *Vault) LookupOther(ctx context.Context, token string) (lookup LookupToken, err error)

LookupOther lookup information on passed token

func (*Vault) LookupSelf

func (v *Vault) LookupSelf(ctx context.Context) (lookup LookupToken, err error)

LookupSelf lookup information on current token used in the instance

func (*Vault) RenewTokenOther

func (v *Vault) RenewTokenOther(ctx context.Context, token string) (err error)

RenewTokenOther attempts to renew passed token using self's token

func (*Vault) RenewTokenOverride

func (v *Vault) RenewTokenOverride(ctx context.Context, token string) (err error)

RenewTokenOverride attempts to renew passed token with passed token as auth

func (*Vault) RenewTokenSelf

func (v *Vault) RenewTokenSelf(ctx context.Context) (err error)

RenewTokenSelf attempts to renew token registered to self. Cannot renew root token with 0 time to live (never expire).

func (*Vault) RevokeToken

func (v *Vault) RevokeToken(ctx context.Context, token string) (err error)

RevokeToken revokes given token string. Cannot revoke root token if instance token is not root If getting permission denied error, then it's most likely that reason.

func (*Vault) TransitDecrypt

func (v *Vault) TransitDecrypt(ctx context.Context, key, cipherText string) (data []byte, err error)

TransitDecrypt decrypts a transit encrypted payload. If decyprting a big ciphertext like if decrypted it's actually an image, please use TransitDecryptStream.

func (*Vault) TransitDecryptStream

func (v *Vault) TransitDecryptStream(ctx context.Context, key string, cipher io.Reader) (payload io.Reader, err error)

TransitDecryptStream decrypts a transit encrypted payload in streaming manner. Best usage is if you expect a big ciphertext from whatever your source is.

func (*Vault) TransitEncrypt

func (v *Vault) TransitEncrypt(ctx context.Context, key string, payload []byte) (cipherText string, err error)

TransitEncrypt will encrypt payload for sending somewhere else. 'key' is the encryptor name.

func (*Vault) TransitEncryptStream

func (v *Vault) TransitEncryptStream(ctx context.Context, key string, payload io.Reader) (io.Reader, error)

TransitEncryptStream will encrypt payload in stream manner to prevent memory overload on huge number of operation. Use this function for big files. The returned io Reader is a stream of pure encoded vault data without bells and whistles of JSON.

func (*Vault) UpsertKeyValue

func (v *Vault) UpsertKeyValue(ctx context.Context, key string, data interface{}) (err error)

UpsertKeyValue method

func (*Vault) UpsertPolicy

func (v *Vault) UpsertPolicy(ctx context.Context, policy string, permissions map[string][]Capability) (err error)

UpsertPolicy creates/updates a policy. Token used in the instance must have the permission to even update policy itself. Root token have all permissions

Jump to

Keyboard shortcuts

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