security

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// KeySize is the size of AES-256 key in bytes.
	KeySize = 32
	// NonceSize is the size of GCM nonce in bytes.
	NonceSize = 12
	// SaltSize is the size of PBKDF2 salt in bytes.
	SaltSize = 16
	// Iterations is the PBKDF2 iteration count.
	Iterations = 100000
)

Variables

View Source
var (
	ErrKeyNotFound      = errors.New("key not found")
	ErrNoEncryptionKeys = errors.New("no encryption keys available")
	ErrDecryptionFailed = errors.New("decryption failed")

	// KMS errors
	ErrKMSUnavailable  = errors.New("KMS service unavailable")
	ErrKMSAccessDenied = errors.New("KMS access denied")
	ErrKMSKeyDisabled  = errors.New("KMS key is disabled")
	ErrKMSThrottled    = errors.New("KMS request throttled")
	ErrKMSInvalidKey   = errors.New("KMS invalid key")
	ErrPKCS11Module    = errors.New("PKCS#11 module error")
	ErrPKCS11Session   = errors.New("PKCS#11 session error")
)

Functions

func IsTransient

func IsTransient(err error) bool

IsTransient reports whether err is a transient KMS error eligible for retry.

Types

type CompositeCryptoProvider

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

CompositeCryptoProvider implements CryptoProvider with fallback logic. It tries the primary provider first (typically companion), then falls back to local.

func NewCompositeCryptoProvider

func NewCompositeCryptoProvider(primary CryptoProvider, fallback CryptoProvider, checker ConnectionChecker) *CompositeCryptoProvider

NewCompositeCryptoProvider creates a new CompositeCryptoProvider.

func (*CompositeCryptoProvider) Decrypt

func (c *CompositeCryptoProvider) Decrypt(ctx context.Context, keyID string, ciphertext []byte) ([]byte, error)

Decrypt implements CryptoProvider.

func (*CompositeCryptoProvider) Encrypt

func (c *CompositeCryptoProvider) Encrypt(ctx context.Context, keyID string, plaintext []byte) ([]byte, error)

Encrypt implements CryptoProvider.

func (*CompositeCryptoProvider) Sign

func (c *CompositeCryptoProvider) Sign(ctx context.Context, keyID string, payload []byte) ([]byte, error)

Sign implements CryptoProvider.

func (*CompositeCryptoProvider) UsedLocal

func (c *CompositeCryptoProvider) UsedLocal() bool

UsedLocal returns true if the last operation used the local fallback.

type ConnectionChecker

type ConnectionChecker interface {
	IsConnected() bool
}

ConnectionChecker provides connection status checking.

type CryptoProvider

type CryptoProvider interface {
	// Sign generates a signature for the given payload using the specified key ID.
	Sign(ctx context.Context, keyID string, payload []byte) ([]byte, error)
	// Encrypt encrypts the given plaintext using the specified key ID.
	Encrypt(ctx context.Context, keyID string, plaintext []byte) ([]byte, error)
	// Decrypt decrypts the given ciphertext using the specified key ID.
	Decrypt(ctx context.Context, keyID string, ciphertext []byte) ([]byte, error)
}

CryptoProvider defines the interface for cryptographic operations.

func NewKMSProvider

func NewKMSProvider(providerName KMSProviderName, kmsConfig config.KMSConfig) (CryptoProvider, error)

NewKMSProvider creates a CryptoProvider for the named KMS backend. Supported providers: "aws-kms", "gcp-kms", "azure-kv", "pkcs11". Build tags control which providers are compiled in; uncompiled providers return a descriptive error.

type DecryptRequest

type DecryptRequest struct {
	ID         string `json:"id"`
	KeyID      string `json:"keyId"`
	Ciphertext []byte `json:"ciphertext"`
}

DecryptRequest represents the payload for decryption.

type DecryptResponse

type DecryptResponse struct {
	ID        string `json:"id"`
	Plaintext []byte `json:"plaintext"`
	Error     string `json:"error,omitempty"`
}

DecryptResponse represents the payload for decryption response.

type EncryptRequest

type EncryptRequest struct {
	ID        string `json:"id"`
	KeyID     string `json:"keyId"`
	Plaintext []byte `json:"plaintext"`
}

EncryptRequest represents the payload for encryption.

type EncryptResponse

type EncryptResponse struct {
	ID         string `json:"id"`
	Ciphertext []byte `json:"ciphertext"`
	Error      string `json:"error,omitempty"`
}

EncryptResponse represents the payload for encryption response.

type KMSError

type KMSError struct {
	Provider string
	Op       string
	KeyID    string
	Err      error
}

KMSError wraps a KMS operation error with context.

func (*KMSError) Error

func (e *KMSError) Error() string

func (*KMSError) Unwrap

func (e *KMSError) Unwrap() error

type KMSHealthChecker

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

KMSHealthChecker implements ConnectionChecker for KMS providers. It caches the connection status with a configurable probe interval.

