secrets

package
v0.9.17 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: BSD-3-Clause Imports: 17 Imported by: 1

Documentation

Overview

Package secrets provides the functionality to access secrets from Vault by reading them out of a JSON file with automatic refresh on change.

Store should be used to instantiate and configure the secret fetcher.

Index

Constants

View Source
const (
	// SimpleType secrets are basic string secrets.
	SimpleType = "simple"

	// VersionedType secrets are secrets that can be rotated gracefully.
	VersionedType = "versioned"

	// CredentialType secrets are username/password pairs as a single secret
	// in vault.
	CredentialType = "credential"
)
View Source
const (
	// JWTPubKeyPath is the expected key for the EdgeRequestContext public
	// key.
	JWTPubKeyPath = "secret/authentication/public-key"
)

Variables

View Source
var ErrEmptySecretKey = errors.New("secrets: secret path cannot be empty")

ErrEmptySecretKey is returned when the path for a secret is empty.

View Source
var ErrInvalidEncoding = errors.New("secrets: invalid encoding, expected identity, base64 or empty")

ErrInvalidEncoding is the error returned by the parser when we got an invalid encoding in the secrets.json file.

View Source
var TestJWTPubKeySecret = GenericSecret{
	Type: "versioned",
	Current: `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtzMnDEQPd75QZByogNlB
NY2auyr4sy8UNTDARs79Edq/Jw5tb7ub412mOB61mVrcuFZW6xfmCRt0ILgoaT66
Tp1RpuEfghD+e7bYZ+Q2pckC1ZaVPIVVf/ZcCZ0tKQHoD8EpyyFINKjCh516VrCx
KuOm2fALPB/xDwDBEdeVJlh5/3HHP2V35scdvDRkvr2qkcvhzoy0+7wUWFRZ2n6H
TFrxMHQoHg0tutAJEkjsMw9xfN7V07c952SHNRZvu80V5EEpnKw/iYKXUjCmoXm8
tpJv5kXH6XPgfvOirSbTfuo+0VGqVIx9gcomzJ0I5WfGTD22dAxDiRT7q7KZnNgt
TwIDAQAB
-----END PUBLIC KEY-----`,
}

TestJWTPubKeySecret is the default EdgeRequestContext public key secret set when using NewTestSecrets.

pubkey copied from: https://github.com/reddit/edgecontext.py/blob/420e58728ee7085a2f91c5db45df233142b251f9/tests/edge_context_tests.py#L11-L21

Functions

func UpdateTestSecrets added in v0.2.1

func UpdateTestSecrets(fw *filewatcher.MockFileWatcher, raw map[string]GenericSecret) error

UpdateTestSecrets replaces the secrets returned by the MockFileWatcher with the the given raw secrets.

Like NewTestSecrets, if you do not provide a value for the key defined by JWTPubKeyPath, then we will add a default secret for you.

Types

type CSIFile added in v0.9.12

type CSIFile struct {
	Secret GenericSecret `json:"data"`
}

CSIFile represents the raw parsed object of a file made by the Vault CSI provider

type Config

type Config struct {
	// Path is the path to the secrets.json file or Vault CSI directory to load
	// your service's secrets from.
	//
	// Examples:
	// - /var/local/secrets/secrets.json
	// - /mnt/secrets
	Path string `yaml:"path"`
}

Config is the confuration struct for the secrets package.

Can be deserialized from YAML.

type CredentialSecret

type CredentialSecret struct {
	Username string
	Password string
}

CredentialSecret represent represent username/password pairs as a single secret in vault. Note that usernames are not generally considered secret, but they are tied to passwords.

type Document

type Document struct {
	Secrets map[string]GenericSecret `json:"secrets"`
	Vault   Vault                    `json:"vault"`
}

Document represents the raw parsed entity of a Secrets JSON and is not meant to be used other than instantiating Secrets.

func (*Document) Validate

func (s *Document) Validate() error

Validate checks the Document for any errors that violate the Baseplate specification.

When this function returns a non-nil error, the error is either a TooManyFieldsError, or a BatchError containing multiple TooManyFieldsError.

type Encoding added in v0.2.1

type Encoding int

Encoding represents the Encoding used to encode a secret.

const (
	// IdentityEncoding indicates no encoding beyond JSON itself.
	IdentityEncoding Encoding = iota
	// Base64Encoding indicates that the secret is base64 encoded.
	Base64Encoding
)

func (Encoding) MarshalJSON added in v0.2.1

func (e Encoding) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON string representation of the encoding.

func (*Encoding) UnmarshalJSON added in v0.2.1

func (e *Encoding) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals the given JSON data into an encoding.

type GenericSecret

type GenericSecret struct {
	Type     string   `json:"type"`
	Value    string   `json:"value"`
	Encoding Encoding `json:"encoding"`

	Current  string `json:"current"`
	Previous string `json:"previous"`
	Next     string `json:"next"`

	Username string `json:"username"`
	Password string `json:"password"`
}

GenericSecret is a placeholder to fit all types of secrets when parsing the Secret JSON before processing them into their more typed equivalents.

type Secret

type Secret []byte

A Secret is the base type of secrets.

func (Secret) IsEmpty

func (s Secret) IsEmpty() bool

IsEmpty returns true if the secret is empty.

type SecretHandlerFunc

type SecretHandlerFunc func(sec *Secrets)

SecretHandlerFunc is the actual function that works with the Secrets

type SecretMiddleware

type SecretMiddleware func(next SecretHandlerFunc) SecretHandlerFunc

SecretMiddleware creates chain of SecretHandlerFunc calls

type SecretNotFoundError

type SecretNotFoundError string

SecretNotFoundError is returned when the key for a secret is not present in the secret store.

func (SecretNotFoundError) Error

