vault

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 21 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Vault

GitHub release Go Reference

A flexible Go library for secure secret management with multiple backend providers. Made for flow but can be used independently.

Features

  • Multiple Provider Support: Choose from local encrypted storage, system keyring, or external CLI tools
  • Pluggable Architecture: Easy to extend with custom providers
  • Type Safety: Strong typing for secrets with secure memory handling
  • Thread Safe: Concurrent access protection with read/write mutexes
  • Comprehensive API: Full CRUD operations plus metadata and existence checks

Quick Start

package main

import (
    "fmt"
    "github.com/flowexec/vault"
)

func main() {
    // Create a new AES vault
    v, err := vault.New("my-vault",
        vault.WithProvider(vault.ProviderTypeAES256),
        vault.WithLocalPath("/path/to/vault/storage"),
        vault.WithAESKeyFromEnv("VAULT_KEY"),
    )
    if err != nil {
        panic(err)
    }
    defer v.Close()

    // Store a secret
    secret := vault.NewSecretValue([]byte("my-secret-value"))
    err = v.SetSecret("api-key", secret)
    if err != nil {
        panic(err)
    }

    // Retrieve a secret
    retrieved, err := v.GetSecret("api-key")
    if err != nil {
        panic(err)
    }
    fmt.Println("Secret:", retrieved.PlainTextString())
}

Provider Types

Local Encrypted Providers
AES256 Provider

Stores secrets in an AES-256 encrypted file with configurable key sources.

provider, _, err := vault.New("my-vault",
    vault.WithProvider(vault.ProviderTypeAES256),
    vault.WithAESPath("~/.config/flow/vaults"), // a directory, not a file
)

Key Generation:

key, err := vault.GenerateEncryptionKey()
// Store this key securely (environment variable, HSM, etc.)
Age Provider

Uses the age encryption tool with public key cryptography.

provider, _, err := vault.New("my-vault",
    vault.WithProvider(vault.ProviderTypeAge),
    vault.WithAgePath("~/.config/flow/vaults"), // a directory, not a file
)

Key Generation:

age-keygen -o ~/.age/identity.txt
# Add recipients to vault configuration
Keyring Provider

Integrates with the operating system's secure keyring.

provider, _, err := vault.New("my-vault",
    vault.WithProvider(vault.ProviderTypeKeyring),
    vault.WithKeyringService("my-app-secrets"),
)

No additional setup required - uses OS authentication.

Unencrypted Provider

Stores secrets in plain text JSON files.

provider, _, err := vault.New("my-vault",
    vault.WithProvider(vault.ProviderTypeUnencrypted),
    vault.WithUnencryptedPath("~/.config/flow/vaults"), // a directory, not a file
)
External CLI Providers
External Provider

Reads secrets that live in another tool — 1Password, pass, AWS SSM, Bitwarden — through that tool's CLI.

An external vault is a read-through registry, not a store. It holds a set of links: a key you choose, paired with a reference the provider understands. Reading a key resolves its reference and runs the get command. Nothing is ever written back.

config := &vault.Config{
    ID:   "work",
    Type: vault.ProviderTypeExternal,
    External: &vault.ExternalConfig{
        Get: vault.CommandConfig{
            CommandTemplate: "op read --no-newline '{{ref}}' && echo", // exactly one trailing newline, which GetSecret strips
        },
        // Where the link registry is kept.
        StoragePath: "~/.config/flow/vaults",
        // Catches a mistyped reference at link time rather than at read time.
        ReferencePattern: `^op://[^/]+/[^/]+/[^/]+$`,
    },
}

provider, _ := vault.NewExternalVaultProvider(config)

// Point a key at something that already exists. Note the field on the end:
// one item's several credentials are addressed individually.
links := provider.(vault.ReferenceVault)
_ = links.Link("aws-access-key", "op://Team/AWS/access_key_id")
_ = links.Link("aws-secret-key", "op://Team/AWS/secret_access_key")

secret, _ := provider.GetSecret("aws-access-key")

