Documentation
¶
Overview ¶
Package crypto provides an encryption codec for the rbaliyan/config library. It implements AES-256-GCM envelope encryption: each config value is encrypted with a freshly generated Data Encryption Key (DEK) that is itself wrapped by a Key Encryption Key (KEK) held by a pluggable Provider.
The package is organised around the following building blocks:
- Codec wraps an inner codec (json, yaml, toml, …) with transparent encryption. Register the codec with config's codec registry and configuration values are encrypted on Set and decrypted on Get.
- Provider abstracts KEK ownership. Built-ins: NewProvider (static single-key), NewKeyRingProvider (multi-key with live rotation), plus KMS-backed providers in the awskms, gcpkms, azurekv, vault, and gpg sub-packages.
- NamespaceSelector routes Encrypt/Decrypt to different providers based on the config namespace — useful for multi-tenant deployments where each tenant holds its own KEK.
- SelectorCodec combines a NamespaceSelector with an inner codec so a single codec registration covers all namespaces; the namespace is read from the context via WithNamespace.
- Poll drives backend-agnostic runtime key rotation against any KeyRingProvider. The AWS/GCP/Azure sub-packages ship a NewPoller helper that returns a FetchFn ready to hand to Poll; the vault sub-package has its own vault.Poll specialisation.
- EncryptedCache wraps any config.Cache (Redis, memory, …) so that cached values are stored as authenticated ciphertext. The full payload — data bytes, codec name, type, and metadata — is encrypted by the supplied Provider before the entry reaches the backing store.
For re-encrypting at-rest ciphertext after the current KEK changes, see the rotation sub-package. The otel sub-package provides optional OpenTelemetry tracing and metrics via WrapProvider.
Index ¶
- Variables
- func IsDecryptionFailed(err error) bool
- func IsDuplicateKeyID(err error) bool
- func IsInvalidFormat(err error) bool
- func IsInvalidKeyID(err error) bool
- func IsInvalidKeySize(err error) bool
- func IsKeyNotFound(err error) bool
- func IsNoProviderForNamespace(err error) bool
- func IsProviderClosed(err error) bool
- func IsRemoveCurrentKey(err error) bool
- func IsUnsupportedFormat(err error) bool
- func NamespaceFromContext(ctx context.Context) string
- func Poll(ctx context.Context, ring KeyRingProvider, interval time.Duration, ...) (func(), error)
- func WithNamespace(ctx context.Context, namespace string) context.Context
- type Codec
- func (c *Codec) Decode(ctx context.Context, data []byte, v any) error
- func (c *Codec) Encode(ctx context.Context, v any) ([]byte, error)
- func (c *Codec) Name() string
- func (c *Codec) Reverse(ctx context.Context, data []byte) ([]byte, error)
- func (c *Codec) Transform(ctx context.Context, data []byte) ([]byte, error)
- type CodecOption
- type EncryptedCache
- func (c *EncryptedCache) Delete(ctx context.Context, namespace, key string) error
- func (c *EncryptedCache) Get(ctx context.Context, namespace, key string) (config.Value, error)
- func (c *EncryptedCache) Set(ctx context.Context, namespace, key string, value config.Value) error
- func (c *EncryptedCache) Stats() config.CacheStats
- type FetchFn
- type KeyRingProvider
- type KeyVersion
- type NamespaceOption
- type NamespaceSelector
- func (s *NamespaceSelector) AddProvider(namespace string, provider Provider) error
- func (s *NamespaceSelector) Close() error
- func (s *NamespaceSelector) ForNamespace(namespace string) Provider
- func (s *NamespaceSelector) RemoveAndClose(namespace string) error
- func (s *NamespaceSelector) RemoveProvider(namespace string)
- type PollOption
- type Provider
- type SelectorCodec
- func (c *SelectorCodec) Decode(ctx context.Context, data []byte, v any) error
- func (c *SelectorCodec) Encode(ctx context.Context, v any) ([]byte, error)
- func (c *SelectorCodec) Name() string
- func (c *SelectorCodec) Reverse(ctx context.Context, data []byte) ([]byte, error)
- func (c *SelectorCodec) Transform(ctx context.Context, data []byte) ([]byte, error)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrKeyNotFound is returned when a key ID is not found in the provider. ErrKeyNotFound = errors.New("crypto: key not found") // ErrInvalidKeySize is returned when a key is not 32 bytes (AES-256). ErrInvalidKeySize = errors.New("crypto: invalid key size, must be 32 bytes") // ErrInvalidFormat is returned when encrypted data has an invalid format. ErrInvalidFormat = errors.New("crypto: invalid encrypted data format") // ErrUnsupportedFormat is returned when the format byte in a v2 header is not recognised. ErrUnsupportedFormat = errors.New("crypto: unsupported encrypted format") // ErrDecryptionFailed is returned when decryption fails (wrong key, tampered data). ErrDecryptionFailed = errors.New("crypto: decryption failed") // ErrInvalidKeyID is returned when a key ID is empty or invalid. ErrInvalidKeyID = errors.New("crypto: invalid key ID") // ErrProviderClosed is returned when a provider has been closed. ErrProviderClosed = errors.New("crypto: provider has been closed") // ErrRemoveCurrentKey is returned when attempting to remove the active encryption key. ErrRemoveCurrentKey = errors.New("crypto: cannot remove current key") // ErrNoProviderForNamespace is returned when a namespace has no registered provider and no fallback is set. ErrNoProviderForNamespace = errors.New("crypto: no key provider for namespace") // ErrDuplicateKeyID is returned from AddKey when the key ID is already present in the ring. ErrDuplicateKeyID = errors.New("crypto: duplicate key ID") )
var NamespaceContextKey = namespaceKey{}
NamespaceContextKey is the context key used to pass the config namespace into SelectorCodec.Encode and SelectorCodec.Decode. Set it with:
ctx = crypto.WithNamespace(ctx, "payments")
Functions ¶
func IsDecryptionFailed ¶
IsDecryptionFailed returns true if the error is or wraps ErrDecryptionFailed.
func IsDuplicateKeyID ¶ added in v0.5.1
IsDuplicateKeyID returns true if the error is or wraps ErrDuplicateKeyID.
func IsInvalidFormat ¶
IsInvalidFormat returns true if the error is or wraps ErrInvalidFormat.
func IsInvalidKeyID ¶
IsInvalidKeyID returns true if the error is or wraps ErrInvalidKeyID.
func IsInvalidKeySize ¶
IsInvalidKeySize returns true if the error is or wraps ErrInvalidKeySize.
func IsKeyNotFound ¶
IsKeyNotFound returns true if the error is or wraps ErrKeyNotFound.
func IsNoProviderForNamespace ¶ added in v0.3.0
IsNoProviderForNamespace returns true if the error is or wraps ErrNoProviderForNamespace.
func IsProviderClosed ¶ added in v0.3.0
IsProviderClosed returns true if the error is or wraps ErrProviderClosed.
func IsRemoveCurrentKey ¶ added in v0.2.3
IsRemoveCurrentKey returns true if the error is or wraps ErrRemoveCurrentKey.
func IsUnsupportedFormat ¶ added in v0.3.0
IsUnsupportedFormat returns true if the error is or wraps ErrUnsupportedFormat.
func NamespaceFromContext ¶ added in v0.5.1
NamespaceFromContext extracts the namespace previously set by WithNamespace. Returns an empty string if no namespace is present.
func Poll ¶ added in v0.5.1
func Poll(ctx context.Context, ring KeyRingProvider, interval time.Duration, fetchFn FetchFn, opts ...PollOption) (func(), error)
Poll starts a background goroutine that calls fetchFn at interval, adding any newly-seen key versions to ring and promoting the current key.
An initial fetch is performed before the ticker starts; if it fails, Poll returns an error immediately (fail-fast at startup).
The returned stop function cancels the goroutine and blocks until it exits. Callers should defer stop() after a successful Poll call.
Types ¶
type Codec ¶
type Codec struct {
// contains filtered or unexported fields
}
Codec wraps an inner codec with envelope encryption. On Encode, the inner codec serializes the value, then the result is encrypted. On Decode, the data is decrypted, then the inner codec deserializes the plaintext.
Codec is safe for concurrent use if the underlying Provider and inner codec are safe for concurrent use.
func NewCodec ¶
NewCodec creates an encrypting codec that wraps the given inner codec. The codec name is "encrypted:<inner>", e.g. "encrypted:json". With WithClientCodec the name becomes "client:encrypted:<inner>". Returns an error if inner or provider is nil.
Example ¶
package main
import (
"context"
"fmt"
crypto "github.com/rbaliyan/config-crypto"
jsoncodec "github.com/rbaliyan/config/codec/json"
)
func main() {
ctx := context.Background()
// 32-byte key for AES-256.
key := make([]byte, 32)
for i := range key {
key[i] = byte(i)
}
provider, err := crypto.NewProvider(key, "key-1")
if err != nil {
panic(err)
}
defer provider.Close()
encJSON, err := crypto.NewCodec(jsoncodec.New(), provider)
if err != nil {
panic(err)
}
fmt.Println("Codec name:", encJSON.Name())
// Decode round-trip.
data, err := encJSON.Encode(ctx, "my-secret")
if err != nil {
panic(err)
}
var result string
if err := encJSON.Decode(ctx, data, &result); err != nil {
panic(err)
}
fmt.Println("Decrypted:", result)
}
Output: Codec name: encrypted:json Decrypted: my-secret
Example (WithConfig) ¶
package main
import (
"fmt"
crypto "github.com/rbaliyan/config-crypto"
"github.com/rbaliyan/config/codec"
jsoncodec "github.com/rbaliyan/config/codec/json"
)
func main() {
key := make([]byte, 32)
for i := range key {
key[i] = byte(i)
}
provider, err := crypto.NewProvider(key, "key-1")
if err != nil {
panic(err)
}
defer provider.Close()
encJSON, err := crypto.NewCodec(jsoncodec.New(), provider)
if err != nil {
panic(err)
}
if err := codec.Register(encJSON); err != nil {
panic(err)
}
resolved := codec.Get("encrypted:json")
fmt.Println("Resolved:", resolved.Name())
}
Output: Resolved: encrypted:json
func (*Codec) Decode ¶
Decode decrypts the data, then deserializes the plaintext using the inner codec.
type CodecOption ¶ added in v0.3.0
type CodecOption func(*codecOptions)
CodecOption configures NewCodec behavior.
func WithClientCodec ¶ added in v0.2.3
func WithClientCodec() CodecOption
WithClientCodec prefixes the codec name with "client:" so the config-server recognises it as a client-managed codec and passes the bytes through without attempting to decode them. This is shorthand for WithCodecPrefix("client").
func WithCodecPrefix ¶ added in v0.2.3
func WithCodecPrefix(prefix string) CodecOption
WithCodecPrefix adds a custom prefix to the codec name. The resulting name is "<prefix>:encrypted:<inner>". Use this when you need a prefix other than the standard "client:".
type EncryptedCache ¶ added in v0.5.1
type EncryptedCache struct {
// contains filtered or unexported fields
}
EncryptedCache wraps any config.Cache with transparent encryption using the supplied Provider. The full value payload (data bytes, codec name, type, entry ID, and metadata) is encrypted before being written to the inner cache, and decrypted on retrieval. This ensures credentials and other sensitive values are never stored in plaintext in external caches such as Redis, regardless of whether the backing store uses encryption at rest.
EncryptedCache is safe for concurrent use by multiple goroutines.
Error semantics:
- Cache misses, expired entries, and cryptographic failures (wrong key, tampered ciphertext, corrupt payload, unknown schema version) return config.ErrNotFound so the manager transparently re-fetches from the store.
- Entries not written by EncryptedCache (codec sentinel mismatch) are also returned as config.ErrNotFound.
- Provider operational failures (e.g. ErrProviderClosed) are propagated as real errors so callers can surface and handle them.
Example:
provider, _ := crypto.NewProvider(keyBytes, "cache-key")
encCache, _ := crypto.NewEncryptedCache(
configredis.NewCache(rdb, configredis.WithCacheTTL(5*time.Minute)),
provider,
)
mgr, _ := config.New(
config.WithStore(remoteStore),
config.WithCache(encCache),
)
func NewEncryptedCache ¶ added in v0.5.1
func NewEncryptedCache(inner config.Cache, p Provider) (*EncryptedCache, error)
NewEncryptedCache returns a cache that encrypts all values before writing them to inner and decrypts on retrieval. Returns an error if inner or p is nil.
Example ¶
package main
import (
"context"
"fmt"
"sync"
"github.com/rbaliyan/config"
crypto "github.com/rbaliyan/config-crypto"
)
// mapCache is a minimal config.Cache used in examples.
type mapCache struct {
mu sync.RWMutex
data map[string]config.Value
}
func newMapCache() *mapCache { return &mapCache{data: make(map[string]config.Value)} }
func (m *mapCache) Set(_ context.Context, ns, key string, v config.Value) error {
m.mu.Lock()
m.data[ns+"/"+key] = v
m.mu.Unlock()
return nil
}
func (m *mapCache) Get(_ context.Context, ns, key string) (config.Value, error) {
m.mu.RLock()
v, ok := m.data[ns+"/"+key]
m.mu.RUnlock()
if !ok {
return nil, config.ErrNotFound
}
return v, nil
}
func (m *mapCache) Delete(_ context.Context, ns, key string) error {
m.mu.Lock()
delete(m.data, ns+"/"+key)
m.mu.Unlock()
return nil
}
func (m *mapCache) Stats() config.CacheStats { return config.CacheStats{} }
func main() {
ctx := context.Background()
key := make([]byte, 32)
for i := range key {
key[i] = byte(i)
}
provider, err := crypto.NewProvider(key, "cache-key-v1")
if err != nil {
panic(err)
}
defer provider.Close()
inner := newMapCache()
encCache, err := crypto.NewEncryptedCache(inner, provider)
if err != nil {
panic(err)
}
// Store an encrypted value.
val := config.NewValue("my-secret", config.WithValueType(config.TypeString))
if err := encCache.Set(ctx, "prod", "db/password", val); err != nil {
panic(err)
}
// The inner cache holds ciphertext — not the original string.
raw, _ := inner.Get(ctx, "prod", "db/password")
fmt.Println("Inner codec:", raw.Codec())
// Retrieve and decrypt.
got, err := encCache.Get(ctx, "prod", "db/password")
if err != nil {
panic(err)
}
s, _ := got.String()
fmt.Println("Decrypted:", s)
}
Output: Inner codec: crypto:cache Decrypted: my-secret
func NewSessionCache ¶ added in v0.5.2
func NewSessionCache(capacity int) (*EncryptedCache, error)
NewSessionCache returns an EncryptedCache backed by an in-memory LRU and a fresh random AES-256-GCM key generated at call time. The key never leaves process memory and is discarded on restart, so cached values cannot be read by any other process or after a restart — even if they share the same backing store.
capacity is the maximum number of entries (0 uses the config default of 10000).
This is the recommended in-process cache for services that handle secrets or other sensitive configuration values. It provides at-rest protection in memory without requiring an external key management system or Vault integration.
cache, err := crypto.NewSessionCache(0) // default capacity (10000 entries)
mgr, err := config.New(
config.WithStore(remoteStore),
config.WithCache(cache),
)
func (*EncryptedCache) Delete ¶ added in v0.5.1
func (c *EncryptedCache) Delete(ctx context.Context, namespace, key string) error
Delete removes a cache entry from the inner cache.
func (*EncryptedCache) Get ¶ added in v0.5.1
Get retrieves a value from the inner cache and decrypts it.
Returns config.ErrNotFound for:
- Cache misses and expired entries.
- Cryptographic failures (wrong key after rotation, tampered ciphertext, invalid or unsupported ciphertext format) — the manager re-fetches from the store and the fresh value is re-encrypted with the current key.
- Corrupt payload (unknown schema version, out-of-range Type field, malformed JSON) — same fallback behaviour.
Returns a real error (not ErrNotFound) for provider operational failures such as ErrProviderClosed so callers can surface them rather than silently falling through to a potentially unavailable backend store.
func (*EncryptedCache) Set ¶ added in v0.5.1
Set encrypts the value's full payload and stores the ciphertext in the inner cache. Only ExpiresAt is forwarded to the outer wrapper so the inner cache (e.g. Redis) can enforce TTL-based eviction without decrypting. All other metadata — including Version, CreatedAt, UpdatedAt, and EntryID — is kept exclusively inside the ciphertext to avoid leaking operational metadata in Redis plaintext.
func (*EncryptedCache) Stats ¶ added in v0.5.1
func (c *EncryptedCache) Stats() config.CacheStats
Stats returns cache statistics. Hits and Misses reflect post-decryption outcomes measured by EncryptedCache; Size, Capacity, and Evictions are sourced from the inner cache.
A sudden miss-spike without a corresponding hit drop typically indicates key rotation: old ciphertext cannot be decrypted by the new provider, so each cached entry is re-fetched from the backing store and re-encrypted as it is accessed. This is expected behaviour during and shortly after a key rotation.
type FetchFn ¶ added in v0.5.1
type FetchFn func(ctx context.Context) ([]KeyVersion, error)
FetchFn retrieves the current set of key versions from a KMS. It must be idempotent: returning the same version multiple times is safe. Returning versions already known to the ring is safe — Poll skips them.
type KeyRingProvider ¶ added in v0.5.0
type KeyRingProvider interface {
Provider
// AddKey adds a key that can be used for decryption or set as the current
// key. The keyBytes must be 32 bytes for AES-256 and id must not be empty.
// rank is the KV store version number for this key; it is used by
// NeedsReencryption to establish ordering. Pass 0 when the backing store
// does not provide version ordering. Returns ErrDuplicateKeyID if the ID
// already exists.
AddKey(keyBytes []byte, id string, rank uint64) error
// SetCurrentKey switches the active encryption key to the given ID.
// The key must have been previously added via the constructor or AddKey.
SetCurrentKey(id string) error
// RemoveKey removes a key by ID. The current key cannot be removed.
RemoveKey(id string) error
// CurrentKeyID returns the ID of the key currently used for encryption.
CurrentKeyID() string
// NeedsReencryption reports whether ciphertext was encrypted with a key
// that is older than the current key, based on the rank recorded when each
// key was added. It returns true only when the current key has a strictly
// higher rank than the key embedded in the ciphertext header.
//
// It returns false (not true) when the ciphertext key is unknown to this
// provider, since ordering cannot be determined in that case.
// It returns an error only if the ciphertext header cannot be parsed.
NeedsReencryption(ciphertext []byte) (bool, error)
}
KeyRingProvider is a mutable Provider that supports runtime key rotation. Keys can be added, removed, and the current key switched at any time. End users usually get a KeyRingProvider from a KMS package; this interface is exported so KMS packages can build on top of it.
KeyRingProvider is safe for concurrent use.
func NewKeyRingProvider ¶ added in v0.5.0
func NewKeyRingProvider(initialBytes []byte, id string, rank uint64) (KeyRingProvider, error)
NewKeyRingProvider creates a mutable Provider with the given initial key. The keyBytes must be 32 bytes for AES-256. The id identifies this key. rank is the KV store version number for this key (e.g. the Vault KV version integer cast to uint64); it is used by NeedsReencryption to determine whether a given ciphertext was encrypted with an older key. Use 0 when the backing store does not provide version ordering. Key bytes are copied into a memguard Enclave; the caller should zero the original slice after construction as a defence-in-depth measure.
Example (Rotation) ¶
package main
import (
"context"
"fmt"
crypto "github.com/rbaliyan/config-crypto"
jsoncodec "github.com/rbaliyan/config/codec/json"
)
func main() {
ctx := context.Background()
oldKey := make([]byte, 32)
for i := range oldKey {
oldKey[i] = byte(i)
}
// Encrypt with the old key.
oldP, err := crypto.NewProvider(oldKey, "key-v1")
if err != nil {
panic(err)
}
defer oldP.Close()
oldCodec, err := crypto.NewCodec(jsoncodec.New(), oldP)
if err != nil {
panic(err)
}
encrypted, err := oldCodec.Encode(ctx, "secret-data")
if err != nil {
panic(err)
}
// Rotate: KeyRingProvider has both keys; current is v2.
newKey := make([]byte, 32)
for i := range newKey {
newKey[i] = byte(i + 100)
}
ring, err := crypto.NewKeyRingProvider(newKey, "key-v2", 2)
if err != nil {
panic(err)
}
defer ring.Close()
if err := ring.AddKey(oldKey, "key-v1", 1); err != nil {
panic(err)
}
newCodec, err := crypto.NewCodec(jsoncodec.New(), ring)
if err != nil {
panic(err)
}
var result string
if err := newCodec.Decode(ctx, encrypted, &result); err != nil {
panic(err)
}
fmt.Println("Decrypted with rotated provider:", result)
}
Output: Decrypted with rotated provider: secret-data
type KeyVersion ¶ added in v0.5.1
type KeyVersion struct {
ID string // stable identifier (used as key ID in encrypted headers)
Bytes []byte // 32-byte AES-256 key material
Rank uint64 // ordering rank for NeedsReencryption; higher = newer
IsCurrent bool // true if this version should be the active encryption key
}
KeyVersion is a single key version returned by a FetchFn.
type NamespaceOption ¶ added in v0.3.0
type NamespaceOption func(*namespaceOptions)
NamespaceOption configures a NamespaceSelector.
func WithFallbackProvider ¶ added in v0.3.0
func WithFallbackProvider(provider Provider) NamespaceOption
WithFallbackProvider sets the fallback Provider used when a namespace has no dedicated provider.
func WithNamespaceProvider ¶ added in v0.3.0
func WithNamespaceProvider(namespace string, provider Provider) NamespaceOption
WithNamespaceProvider registers a Provider for the given namespace. Nil providers are ignored.
type NamespaceSelector ¶ added in v0.3.0
type NamespaceSelector struct {
// contains filtered or unexported fields
}
NamespaceSelector routes Encrypt/Decrypt to namespace-specific Providers. It holds a map of namespace to Provider plus an optional fallback provider. It is safe for concurrent use; providers can be added or removed at runtime.
In multi-tenant scenarios, use ForNamespace to obtain a namespace-scoped Provider; do not invoke Encrypt or Decrypt directly on the selector — those methods are not exposed because the selector itself does not know which namespace a payload belongs to.
func NewNamespaceSelector ¶ added in v0.3.0
func NewNamespaceSelector(opts ...NamespaceOption) (*NamespaceSelector, error)
NewNamespaceSelector creates a NamespaceSelector with the given options.
func (*NamespaceSelector) AddProvider ¶ added in v0.3.0
func (s *NamespaceSelector) AddProvider(namespace string, provider Provider) error
AddProvider registers a Provider for the given namespace at runtime. Returns an error if provider is nil or the selector has been closed.
func (*NamespaceSelector) Close ¶ added in v0.3.0
func (s *NamespaceSelector) Close() error
Close closes every Provider held by the selector (namespace-scoped and fallback). Errors from individual closes are joined via errors.Join. Safe to call multiple times; subsequent calls are no-ops.
func (*NamespaceSelector) ForNamespace ¶ added in v0.3.0
func (s *NamespaceSelector) ForNamespace(namespace string) Provider
ForNamespace returns a Provider scoped to the given namespace. If the namespace has a registered provider, that provider is used. Otherwise the fallback provider is used. If neither exists, the returned Provider returns ErrNoProviderForNamespace on Encrypt/Decrypt. The returned Provider is safe for concurrent use and reflects runtime changes to the selector (providers added/removed after ForNamespace).
Close on the returned Provider is a no-op; close the underlying providers or the selector itself.
func (*NamespaceSelector) RemoveAndClose ¶ added in v0.3.0
func (s *NamespaceSelector) RemoveAndClose(namespace string) error
RemoveAndClose removes the Provider for the given namespace and calls Close on it. Returns the Close error (or nil if the namespace had no provider). Use this when the selector owns the provider's lifecycle.
func (*NamespaceSelector) RemoveProvider ¶ added in v0.3.0
func (s *NamespaceSelector) RemoveProvider(namespace string)
RemoveProvider removes the Provider for the given namespace. The removed provider is not closed; the caller retains ownership and must call Close on it. Use RemoveAndClose if the selector should close the provider on the caller's behalf.
type PollOption ¶ added in v0.5.1
type PollOption func(*pollOptions)
PollOption configures Poll.
func WithPollErrorHandler ¶ added in v0.5.1
func WithPollErrorHandler(fn func(error)) PollOption
WithPollErrorHandler sets a callback for poll errors (fetch failures, AddKey failures). The callback runs on the polling goroutine and must not block. If unset, errors are logged via slog.
func WithPollMaxRetries ¶ added in v0.5.1
func WithPollMaxRetries(n int) PollOption
WithPollMaxRetries sets the per-version retry cap. After this many failures, the version is permanently skipped for the lifetime of the goroutine. Default is 5.
type Provider ¶ added in v0.3.0
type Provider interface {
// Name returns a short human-readable identifier for this provider.
// Used for logging and observability; need not be globally unique.
Name() string
// Connect initialises any remote connection the provider needs.
// It is the caller's responsibility to call Connect before the first
// Encrypt or Decrypt. Implementations backed by in-memory keys treat
// this as a no-op; remote-key-wrapping implementations use it to
// establish SDK sessions or verify credentials.
Connect(ctx context.Context) error
// Encrypt encrypts plaintext using envelope encryption.
Encrypt(ctx context.Context, plaintext []byte) ([]byte, error)
// Decrypt decrypts ciphertext that was produced by Encrypt.
Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error)
// HealthCheck reports whether the provider is currently usable. It
// returns nil for a healthy provider and an error otherwise.
// Implementations backed by remote services may use ctx to bound the
// check; static providers ignore ctx and return nil unless closed.
HealthCheck(ctx context.Context) error
// Close zeros all key material and releases resources.
// After Close, Encrypt, Decrypt, and HealthCheck return ErrProviderClosed.
Close() error
}
Provider encrypts and decrypts data using envelope encryption. Implementations must be safe for concurrent use.
func NewProvider ¶ added in v0.3.0
NewProvider builds a static Provider from raw 32-byte AES-256 key bytes. Key bytes are copied internally; the caller may safely zero the original after construction. The returned Provider does not expose key rotation methods; use NewKeyRingProvider when runtime rotation is required.
type SelectorCodec ¶ added in v0.5.1
type SelectorCodec struct {
// contains filtered or unexported fields
}
SelectorCodec wraps a NamespaceSelector with an inner codec (e.g. JSON) to provide per-namespace encryption through a single codec registration.
On Encode, it reads the namespace from ctx (via WithNamespace), serializes the value with the inner codec, then encrypts with the namespace-specific provider from the selector.
On Decode, it reads the namespace from ctx, decrypts with the matching provider, then deserializes with the inner codec.
Register once at startup:
sel, _ := crypto.NewNamespaceSelector(
crypto.WithNamespaceProvider("payments", awsProvider),
crypto.WithNamespaceProvider("users", gcpProvider),
crypto.WithFallbackProvider(defaultProvider),
)
sc, _ := crypto.NewSelectorCodec(sel, jsoncodec.New())
codec.Register(sc) // one registration covers all namespaces
When calling store operations, inject the namespace into ctx first:
ctx = crypto.WithNamespace(ctx, "payments") store.Set(ctx, "payments", "db-password", value)
SelectorCodec is safe for concurrent use if the NamespaceSelector and inner codec are safe for concurrent use.
func NewSelectorCodec ¶ added in v0.5.1
func NewSelectorCodec(selector *NamespaceSelector, inner codec.Codec, opts ...CodecOption) (*SelectorCodec, error)
NewSelectorCodec creates a SelectorCodec. The codec name is "encrypted:<inner>" (e.g. "encrypted:json"). WithClientCodec and WithCodecPrefix options from NewCodec are reused here. Returns an error if selector or inner is nil.
func (*SelectorCodec) Decode ¶ added in v0.5.1
Decode decrypts data with the provider resolved from ctx's namespace, then deserializes into v using the inner codec.
func (*SelectorCodec) Encode ¶ added in v0.5.1
Encode serializes v with the inner codec then encrypts with the provider resolved from ctx's namespace. Returns ErrNoProviderForNamespace if no provider is registered for the namespace and no fallback is set.
func (*SelectorCodec) Name ¶ added in v0.5.1
func (c *SelectorCodec) Name() string
Name returns the codec name, e.g. "encrypted:json".
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package awskms provides a crypto.Provider backed by AWS KMS.
|
Package awskms provides a crypto.Provider backed by AWS KMS. |
|
Package azurekv provides a crypto.Provider backed by Azure Key Vault.
|
Package azurekv provides a crypto.Provider backed by Azure Key Vault. |
|
Package gcpkms provides a crypto.Provider backed by Google Cloud KMS.
|
Package gcpkms provides a crypto.Provider backed by Google Cloud KMS. |
|
Package gpg provides a crypto.Provider that decrypts AES-256 keys using GPG.
|
Package gpg provides a crypto.Provider that decrypts AES-256 keys using GPG. |
|
internal
|
|
|
kmsring
Package kmsring factors out the common "unwrap N encrypted keys and build a crypto.KeyRingProvider" loop shared by every KMS adapter in this module.
|
Package kmsring factors out the common "unwrap N encrypted keys and build a crypto.KeyRingProvider" loop shared by every KMS adapter in this module. |
|
Package otel provides OpenTelemetry instrumentation for the config-crypto Provider interface.
|
Package otel provides OpenTelemetry instrumentation for the config-crypto Provider interface. |
|
Package rotation provides a background Orchestrator that re-encrypts stored configuration values whose encryption key is no longer the current version of the ring.
|
Package rotation provides a background Orchestrator that re-encrypts stored configuration values whose encryption key is no longer the current version of the ring. |
|
Package vault provides a crypto.KeyRingProvider backed by a HashiCorp Vault KV v2 secret.
|
Package vault provides a crypto.KeyRingProvider backed by a HashiCorp Vault KV v2 secret. |