func (path SecretNotFoundError) Error() string

type SecretWrongTypeError added in v0.9.17

type SecretWrongTypeError struct {
	Path         string
	DeclaredType string
	CorrectType  string
}

func (SecretWrongTypeError) Error added in v0.9.17

func (e SecretWrongTypeError) Error() string

type Secrets

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

Secrets allows to access secrets based on their different type.

func FromDir added in v0.9.12

func FromDir(dir fs.FS) (*Secrets, error)

FromDir parses a directory and returns its secrets

func NewSecrets

func NewSecrets(r io.Reader) (*Secrets, error)

NewSecrets parses and validates the secret JSON provided by the reader.

func (*Secrets) GetCredentialSecret

func (s *Secrets) GetCredentialSecret(path string) (CredentialSecret, error)

GetCredentialSecret fetches a credential secret or error if the key is not present.

func (*Secrets) GetSimpleSecret

func (s *Secrets) GetSimpleSecret(path string) (SimpleSecret, error)

GetSimpleSecret fetches a simple secret or error if the key is not present.

func (*Secrets) GetVersionedSecret

func (s *Secrets) GetVersionedSecret(path string) (VersionedSecret, error)

GetVersionedSecret fetches a versioned secret or error if the key is not present.

type SimpleSecret

type SimpleSecret struct {
	Value Secret
}

SimpleSecret represent basic secrets.

func (SimpleSecret) AsVersioned

func (s SimpleSecret) AsVersioned() VersionedSecret

AsVersioned returns the SimpleSecret as a VersionedSecret.

The Value of the SimpleSecret will be set as the Current value on the VersionedSecret.

type Store

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

Store gives access to secret tokens with automatic refresh on change.

This local vault allows access to the secrets cached on disk by the fetcher daemon. It will automatically reload the cache when it is changed. Do not cache or store the values returned by this class's methods but rather get them from this class each time you need them. The secrets are served from memory so there's little performance impact to doing so and you will be sure to always have the current version in the face of key rotation etc.

func InitFromConfig

func InitFromConfig(ctx context.Context, cfg Config) (*Store, error)

InitFromConfig returns a new *secrets.Store using the given context and config.

func NewStore

func NewStore(ctx context.Context, path string, logger log.Wrapper, middlewares ...SecretMiddleware) (*Store, error)

NewStore returns a new instance of Store by configuring it with a filewatcher to watch the file in path for changes ensuring secrets store will always return up to date secrets.

Context should come with a timeout otherwise this might block forever, i.e. if the path never becomes available.

func NewTestSecrets added in v0.2.1

func NewTestSecrets(ctx context.Context, raw map[string]GenericSecret, middlewares ...SecretMiddleware) (*Store, *filewatcher.MockFileWatcher, error)

NewTestSecrets returns a SecretsStore using the raw map of key to GenericSecrets as well as the MockFileWatcher that is used to hold the test secrets.

This is provided to aid in testing and should not be used to create production secrets.

If you do not provide a value for the key defined by JWTPubKeyPath, then we will add a default secret for you.

func (*Store) AddMiddlewares

func (s *Store) AddMiddlewares(middlewares ...SecretMiddleware)

AddMiddlewares registers new middlewares to the store.

Every AddMiddlewares call will cause all already registered middlewares to be called again with the latest data.

AddMiddlewares call is not thread-safe, it should not be called concurrently.

func (*Store) Close

func (s *Store) Close() error

Close closes the underlying filewatcher and release associated resources.

After Close is called, you won't get any updates to the secret file, but can still access the secrets as they were before Close is called.

It's OK to call Close multiple times. Calls after the first one are no-ops.

Close doesn't return non-nil errors, but implements io.Closer.

func (*Store) GetCredentialSecret

func (s *Store) GetCredentialSecret(path string) (CredentialSecret, error)

GetCredentialSecret loads secrets from watcher, and fetches a credential secret from secrets

func (*Store) GetSimpleSecret

func (s *Store) GetSimpleSecret(path string) (SimpleSecret, error)

GetSimpleSecret loads secrets from watcher, and fetches a simple secret from secrets

func (*Store) GetVault

func (s *Store) GetVault() (Vault, error)

GetVault returns a struct with a URL and token to access Vault directly. The token will have policies attached based on the current EC2 server's Vault role. This is only necessary if talking directly to Vault.

This function always returns nil error.

func (*Store) GetVersionedSecret

func (s *Store) GetVersionedSecret(path string) (VersionedSecret, error)

GetVersionedSecret loads secrets from watcher, and fetches a versioned secret from secrets

type TooManyFieldsError

type TooManyFieldsError struct {
	Key        string
	SecretType string
}

TooManyFieldsError is a type of errors could be returned by Document.Validate.

Note that Document.Validate could also return a BatchError containing multiple TooManyFieldsError.

func (TooManyFieldsError) Error

func (e TooManyFieldsError) Error() string

type Vault

type Vault struct {
	URL   string `json:"url"`
	Token string `json:"token"`
}

Vault provides authentication credentials so that applications can directly connect to Vault for more complicated use cases.

type VersionedSecret

type VersionedSecret struct {
	Current  Secret
	Previous Secret
	Next     Secret
}

VersionedSecret represent secrets like signing keys that can be rotated gracefully.

The current property contains the active version of a secret. This should be used for any actions that generate new cryptographic data (e.g. signing a token).

The previous and next fields contain old and not-yet-active versions of the secret respectively. These MAY be used by applications to give a grace period for cryptographic tokens generated during a rotation, but SHOULD NOT be used to generate new cryptographic tokens.

func (*VersionedSecret) GetAll

func (v *VersionedSecret) GetAll() []Secret

GetAll returns all versions that are not empty in the following order: current, previous, next.

Jump to

Keyboard shortcuts

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