Because the key is a local alias, you never have to reorganise the store you are pointing at, and because a reference names a field, one item's several credentials are individually reachable.

Reads only. SetSecret returns ErrReadOnly, and DeleteSecret removes the link — the secret in the provider is untouched. Create secrets in the tool that owns them.

This is deliberate. Writing through meant handing the value to a provider CLI, and none of them accept one safely: 1Password takes it as an argv assignment, visible to every process on the machine. It also meant a delete that destroyed real data, and a set that rebuilt an item from scratch, dropping whatever else was on it.

References are validated before they reach a shell — no quotes, backticks, $, backslashes, control characters, leading dashes or .. segments — on the way in and on the way out, since a registry is a file that can be hand-edited.

External Provider Examples

Ready-to-use configurations for popular CLI tools are available in the examples/ directory:

See the examples README for detailed setup instructions.

Usage

Basic Operations
// Store a secret
secret := vault.NewSecretValue([]byte("my-secret-value"))
err = provider.SetSecret("api-key", secret)

// Retrieve the secret
retrieved, err := provider.GetSecret("api-key")
fmt.Println("Secret:", retrieved.PlainTextString())

// List all secrets
secrets, _ := provider.ListSecrets()

// Check if secret exists
exists, _ := provider.HasSecret("api-key")

// Get vault metadata
metadata, err := provider.Metadata()
Configuration from File
// Load configuration from JSON
config, err := vault.LoadConfigJSON("vault-config.json")
provider, _, err := vault.New(config.ID, vault.WithProvider(config.Type))

Documentation

Index

Constants

View Source
const DefaultVaultKeyEnv = "VAULT_KEY"

DefaultVaultKeyEnv is the environment variable consulted when no key source is configured. A const rather than a var: as a package-level var, any dependency could repoint every default key lookup in the process.

Variables

View Source
var (
	ErrSecretNotFound   = errors.New("secret not found")
	ErrInvalidKey       = errors.New("invalid secret key")
	ErrNoAccess         = errors.New("access denied")
	ErrInvalidConfig    = errors.New("invalid configuration")
	ErrVaultNotFound    = errors.New("vault not found")
	ErrDecryptionFailed = errors.New("decryption failed")
	ErrInvalidRecipient = errors.New("invalid recipient")
	ErrPathNotSecure    = errors.New("path is not secure")
	ErrVaultClosed      = errors.New("vault is closed")
	ErrVaultCorrupt     = errors.New("vault file is corrupt")
	// ErrReadOnly is returned by a vault that never writes secret material. An
	// external vault holds references to secrets kept in another system; the way
	// to add one is to link it, and the way to create one is to create it in that
	// system.
	ErrReadOnly = errors.New("vault is read-only")
	// ErrInvalidReference is returned when a reference is malformed or would be
	// unsafe to interpolate into a provider command.
	ErrInvalidReference = errors.New("invalid secret reference")
)

Functions

func DeriveEncryptionKey

func DeriveEncryptionKey(passphrase, sal string) (string, string, error)

DeriveEncryptionKey derives an AES encryption key from a passphrase.

An empty sal requests a freshly generated salt. Pass the returned salt back verbatim to re-derive the same key; it carries the parameters it was made with, so future changes to the defaults cannot alter an existing key.

func GenerateEncryptionKey

func GenerateEncryptionKey() (string, error)

GenerateEncryptionKey generates a new AES encryption key

func New

func New(id string, opts ...Option) (Provider, *Config, error)

New creates a new vault instance with the provided ID and options

func SaveConfigJSON

func SaveConfigJSON(config Config, path string) error

SaveConfigJSON saves the vault configuration to a file in JSON format

func ValidateEncryptionKey

func ValidateEncryptionKey(key string) error

ValidateEncryptionKey checks if a key is valid by attempting to encrypt/decrypt test data

func ValidateSecretKey

func ValidateSecretKey(reference string) error

func ValidateVaultID added in v0.3.0

