kms

package
v1.23.3 Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: BSD-3-Clause Imports: 22 Imported by: 0

Documentation

Overview

Package kms provides a unified Key Management Service with support for both embedded (BadgerDB) and distributed (PostgreSQL) storage backends.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrKeyNotFound = fmt.Errorf("key not found")
	ErrInvalidKey  = fmt.Errorf("invalid key")
)

Common errors

Functions

func DecodeBase64

func DecodeBase64(s string) ([]byte, error)

DecodeBase64 decodes base64 to bytes.

func EncodeBase64

func EncodeBase64(data []byte) string

EncodeBase64 encodes bytes to base64.

func GetJSON

func GetJSON[T any](ctx context.Context, store StorageBackend, key string) (*T, error)

GetJSON retrieves and unmarshals a JSON value.

func SetJSON

func SetJSON(ctx context.Context, store StorageBackend, key string, value any) error

SetJSON marshals and stores a JSON value.

Types

type BadgerConfig

type BadgerConfig struct {
	Dir           string
	InMemory      bool
	SyncWrites    bool
	Compression   bool
	EncryptionKey []byte // 16, 24, or 32 bytes for AES-128, AES-192, AES-256
}

BadgerConfig holds BadgerDB configuration options.

type BadgerStore

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

BadgerStore implements StorageBackend using BadgerDB for embedded storage.

func NewBadgerStore

func NewBadgerStore(cfg *BadgerConfig) (*BadgerStore, error)

NewBadgerStore creates a new BadgerDB-backed storage.

func (*BadgerStore) BeginTx

func (s *BadgerStore) BeginTx(ctx context.Context) (Transaction, error)

BeginTx starts a new transaction.

func (*BadgerStore) Close

func (s *BadgerStore) Close() error

Close closes the BadgerDB store.

func (*BadgerStore) Delete

func (s *BadgerStore) Delete(ctx context.Context, key string) error

Delete removes a key from storage.

func (*BadgerStore) Exists

func (s *BadgerStore) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists.

func (*BadgerStore) Get

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

Get retrieves a value by key.

func (*BadgerStore) List

func (s *BadgerStore) List(ctx context.Context, prefix string) ([]string, error)

List returns all keys with the given prefix.

func (*BadgerStore) Scan

func (s *BadgerStore) Scan(ctx context.Context, prefix string, fn func(key string, value []byte) error) error

Scan iterates over all key-value pairs with the given prefix.

func (*BadgerStore) Set

func (s *BadgerStore) Set(ctx context.Context, key string, value []byte) error

Set stores a value at the given key.

func (*BadgerStore) SetWithTTL

func (s *BadgerStore) SetWithTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error

SetWithTTL stores a value with a time-to-live.

type Config

type Config struct {
	Store       StorageBackend
	RootKey     []byte // Must be 32 bytes for AES-256
	DataDir     string // Only used if Store is nil (creates BadgerStore)
	InMemory    bool
	Compression bool
}

Config holds KMS configuration.

type EncryptedData

type EncryptedData struct {
	KeyID      string `json:"keyId"`
	KeyVersion int    `json:"keyVersion"`
	Data       []byte `json:"data"`
}

EncryptedData represents encrypted data with metadata.

type KMS

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

KMS provides key management and encryption services.

func New

func New(cfg *Config) (*KMS, error)

New creates a new KMS instance.

func (*KMS) Close

func (k *KMS) Close() error

Close closes the KMS and underlying storage.

func (*KMS) CreateSecret

func (k *KMS) CreateSecret(ctx context.Context, name string, value []byte, opts *SecretOptions) (*Secret, error)

CreateSecret creates a new secret.

func (*KMS) Decrypt

func (k *KMS) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error)

Decrypt decrypts data.

func (*KMS) DeleteKey

func (k *KMS) DeleteKey(ctx context.Context, keyID string) error

DeleteKey soft-deletes a key.

func (*KMS) DeleteSecret

func (k *KMS) DeleteSecret(ctx context.Context, secretID string) error

DeleteSecret deletes a secret.