func NewKMSHealthChecker

func NewKMSHealthChecker(provider CryptoProvider, testKeyID string, probeInterval time.Duration) *KMSHealthChecker

NewKMSHealthChecker creates a health checker that probes the KMS provider by attempting a small encrypt/decrypt roundtrip on probeInterval.

func (*KMSHealthChecker) IsConnected

func (h *KMSHealthChecker) IsConnected() bool

IsConnected implements ConnectionChecker. Returns the cached result if fresh, otherwise performs a synchronous probe.

type KMSProviderName

type KMSProviderName string

KMSProviderName identifies a supported KMS backend.

const (
	KMSProviderAWS    KMSProviderName = "aws-kms"
	KMSProviderGCP    KMSProviderName = "gcp-kms"
	KMSProviderAzure  KMSProviderName = "azure-kv"
	KMSProviderPKCS11 KMSProviderName = "pkcs11"
)

func (KMSProviderName) Valid

func (n KMSProviderName) Valid() bool

Valid reports whether n is a recognised KMS provider name.

type KeyInfo

type KeyInfo struct {
	ID          uuid.UUID
	Name        string
	RemoteKeyID string
	Type        KeyType
	CreatedAt   time.Time
	LastUsedAt  *time.Time
}

KeyInfo represents key metadata.

type KeyRegistry

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

KeyRegistry manages encryption/signing keys.

func NewKeyRegistry

func NewKeyRegistry(client *ent.Client) *KeyRegistry

NewKeyRegistry creates a new KeyRegistry.

func (*KeyRegistry) DeleteKey

func (r *KeyRegistry) DeleteKey(ctx context.Context, name string) error

DeleteKey removes a key by name.

func (*KeyRegistry) GetDefaultKey

func (r *KeyRegistry) GetDefaultKey(ctx context.Context) (*KeyInfo, error)

GetDefaultKey retrieves the default encryption key (most recently created).

func (*KeyRegistry) GetKey

func (r *KeyRegistry) GetKey(ctx context.Context, name string) (*KeyInfo, error)

GetKey retrieves a key by name.

func (*KeyRegistry) ListKeys

func (r *KeyRegistry) ListKeys(ctx context.Context) ([]*KeyInfo, error)

ListKeys returns all registered keys.

func (*KeyRegistry) RegisterKey

func (r *KeyRegistry) RegisterKey(ctx context.Context, name, remoteKeyID string, keyType KeyType) (*KeyInfo, error)

RegisterKey registers a new key.

func (*KeyRegistry) UpdateLastUsed

func (r *KeyRegistry) UpdateLastUsed(ctx context.Context, name string) error

UpdateLastUsed updates the last used timestamp for a key.

type KeyType

type KeyType string

KeyType represents the purpose of a key.

const (
	KeyTypeEncryption KeyType = "encryption"
	KeyTypeSigning    KeyType = "signing"
)

func (KeyType) Valid

func (t KeyType) Valid() bool

Valid reports whether t is a known key type.

func (KeyType) Values

func (t KeyType) Values() []KeyType

Values returns all known key types.

type LocalCryptoProvider

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

LocalCryptoProvider implements CryptoProvider using local AES-256-GCM encryption. Key is derived from a passphrase using PBKDF2.

func NewLocalCryptoProvider

func NewLocalCryptoProvider() *LocalCryptoProvider

NewLocalCryptoProvider creates a new LocalCryptoProvider.

func (*LocalCryptoProvider) CalculateChecksum

func (p *LocalCryptoProvider) CalculateChecksum(passphrase string, salt []byte) []byte

CalculateChecksum computes the checksum for a given passphrase and salt. Uses HMAC-SHA256 with salt as key to avoid length extension attacks. NOTE: Changing this algorithm requires migrating existing stored checksums.

func (*LocalCryptoProvider) Decrypt

func (p *LocalCryptoProvider) Decrypt(ctx context.Context, keyID string, ciphertext []byte) ([]byte, error)

Decrypt decrypts data using AES-256-GCM.

func (*LocalCryptoProvider) Encrypt

func (p *LocalCryptoProvider) Encrypt(ctx context.Context, keyID string, plaintext []byte) ([]byte, error)

Encrypt encrypts data using AES-256-GCM.

func (*LocalCryptoProvider) Initialize

func (p *LocalCryptoProvider) Initialize(passphrase string) error

Initialize sets up the provider with a passphrase. The passphrase is used to derive an encryption key using PBKDF2.

func (*LocalCryptoProvider) InitializeWithSalt

func (p *LocalCryptoProvider) InitializeWithSalt(passphrase string, salt []byte) error

InitializeWithSalt sets up the provider with existing salt (for loading saved state).

func (*LocalCryptoProvider) IsInitialized

func (p *LocalCryptoProvider) IsInitialized() bool

IsInitialized returns true if the provider has been initialized.

func (*LocalCryptoProvider) Salt

func (p *LocalCryptoProvider) Salt() []byte