func ValidateVaultID(id string) error

ValidateVaultID checks an identifier that will be used to build filesystem paths and keyring entry names.

Types

type AES256Vault

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

AES256Vault manages operations on an instance of a local vault backed by AES256 symmetric encryption.

func NewAES256Vault

func NewAES256Vault(cfg *Config) (*AES256Vault, error)

func (*AES256Vault) Close

func (v *AES256Vault) Close() error

func (*AES256Vault) DeleteSecret

func (v *AES256Vault) DeleteSecret(key string) error

func (*AES256Vault) GetSecret

func (v *AES256Vault) GetSecret(key string) (Secret, error)

func (*AES256Vault) HasSecret

func (v *AES256Vault) HasSecret(key string) (bool, error)

func (*AES256Vault) ID

func (v *AES256Vault) ID() string

func (*AES256Vault) ListSecrets

func (v *AES256Vault) ListSecrets() ([]string, error)

func (*AES256Vault) Metadata

func (v *AES256Vault) Metadata() (Metadata, error)

func (*AES256Vault) SetSecret

func (v *AES256Vault) SetSecret(key string, secret Secret) error

type AESState

type AESState struct {
	Metadata `yaml:"metadata"`

	// yaml, not json: this struct is marshaled with gopkg.in/yaml.v3, which
	// ignores json tags and would otherwise have keyed this field as "version"
	// only by lowercasing coincidence.
	Version int               `yaml:"version"`
	ID      string            `yaml:"id"`
	Secrets map[string]string `yaml:"secrets"`
}

AESState represents the state of the local AES256 vault.

type AesConfig

type AesConfig struct {
	// Storage location for the vault file
	StoragePath string `json:"storage_path"`
	// DEK sources for decryption (in order of preference)
	KeySource []KeySource `json:"key_sources,omitempty"`
}

AesConfig contains local (AES256-based) vault configuration

func (*AesConfig) Validate

func (c *AesConfig) Validate() error

type AgeConfig

type AgeConfig struct {
	// Storage location for the vault file
	StoragePath string `json:"storage_path"`

	// Identity sources for decryption (in order of preference)
	IdentitySources []IdentitySource `json:"identity_sources,omitempty"`

	// Recipients who can decrypt secrets
	Recipients []string `json:"recipients,omitempty"`
}

AgeConfig contains local (age-based) vault configuration

func (*AgeConfig) Validate

func (c *AgeConfig) Validate() error

type AgeState

type AgeState struct {
	Metadata `json:"metadata"`

	Version    int               `json:"version"`
	ID         string            `json:"id"`
	Recipients []string          `json:"recipients"`
	Secrets    map[string]string `json:"secrets"`
}

AgeState represents the state of the local age vault

type AgeVault

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

AgeVault manages operations on an instance of a local vault backed by age encryption.

func NewAgeVault

func NewAgeVault(cfg *Config) (*AgeVault, error)

func (*AgeVault) AddRecipient

func (v *AgeVault) AddRecipient(publicKey string) error

func (*AgeVault) Close

func (v *AgeVault) Close() error

func (*AgeVault) DeleteSecret

func (v *AgeVault) DeleteSecret(key string) error

func (*AgeVault) GetSecret

func (v *AgeVault) GetSecret(key string) (Secret, error)

func (*AgeVault) HasSecret

func (v *AgeVault) HasSecret(key string) (bool, error)

func (*AgeVault) ID

func (v *AgeVault) ID() string

func (*AgeVault) ListRecipients

func (v *AgeVault) ListRecipients() ([]string, error)

func (*AgeVault) ListSecrets

func (v *AgeVault) ListSecrets() ([]string, error)

func (*AgeVault) Metadata

func (v *AgeVault) Metadata() (Metadata, error)

func (*AgeVault) RemoveRecipient

func (v *AgeVault) RemoveRecipient(publicKey string) error

func (*AgeVault) SetSecret

func (v *AgeVault) SetSecret(key string, value Secret) error