func (*KMS) Encrypt

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

Encrypt encrypts data using the specified key.

func (*KMS) GenerateKey

func (k *KMS) GenerateKey(ctx context.Context, name string, keyType KeyType, usage KeyUsage, opts *KeyOptions) (*Key, error)

GenerateKey generates a new cryptographic key.

func (*KMS) GetKey

func (k *KMS) GetKey(ctx context.Context, keyID string) (*Key, error)

GetKey retrieves a key by ID.

func (*KMS) GetKeyByName

func (k *KMS) GetKeyByName(ctx context.Context, name string) (*Key, error)

GetKeyByName retrieves a key by name.

func (*KMS) GetPublicKey

func (k *KMS) GetPublicKey(ctx context.Context, keyID string) ([]byte, error)

GetPublicKey returns the public key for an asymmetric key.

func (*KMS) GetSecret

func (k *KMS) GetSecret(ctx context.Context, secretID string) (*Secret, error)

GetSecret retrieves a secret by ID.

func (*KMS) GetSecretValue

func (k *KMS) GetSecretValue(ctx context.Context, secretID string) ([]byte, error)

GetSecretValue retrieves and decrypts a secret value.

func (*KMS) ListKeys

func (k *KMS) ListKeys(ctx context.Context, prefix string) ([]*Key, error)

ListKeys lists all keys, optionally filtered by prefix.

func (*KMS) ListSecrets

func (k *KMS) ListSecrets(ctx context.Context, env, path string) ([]*Secret, error)

ListSecrets lists secrets, optionally filtered by environment or path.

func (*KMS) Sign

func (k *KMS) Sign(ctx context.Context, keyID string, data []byte) ([]byte, error)

Sign signs data using an asymmetric key.

func (*KMS) UpdateSecret

func (k *KMS) UpdateSecret(ctx context.Context, secretID string, newValue []byte) (*Secret, error)

UpdateSecret updates a secret's value.

func (*KMS) Verify

func (k *KMS) Verify(ctx context.Context, keyID string, data, signature []byte) (bool, error)

Verify verifies a signature.

type Key

type Key struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Description string            `json:"description,omitempty"`
	Type        KeyType           `json:"type"`
	Usage       KeyUsage          `json:"usage"`
	Status      KeyStatus         `json:"status"`
	Version     int               `json:"version"`
	OrgID       string            `json:"orgId,omitempty"`
	ProjectID   string            `json:"projectId,omitempty"`
	Created     time.Time         `json:"created"`
	Updated     time.Time         `json:"updated"`
	ExpiresAt   *time.Time        `json:"expiresAt,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`

	// For MPC keys
	Threshold    int      `json:"threshold,omitempty"`
	TotalShares  int      `json:"totalShares,omitempty"`
	ShareHolders []string `json:"shareHolders,omitempty"`
}

Key represents a cryptographic key in the KMS.

type KeyMaterial

type KeyMaterial struct {
	KeyID            string    `json:"keyId"`
	Version          int       `json:"version"`
	EncryptedKey     []byte    `json:"encryptedKey"`     // Encrypted with root key
	EncryptedPrivate []byte    `json:"encryptedPrivate"` // For asymmetric keys
	PublicKey        []byte    `json:"publicKey"`        // Public key (if asymmetric)
	Nonce            []byte    `json:"nonce"`
	Created          time.Time `json:"created"`
}

KeyMaterial holds the encrypted key material.

type KeyOptions

type KeyOptions struct {
	Description string
	OrgID       string
	ProjectID   string
	Metadata    map[string]string
	ExpiresIn   time.Duration
}

KeyOptions holds optional parameters for key generation.

type KeyStatus

type KeyStatus string

KeyStatus represents the current state of a key.

const (
	KeyStatusActive   KeyStatus = "active"
	KeyStatusInactive KeyStatus = "inactive"
	KeyStatusDeleted  KeyStatus = "deleted"
	KeyStatusPending  KeyStatus = "pending" // For MPC key generation
)

type KeyType

type KeyType string

KeyType represents the type of cryptographic key.