Salt returns the current salt for persistence.

func (*LocalCryptoProvider) Sign

func (p *LocalCryptoProvider) Sign(ctx context.Context, keyID string, payload []byte) ([]byte, error)

Sign generates a signature using HMAC-SHA256 (local signing).

type RPCProvider

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

RPCProvider implements CryptoProvider using an asynchronous RPC mechanism.

func NewRPCProvider

func NewRPCProvider() *RPCProvider

NewRPCProvider creates a new RPCProvider.

func (*RPCProvider) Decrypt

func (s *RPCProvider) Decrypt(ctx context.Context, keyID string, ciphertext []byte) ([]byte, error)

Decrypt implements the CryptoProvider interface.

func (*RPCProvider) Encrypt

func (s *RPCProvider) Encrypt(ctx context.Context, keyID string, plaintext []byte) ([]byte, error)

Encrypt implements the CryptoProvider interface.

func (*RPCProvider) HandleDecryptResponse

func (s *RPCProvider) HandleDecryptResponse(resp DecryptResponse) error

HandleDecryptResponse processes an incoming decrypt response.

func (*RPCProvider) HandleEncryptResponse

func (s *RPCProvider) HandleEncryptResponse(resp EncryptResponse) error

HandleEncryptResponse processes an incoming encrypt response.

func (*RPCProvider) HandleSignResponse

func (s *RPCProvider) HandleSignResponse(resp SignResponse) error

HandleSignResponse processes an incoming sign response.

func (*RPCProvider) SetSender

func (s *RPCProvider) SetSender(sender types.RPCSenderFunc)

SetSender configures the function used to send requests.

func (*RPCProvider) Sign

func (s *RPCProvider) Sign(ctx context.Context, keyID string, payload []byte) ([]byte, error)

Sign implements the CryptoProvider interface.

type RefStore

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

RefStore manages mapping between opaque reference tokens and secret plaintext values. It prevents AI agents from seeing actual secret values by substituting them with safe reference tokens.

func NewRefStore

func NewRefStore() *RefStore

NewRefStore creates a new RefStore.

func (*RefStore) Clear

func (r *RefStore) Clear()

Clear removes all stored references.

func (*RefStore) Names

func (r *RefStore) Names() map[string]string

Names returns a mapping of plaintext value (as string) to its reference name. This is used by the scanner to mask secrets in output, replacing them with tokens like [SECRET:name].

func (*RefStore) Resolve

func (r *RefStore) Resolve(token string) ([]byte, bool)

Resolve resolves a single reference token to its plaintext value. Returns the plaintext and true if found, or nil and false otherwise.

func (*RefStore) ResolveAll

func (r *RefStore) ResolveAll(input string) string

ResolveAll replaces all {{secret:...}} and {{decrypt:...}} tokens in the input string with their actual plaintext values.

func (*RefStore) Store

func (r *RefStore) Store(name string, value []byte) string

Store stores a secret value and returns its reference token in the format {{secret:name}}.

func (*RefStore) StoreDecrypted

func (r *RefStore) StoreDecrypted(id string, value []byte) string

StoreDecrypted stores a decrypted value and returns its reference token in the format {{decrypt:id}}.

func (*RefStore) Values

func (r *RefStore) Values() [][]byte

Values returns all stored plaintext values. This is useful for output scanning to detect accidental secret leakage.

type SecretInfo

type SecretInfo struct {
	ID          uuid.UUID
	Name        string
	KeyID       uuid.UUID
	KeyName     string
	CreatedAt   time.Time
	UpdatedAt   time.Time
	AccessCount int
}

SecretInfo represents secret metadata (without the actual value).

type SecretsStore

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

SecretsStore manages encrypted secrets.

func NewSecretsStore

func NewSecretsStore(client *ent.Client, registry *KeyRegistry, crypto CryptoProvider) *SecretsStore

NewSecretsStore creates a new SecretsStore.

func (*SecretsStore) Delete

func (s *SecretsStore) Delete(ctx context.Context, name string) error

Delete removes a secret by name.

func (*SecretsStore) Get

func (s *SecretsStore) Get(ctx context.Context, name string) ([]byte, error)

Get retrieves and decrypts a secret value.

func (*SecretsStore) List

func (s *SecretsStore) List(ctx context.Context) ([]*SecretInfo, error)

List returns metadata for all secrets.

func (*SecretsStore) Store

func (s *SecretsStore) Store(ctx context.Context, name string, value []byte) error

Store encrypts and stores a secret value.

type SignRequest

type SignRequest struct {
	ID      string `json:"id"`
	KeyID   string `json:"keyId"`
	Payload []byte `json:"payload"`
}

SignRequest represents the payload sent to the signer provider.

type SignResponse

type SignResponse struct {
	ID        string `json:"id"`
	Signature []byte `json:"signature"`
	Error     string `json:"error,omitempty"`
}

SignResponse represents the payload received from the signer provider.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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