type CommandConfig added in v0.2.0

type CommandConfig struct {
	// CommandTemplate for building command arguments
	CommandTemplate string `json:"cmd"`
	// OutputTemplate for parsing command output
	OutputTemplate string `json:"output,omitempty"`
	// InputTemplate for providing input to the command
	InputTemplate string `json:"input,omitempty"`
}

CommandConfig represents a command template to be executed with its arguments

type Config

type Config struct {
	ID          string             `json:"id"`
	Type        ProviderType       `json:"type"`
	Age         *AgeConfig         `json:"age,omitempty"`
	Aes         *AesConfig         `json:"aes,omitempty"`
	External    *ExternalConfig    `json:"external,omitempty"`
	Keyring     *KeyringConfig     `json:"keyring,omitempty"`
	Unencrypted *UnencryptedConfig `json:"unencrypted,omitempty"`
	// contains filtered or unexported fields
}

func LoadConfigJSON

func LoadConfigJSON(path string) (Config, error)

LoadConfigJSON loads the vault configuration from a file in JSON format

func (*Config) Validate

func (c *Config) Validate() error

type ExternalConfig

type ExternalConfig struct {
	// Get resolves a reference to a secret value. Its command template receives
	// {{ ref }} (the reference) and {{ key }} (the alias).
	Get CommandConfig `json:"get,omitempty"`
	// Metadata CommandConfig for the metadata operation
	Metadata CommandConfig `json:"metadata,omitempty"`

	// StoragePath is the directory holding this vault's link registry.
	//
	// Not required by Validate: a config authored by hand or rendered from a
	// preset does not know where the consuming tool keeps vault state, so the
	// tool fills this in before constructing the provider. It is required at
	// construction, where a missing value is a real error rather than a
	// half-configured file on disk.
	StoragePath string `json:"storage_path,omitempty"`

	// ReferencePattern constrains what a reference may look like for this
	// provider, as a regular expression. It is a usability gate that catches a
	// mistyped reference at link time rather than at read time; the safety rules
	// in validateReference apply regardless of what it permits.
	ReferencePattern string `json:"reference_pattern,omitempty"`

	// Source records which preset generated this config, for the generator's own
	// use. Opaque to the library.
	Source *SourceRef `json:"source,omitempty"`

	// Environment variables for commands
	Environment map[string]string `json:"environment,omitempty"`

	// Timeout duration string for command execution
	Timeout string `json:"timeout,omitempty"`

	// WorkingDir for command execution
	WorkingDir string `json:"working_dir,omitempty"`

	// NotFoundPattern is matched against a failing command's error output to tell
	// "this secret does not exist" apart from a real failure (an expired session,
	// a network error, a permissions problem). Without it, any non-zero exit is
	// read as absence. Example: "ParameterNotFound".
	NotFoundPattern string `json:"not_found_pattern,omitempty"`

	// Legacy write-era fields. Parsed so a pre-v0.4.0 config still unmarshals
	// instead of failing at load, and reported as inert by Validate. Set and
	// Delete are never executed. List is read by MigrateLegacyLinks, which is the
	// one place a legacy config still has something useful to say: it can name
	// the keys that used to exist so they can be seeded as links.
	LegacySet           CommandConfig `json:"set,omitempty"`
	LegacyDelete        CommandConfig `json:"delete,omitempty"`
	LegacyList          CommandConfig `json:"list,omitempty"`
	LegacyListSeparator string        `json:"separator,omitempty"`
	LegacyExists        CommandConfig `json:"exists,omitempty"`
}

ExternalConfig contains external (cli command-based) vault configuration.

An external vault is a read-through registry, not a store. It holds a set of links -- an alias paired with a reference the provider's CLI understands, such as an op:// URI, a pass entry path or an SSM parameter name -- and resolves them by running Get. It never writes secret material anywhere.

That is why there is only a get command here. Writing through to a provider meant either interpolating the secret into a shell command or handing it to a CLI as an argv element, and it meant a delete that destroyed real data. Both are gone: a secret is created in the tool that owns it, and removing a link removes only the link.