const (
	KeyTypeAES256    KeyType = "aes-256-gcm"
	KeyTypeRSA3072   KeyType = "rsa-3072"
	KeyTypeRSA4096   KeyType = "rsa-4096"
	KeyTypeECDSAP256 KeyType = "ecdsa-p256"
	KeyTypeECDSAP384 KeyType = "ecdsa-p384"
	KeyTypeEdDSA     KeyType = "ed25519"
)

type KeyUsage

type KeyUsage string

KeyUsage represents what a key can be used for.

const (
	KeyUsageEncryptDecrypt KeyUsage = "encrypt-decrypt"
	KeyUsageSignVerify     KeyUsage = "sign-verify"
	KeyUsageMPC            KeyUsage = "mpc"
)

type KmsKey

type KmsKey struct {
	ID                  string `json:"id"`
	Description         string `json:"description"`
	IsDisabled          bool   `json:"isDisabled"`
	OrgID               string `json:"orgId"`
	Name                string `json:"name"`
	ProjectID           string `json:"projectId"`
	KeyUsage            string `json:"keyUsage"` // "sign-verify" or "encrypt-decrypt"
	Version             int    `json:"version"`
	EncryptionAlgorithm string `json:"encryptionAlgorithm"` // "rsa-4096", "ecc-nist-p256", "aes-256-gcm", "aes-128-gcm"
}

KmsKey matches kms-go SDK KmsKey struct

type MPCChain

type MPCChain string

MPCChain represents a supported blockchain.

const (
	MPCChainEthereum  MPCChain = "ethereum"
	MPCChainPolygon   MPCChain = "polygon"
	MPCChainArbitrum  MPCChain = "arbitrum"
	MPCChainOptimism  MPCChain = "optimism"
	MPCChainBase      MPCChain = "base"
	MPCChainAvalanche MPCChain = "avalanche"
	MPCChainBNB       MPCChain = "bnb"
	MPCChainBitcoin   MPCChain = "bitcoin"
	MPCChainSolana    MPCChain = "solana"
	MPCChainLux       MPCChain = "lux"
)

type MPCKeyType

type MPCKeyType string

MPC key types for threshold signing

const (
	MPCKeyTypeECDSA   MPCKeyType = "ecdsa"   // Ethereum, Bitcoin
	MPCKeyTypeEdDSA   MPCKeyType = "eddsa"   // Solana
	MPCKeyTypeTaproot MPCKeyType = "taproot" // Bitcoin Taproot
)

type MPCManager

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

MPCManager handles MPC operations integrated with KMS.

func NewMPCManager

func NewMPCManager(kms *KMS) *MPCManager

NewMPCManager creates a new MPC manager.

func (*MPCManager) CreateSigningRequest

func (m *MPCManager) CreateSigningRequest(ctx context.Context, walletID string, chain MPCChain, rawTransaction []byte, opts *SigningOptions) (*MPCSigningRequest, error)

CreateSigningRequest creates a new signing request.

func (*MPCManager) CreateWallet

func (m *MPCManager) CreateWallet(ctx context.Context, name string, keyType MPCKeyType, threshold, totalParties int, participantIDs []string, opts *WalletOptions) (*MPCWallet, error)

CreateWallet creates a new MPC wallet.

func (*MPCManager) GetKeyShare

func (m *MPCManager) GetKeyShare(ctx context.Context, walletID, nodeID string) ([]byte, error)

GetKeyShare retrieves an encrypted key share.

func (*MPCManager) GetNode

func (m *MPCManager) GetNode(ctx context.Context, nodeID string) (*MPCNode, error)

GetNode retrieves a node by ID.

func (*MPCManager) GetSigningRequest

func (m *MPCManager) GetSigningRequest(ctx context.Context, requestID string) (*MPCSigningRequest, error)

GetSigningRequest retrieves a signing request.

func (*MPCManager) GetWallet

func (m *MPCManager) GetWallet(ctx context.Context, walletID string) (*MPCWallet, error)

GetWallet retrieves a wallet by ID.