func (*ExternalConfig) LegacyWriteCommands added in v0.4.0

func (c *ExternalConfig) LegacyWriteCommands() []string

LegacyWriteCommands returns the names of the inert write-era commands present in this config, so a caller can tell the user they are being ignored.

func (*ExternalConfig) Validate

func (c *ExternalConfig) Validate() error

type ExternalVaultProvider

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

func NewExternalVaultProvider added in v0.2.0

func NewExternalVaultProvider(cfg *Config) (*ExternalVaultProvider, error)

func (*ExternalVaultProvider) Close

func (v *ExternalVaultProvider) Close() error

func (*ExternalVaultProvider) DeleteSecret

func (v *ExternalVaultProvider) DeleteSecret(key string) error

DeleteSecret removes a link. The referenced secret is not touched.

This is the one method whose meaning differs from the other providers: on an aes or age vault Delete destroys secret material, and here it only forgets where something is. That asymmetry is the point -- an external vault points at data it does not own, and a vault should not be able to destroy a colleague's 1Password item because someone tidied up a key list. Callers that phrase a confirmation prompt should say "unlink", not "delete".

func (*ExternalVaultProvider) GetSecret

func (v *ExternalVaultProvider) GetSecret(key string) (Secret, error)

func (*ExternalVaultProvider) HasSecret

func (v *ExternalVaultProvider) HasSecret(key string) (bool, error)

HasSecret reports whether a key is linked.

Registry lookup only: it deliberately does not verify that the reference still resolves. That would spawn a provider process and reach the network to answer a boolean, and callers use this on paths where that cost is not expected. A link whose target has been deleted in the provider surfaces at GetSecret, which is where the caller is already prepared to wait and to handle failure.

func (*ExternalVaultProvider) ID

func (v *ExternalVaultProvider) ID() string
func (v *ExternalVaultProvider) Link(key, reference string) error
func (v *ExternalVaultProvider) Links() (map[string]string, error)

func (*ExternalVaultProvider) ListSecrets

func (v *ExternalVaultProvider) ListSecrets() ([]string, error)

ListSecrets returns the linked keys, sorted.

These are the vault's contents, not the provider's. A vault knows about what has been linked into it; the provider's full inventory is a separate question and browsing it is a job for a discovery command, not for a list of secrets the caller can actually resolve.

func (*ExternalVaultProvider) Metadata added in v0.2.0

func (v *ExternalVaultProvider) Metadata() (Metadata, error)
func (v *ExternalVaultProvider) MigrateLegacyLinks() ([]string, error)

MigrateLegacyLinks seeds the registry from a pre-v0.4.0 config's list command, mapping every key the backend reports to itself.

Before v0.4.0 an external vault addressed secrets by key directly, so the keys a legacy vault knows about are also valid references for it: linking each to its own name reproduces the old behaviour exactly, and the links can then be re-pointed at wherever those secrets actually live.

This is deliberately explicit rather than something that happens on first open. It runs the provider's list command, which reaches the network and can raise a biometric prompt; doing that implicitly because a UI happened to render a vault list would be a surprise with no obvious cause.

Existing links are never overwritten, so running it twice is safe.

func (*ExternalVaultProvider) Reference added in v0.4.0

func (v *ExternalVaultProvider) Reference(key string) (string, error)

func (*ExternalVaultProvider) SetContext added in v0.3.0

func (v *ExternalVaultProvider) SetContext(ctx context.Context)

SetContext replaces the context used for command execution, allowing callers to cancel in-flight operations. The Provider interface does not thread a context through its methods, so this is the supported way to make external commands cancellable.

func (*ExternalVaultProvider) SetExecutionFunc added in v0.2.0

func (v *ExternalVaultProvider) SetExecutionFunc(
	fn func(ctx context.Context, cmd, input, dir string, envList []string) (string, error),
)

func (*ExternalVaultProvider) SetSecret

func (v *ExternalVaultProvider) SetSecret(_ string, _ Secret) error

SetSecret always fails. An external vault resolves references to secrets kept in another system and never writes to it.

This is not a missing feature. Writing through meant handing the value to a provider CLI, and no supported provider accepts one safely: 1Password takes it as an argv assignment, visible to every process on the machine. It also meant a set that rebuilt an item from scratch, discarding whatever else was on it.

func (v *ExternalVaultProvider) Unlink(key string) error

type IdentityResolver

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

func NewIdentityResolver

func NewIdentityResolver(sources []IdentitySource) *IdentityResolver

func (*IdentityResolver) ResolveIdentities

func (r *IdentityResolver) ResolveIdentities() ([]age.Identity, error)

type IdentitySource

type IdentitySource struct {
	// Type of identity source
	// Must be one of: "env", "file"
	Type string `json:"type"`
	// Path to the identity file (for "file" type)
	Path string `json:"fullPath,omitempty"`
	// Environment variable name (for "env" type)
	Name string `json:"name,omitempty"`
}

IdentitySource represents a source for the local vault identity keys

type KeyResolver

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

func NewKeyResolver

func NewKeyResolver(sources []KeySource) *KeyResolver

func (*KeyResolver) ResolveKeys

func (r *KeyResolver) ResolveKeys() ([]string, error)

func (*KeyResolver) TryDecrypt

func (r *KeyResolver) TryDecrypt(encryptedData string) (string, string, error)

type KeySource

type KeySource struct {
	// Type of data encryption key source
	// Must be one of: "env", "file"
	Type string `json:"type"`
	// Path to the identity file (for "file" type)
	Path string `json:"fullPath,omitempty"`
	// Environment variable name (for "env" type)
	Name string `json:"name,omitempty"`
}

KeySource represents a source for the local vault encryption keys

type KeyringConfig added in v0.2.0

type KeyringConfig struct {
	// Service name used for keyring operations
	Service string `json:"service"`
}

KeyringConfig contains keyring vault configuration

func (*KeyringConfig) Validate added in v0.2.0

func (c *KeyringConfig) Validate() error

type KeyringVault added in v0.2.0

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

KeyringVault manages operations on a keyring-based vault that stores secrets in the system keyring.

func NewKeyringVault added in v0.2.0

func NewKeyringVault(cfg *Config) (*KeyringVault, error)

func (*KeyringVault) Close added in v0.2.0

func (v *KeyringVault) Close() error

func (*KeyringVault) DeleteSecret added in v0.2.0

func (v *KeyringVault) DeleteSecret(key string) error

func (*KeyringVault) GetSecret added in v0.2.0

func (v *KeyringVault) GetSecret(key string) (Secret, error)

func (*KeyringVault) HasSecret added in v0.2.0

func (v *KeyringVault) HasSecret(key string) (bool, error)

func (*KeyringVault) ID added in v0.2.0

func (v *KeyringVault) ID() string

func (*KeyringVault) ListSecrets added in v0.2.0

func (v *KeyringVault) ListSecrets() ([]string, error)

func (*KeyringVault) Metadata added in v0.2.0

func (v *KeyringVault) Metadata() (Metadata, error)

func (*KeyringVault) SetSecret added in v0.2.0

func (v *KeyringVault) SetSecret(key string, secret Secret) error

type Metadata

type Metadata struct {
	Created      time.Time `json:"created"`
	LastModified time.Time `json:"lastModified"`
	RawData      string    `json:"data,omitempty"`
}

type Option

type Option func(*Config)

func WithAESKeyFromEnv

func WithAESKeyFromEnv(envVar string) Option

WithAESKeyFromEnv specifies to retrieve the AES key from an environment variable

func WithAESKeyFromFile

func WithAESKeyFromFile(path string) Option

WithAESKeyFromFile specifies to retrieve the AES key from a file

func WithAESPath

func WithAESPath(path string) Option

WithAESPath sets the AES vault storage path

func WithAgeIdentityFromEnv