func (*MPCManager) ListNodes

func (m *MPCManager) ListNodes(ctx context.Context) ([]*MPCNode, error)

ListNodes lists all registered MPC nodes.

func (*MPCManager) ListPendingSigningRequests

func (m *MPCManager) ListPendingSigningRequests(ctx context.Context, walletID string) ([]*MPCSigningRequest, error)

ListPendingSigningRequests lists all pending signing requests for a wallet.

func (*MPCManager) ListWallets

func (m *MPCManager) ListWallets(ctx context.Context) ([]*MPCWallet, error)

ListWallets lists all MPC wallets.

func (*MPCManager) RegisterNode

func (m *MPCManager) RegisterNode(ctx context.Context, name, endpoint string, port int, publicKey []byte, opts *NodeOptions) (*MPCNode, error)

RegisterNode registers a new MPC node.

func (*MPCManager) SetFinalSignature

func (m *MPCManager) SetFinalSignature(ctx context.Context, requestID string, finalSig []byte) error

SetFinalSignature sets the combined final signature.

func (*MPCManager) SetWalletPublicKey

func (m *MPCManager) SetWalletPublicKey(ctx context.Context, walletID string, publicKey []byte, chainAddresses map[MPCChain]string) error

SetWalletPublicKey sets the public key after MPC key generation completes.

func (*MPCManager) StoreKeyShare

func (m *MPCManager) StoreKeyShare(ctx context.Context, walletID, nodeID string, encryptedShare []byte) error

StoreKeyShare stores an encrypted key share for a node.

func (*MPCManager) SubmitPartialSignature

func (m *MPCManager) SubmitPartialSignature(ctx context.Context, requestID, nodeID string, partialSig []byte) (*MPCSigningRequest, error)

SubmitPartialSignature submits a partial signature from a node.

func (*MPCManager) UpdateNodeStatus

func (m *MPCManager) UpdateNodeStatus(ctx context.Context, nodeID, status string) error

UpdateNodeStatus updates a node's status and last seen time.

type MPCNode

type MPCNode struct {
	ID        string            `json:"id"`
	Name      string            `json:"name"`
	Endpoint  string            `json:"endpoint"`
	Port      int               `json:"port"`
	PublicKey []byte            `json:"publicKey"`
	Status    string            `json:"status"`
	OrgID     string            `json:"orgId,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
	Created   time.Time         `json:"created"`
	LastSeen  time.Time         `json:"lastSeen"`
}

MPCNode represents a participant node in MPC operations.

type MPCSigningRequest

type MPCSigningRequest struct {
	ID             string            `json:"id"`
	WalletID       string            `json:"walletId"`
	Chain          MPCChain          `json:"chain"`
	RawTransaction []byte            `json:"rawTransaction"`
	Message        []byte            `json:"message,omitempty"` // For message signing
	Status         SigningStatus     `json:"status"`
	Signatures     map[string][]byte `json:"signatures"` // nodeID -> partial signature
	FinalSignature []byte            `json:"finalSignature,omitempty"`
	RequiredSigs   int               `json:"requiredSigs"`
	CollectedSigs  int               `json:"collectedSigs"`
	Created        time.Time         `json:"created"`
	ExpiresAt      time.Time         `json:"expiresAt"`
	Metadata       map[string]string `json:"metadata,omitempty"`
}

MPCSigningRequest represents a request to sign data.

type MPCWallet

type MPCWallet struct {
	ID             string              `json:"id"`
	Name           string              `json:"name"`
	KeyType        MPCKeyType          `json:"keyType"`
	Threshold      int                 `json:"threshold"`    // t in t-of-n
	TotalParties   int                 `json:"totalParties"` // n in t-of-n
	ParticipantIDs []string            `json:"participantIds"`
	PublicKey      []byte              `json:"publicKey"`
	ChainAddresses map[MPCChain]string `json:"chainAddresses"`
	Status         KeyStatus           `json:"status"`
	OrgID          string              `json:"orgId,omitempty"`
	ProjectID      string              `json:"projectId,omitempty"`
	Metadata       map[string]string   `json:"metadata,omitempty"`
	Created        time.Time           `json:"created"`
	Updated        time.Time           `json:"updated"`
}

MPCWallet represents a multi-party computation wallet.

type NodeOptions

type NodeOptions struct {
	OrgID    string
	Metadata map[string]string
}

NodeOptions holds options for node registration.

type Secret

type Secret struct {
	ID          string            `json:"id"`
	Name        string            `json:"name"`
	Version     int               `json:"version"`
	KeyID       string            `json:"keyId"`       // KMS key used for encryption
	Environment string            `json:"environment"` // dev, staging, prod
	Path        string            `json:"path"`        // Folder path
	Value       []byte            `json:"value"`       // Encrypted value
	Nonce       []byte            `json:"nonce"`
	Tags        []string          `json:"tags,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
	OrgID       string            `json:"orgId,omitempty"`
	ProjectID   string            `json:"projectId,omitempty"`
	Created     time.Time         `json:"created"`
	Updated     time.Time         `json:"updated"`
}

Secret represents a stored secret.

type SecretOptions

type SecretOptions struct {
	KeyID       string
	Environment string
	Path        string
	Tags        []string
	Metadata    map[string]string
	OrgID       string
	ProjectID   string
}

SecretOptions holds options for secret creation.

type SecretResponse

type SecretResponse struct {
	ID          string `json:"id"`
	SecretKey   string `json:"secretKey"`
	SecretValue string `json:"secretValue,omitempty"`
	Version     int    `json:"version"`
	Type        string `json:"type"`
	Environment string `json:"environment"`
	SecretPath  string `json:"secretPath"`
}

Secret response matching kms-go SDK Secret model

type Server

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

Server provides the HTTP API for KMS operations. API is compatible with the kms-go SDK client at github.com/luxfi/kms-go

func NewServer

func NewServer(kms *KMS, cfg *ServerConfig) *Server

NewServer creates a new KMS HTTP server.

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server.

func (*Server) Stop

func (s *Server) Stop(ctx context.Context) error

Stop gracefully shuts down the server.

type ServerConfig

type ServerConfig struct {
	Addr           string
	ReadTimeout    time.Duration
	WriteTimeout   time.Duration
	MaxHeaderBytes int
	CORSOrigins    []string
	APIKey         string // Simple API key authentication
	EnableMPC      bool
	EnableSecrets  bool
}

ServerConfig holds server configuration.

func DefaultServerConfig

func DefaultServerConfig() *ServerConfig

DefaultServerConfig returns default server configuration.

type SigningOptions

type SigningOptions struct {
	Message   []byte
	ExpiresIn time.Duration
	Metadata  map[string]string
}

SigningOptions holds options for signing requests.

type SigningStatus

type SigningStatus string

SigningStatus represents the status of a signing request.

const (
	SigningStatusPending    SigningStatus = "pending"
	SigningStatusCollecting SigningStatus = "collecting"
	SigningStatusComplete   SigningStatus = "complete"
	SigningStatusFailed     SigningStatus = "failed"
	SigningStatusExpired    SigningStatus = "expired"
)

type StorageBackend

type StorageBackend interface {
	// Key operations
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, value []byte) error
	SetWithTTL(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	Exists(ctx context.Context, key string) (bool, error)

	// Iteration
	List(ctx context.Context, prefix string) ([]string, error)
	Scan(ctx context.Context, prefix string, fn func(key string, value []byte) error) error

	// Transaction support
	BeginTx(ctx context.Context) (Transaction, error)

	// Lifecycle
	Close() error
}

StorageBackend defines the storage interface for KMS operations.

type Transaction

type Transaction interface {
	Get(key string) ([]byte, error)
	Set(key string, value []byte) error
	Delete(key string) error
	Commit() error
	Rollback() error
}

Transaction represents a storage transaction.

type WalletOptions

type WalletOptions struct {
	OrgID     string
	ProjectID string
	Metadata  map[string]string
}

WalletOptions holds options for wallet creation.

Jump to

Keyboard shortcuts

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