func WithAgeIdentityFromEnv(envVar string) Option

WithAgeIdentityFromEnv specifies to retrieve the age identity from an environment variable

func WithAgeIdentityFromFile

func WithAgeIdentityFromFile(path string) Option

WithAgeIdentityFromFile specifies to retrieve the age identity from a file

func WithAgePath

func WithAgePath(path string) Option

WithAgePath sets the age vault storage path

func WithAgeRecipients

func WithAgeRecipients(recipients ...string) Option

WithAgeRecipients sets the recipients for age vaults

func WithExternalConfig

func WithExternalConfig(cfg *ExternalConfig) Option

WithExternalConfig sets the external vault configuration. FOR TESTING PURPOSES ONLY. TODO: break this down when the external provider is fully implemented

func WithKeyringService added in v0.2.0

func WithKeyringService(service string) Option

WithKeyringService sets the keyring service name

func WithLocalPath

func WithLocalPath(path string) Option

WithLocalPath sets the local vault storage path (works for Age, AES, and Unencrypted based on provider type).

The path is applied once all options have been processed, so it does not matter whether WithProvider is passed before or after it. Previously this switched on c.Type immediately and was a silent no-op unless WithProvider happened to come first, surfacing later as "storage path is required".

func WithProvider

func WithProvider(provider ProviderType) Option

WithProvider sets the vault provider type

func WithUnencryptedPath added in v0.2.0

func WithUnencryptedPath(path string) Option

WithUnencryptedPath sets the unencrypted vault storage path

type Provider

type Provider interface {
	GetSecret(key string) (Secret, error)
	SetSecret(key string, value Secret) error
	DeleteSecret(key string) error
	ListSecrets() ([]string, error)
	HasSecret(key string) (bool, error)

	// ID returns a unique identifier for this vault instance
	ID() string

	// Metadata returns vault metadata such as creation time. It returns an error
	// rather than a zero value so that a failing backend command, a timeout, and
	// "no metadata configured" stay distinguishable.
	Metadata() (Metadata, error)

	Close() error
}

type ProviderType

type ProviderType string
const (
	ProviderTypeAES256      ProviderType = "aes256"
	ProviderTypeAge         ProviderType = "age"
	ProviderTypeExternal    ProviderType = "external"
	ProviderTypeKeyring     ProviderType = "keyring"
	ProviderTypeUnencrypted ProviderType = "unencrypted"
)

type RecipientManager

type RecipientManager interface {
	AddRecipient(identity string) error
	RemoveRecipient(identity string) error
	ListRecipients() ([]string, error)
}

func HasRecipientManagement

func HasRecipientManagement(v Provider) (RecipientManager, bool)

type ReferenceVault added in v0.4.0

type ReferenceVault interface {
	// Link points key at reference, replacing any existing link for that key.
	Link(key, reference string) error
	// Unlink removes a key's link. The referenced secret is untouched.
	Unlink(key string) error
	// Reference returns the reference a key points at.
	Reference(key string) (string, error)
	// Links returns a copy of the whole registry.
	Links() (map[string]string, error)
}

ReferenceVault is implemented by vaults that hold references to secrets kept somewhere else rather than the secret material itself.

Each entry pairs a key -- the alias the rest of the system uses -- with a reference the provider's CLI understands: an op:// URI, a pass entry path, an SSM parameter name. Reads resolve the alias and then read through. Because the alias is free, a caller never has to reorganise the store it is pointing at, and because a reference names a field as well as an item, one item's several credentials are individually addressable.

Callers obtain this by type-asserting a Provider.

type Secret

type Secret interface {
	// PlainTextString returns the decrypted value as a string
	PlainTextString() string

	// String returns a masked representation for display
	String() string

	// Bytes returns the raw byte representation of the secret
	Bytes() []byte

	// Zero securely clears the secret from memory
	Zero()
}

type SecretValue

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

func NewSecretValue

func NewSecretValue(value []byte) *SecretValue

func (*SecretValue) Bytes

func (s *SecretValue) Bytes() []byte

func (*SecretValue) PlainTextString

func (s *SecretValue) PlainTextString() string

PlainTextString returns the secret as a string.

The result is an immutable Go string and therefore cannot be zeroed; Zero() on this SecretValue will not reclaim it. Keep the returned value as short-lived as possible, and prefer Bytes() when the caller can clear it.

func (SecretValue) String

func (s SecretValue) String() string

String masks the secret so it cannot be printed by accident.

Deliberately a value receiver: with a pointer receiver, formatting a dereferenced copy (fmt.Sprintf("%v", *secret)) falls outside the method set and prints the raw bytes instead of the mask.

func (*SecretValue) Zero

func (s *SecretValue) Zero()

type SecureBytes

type SecureBytes []byte

SecureBytes is a wrapper around []byte that provides secure memory handling

func (SecureBytes) Copy

func (s SecureBytes) Copy() SecureBytes

Copy creates a secure copy of the bytes

func (*SecureBytes) Zero

func (s *SecureBytes) Zero()

Zero clears the byte slice.

Note on what this can and cannot guarantee: it overwrites *this* buffer only. Any Go string derived from it (see PlainTextString) is immutable and cannot be zeroed, and the runtime may have copied the backing array during a heap move. Treat this as reducing exposure, not eliminating it.

type SourceRef added in v0.4.0

type SourceRef struct {
	Name   string            `json:"name"`
	Values map[string]string `json:"values,omitempty"`
}

SourceRef records which generator produced a configuration. The library never interprets it; it exists so a tool that renders configs from presets can recognise its own output later and re-run preset-specific work (a readiness check, a discovery browse) against an already-created vault.

type UnencryptedConfig added in v0.2.0

type UnencryptedConfig struct {
	// Storage location for the vault file
	StoragePath string `json:"storage_path"`
}

UnencryptedConfig contains unencrypted (plain text) vault configuration

func (*UnencryptedConfig) Validate added in v0.2.0

func (c *UnencryptedConfig) Validate() error

type UnencryptedState added in v0.2.0

type UnencryptedState struct {
	Metadata `json:"metadata"`

	Version int               `json:"version"`
	ID      string            `json:"id"`
	Secrets map[string]string `json:"secrets"`
}

UnencryptedState represents the state of the unencrypted vault.

type UnencryptedVault added in v0.2.0

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

UnencryptedVault manages operations on an instance of an unencrypted vault that stores secrets in JSON format.

func NewUnencryptedVault added in v0.2.0

func NewUnencryptedVault(cfg *Config) (*UnencryptedVault, error)

func (*UnencryptedVault) Close added in v0.2.0

func (v *UnencryptedVault) Close() error

func (*UnencryptedVault) DeleteSecret added in v0.2.0

func (v *UnencryptedVault) DeleteSecret(key string) error

func (*UnencryptedVault) GetSecret added in v0.2.0

func (v *UnencryptedVault) GetSecret(key string) (Secret, error)

func (*UnencryptedVault) HasSecret added in v0.2.0

func (v *UnencryptedVault) HasSecret(key string) (bool, error)

func (*UnencryptedVault) ID added in v0.2.0

func (v *UnencryptedVault) ID() string

func (*UnencryptedVault) ListSecrets added in v0.2.0

func (v *UnencryptedVault) ListSecrets() ([]string, error)

func (*UnencryptedVault) Metadata added in v0.2.0

func (v *UnencryptedVault) Metadata() (Metadata, error)

func (*UnencryptedVault) SetSecret added in v0.2.0

func (v *UnencryptedVault) SetSecret(key string, secret Secret) error

type VaultPathError

type VaultPathError struct {
	Path string
	Err  error
}

func NewVaultPathError

func NewVaultPathError(path string) *VaultPathError

func (*VaultPathError) Error

func (e *VaultPathError) Error() string

func (*VaultPathError) Unwrap

func (e *VaultPathError) Unwrap() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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