Files
upstream-seaweedfs/weed/kms/config.go
upstream-mirror 89f5be005d
Some checks failed
go: build dev binaries / cleanup (push) Successful in 4s
Codespell / Check for spelling errors (push) Failing after 3s
docker: build dev containers / build-rust-binaries (amd64, x86_64-unknown-linux-musl) (push) Failing after 3s
docker: build dev containers / build-dev-containers (push) Has been skipped
docker: build dev containers / build-rust-binaries (arm64, true, aarch64-unknown-linux-musl) (push) Failing after 3s
End to End / FUSE Mount (push) Failing after 2s
EC Integration Tests / EC Integration Tests (push) Failing after 30s
FUSE DLM Integration Tests / FUSE DLM Integration Tests (push) Failing after 3s
FUSE Volume Server Failover Tests / FUSE Volume Server Failover (push) Failing after 3s
FUSE Integration Tests / FUSE Integration Testing (push) Failing after 2s
FUSE P2P Peer Chunk Sharing Integration Tests / FUSE P2P Peer Chunk Sharing (push) Failing after 3s
go: build binary / Go Vet (push) Failing after 2s
go: build binary / Go Vet 32-bit (push) Failing after 3s
go: build binary / Build (push) Failing after 4s
go: build binary / Build cross-platform (freebsd/amd64) (push) Failing after 3s
go: build binary / Build cross-platform (windows/amd64) (push) Failing after 3s
go: build binary / Build cross-platform (darwin/arm64) (push) Failing after 3s
go: build binary / Build cross-platform (windows/arm64) (push) Failing after 3s
go: build binary / Test (push) Failing after 2s
go: build binary / Test 32-bit (push) Failing after 3s
helm: lint and test charts / lint-test (push) Failing after 3s
Java Client Integration Tests / Java Integration Tests (11) (push) Failing after 3s
Java Client Integration Tests / Java Integration Tests (17) (push) Failing after 3s
go: build dev binaries / build_dev_linux_windows (amd64, linux) (push) Failing after 2s
go: build dev binaries / build_dev_linux_windows (amd64, windows) (push) Failing after 3s
go: build dev binaries / build_dev_darwin (amd64, darwin) (push) Has been skipped
go: build dev binaries / build_dev_darwin (arm64, darwin) (push) Has been skipped
Java Client Unit Tests / Java Unit Tests (11) (push) Failing after 3s
Java Client Unit Tests / Java Unit Tests (17) (push) Failing after 2s
Java Client Unit Tests / Java Unit Tests (21) (push) Failing after 3s
Java Client Unit Tests / Java Unit Tests (8) (push) Failing after 3s
Kafka Quick Test (Load Test with Schema Registry) / Kafka Client Load Test (Quick) (push) Failing after 3s
Kafka Gateway Tests / Kafka Unit Tests (unit-tests-1) (push) Failing after 11s
Kafka Gateway Tests / Kafka Integration Tests (Critical) (integration-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka End-to-End Tests (with SMQ) (e2e-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka Consumer Group Tests (Highly Isolated) (consumer-group-1) (push) Failing after 2s
Kafka Gateway Tests / Kafka Client Compatibility (with SMQ) (client-compat-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka SMQ Integration Tests (Full Stack) (smq-integration-1) (push) Failing after 3s
Kafka Gateway Tests / Kafka Protocol Tests (Isolated) (protocol-1) (push) Failing after 3s
KMS Tests / KMS Provider Integration Tests (push) Failing after 2s
KMS Tests / S3 KMS End-to-End Tests (push) Failing after 3s
Master Cold Start Tests / Master Cold Start Tests (push) Failing after 4s
Metadata Subscribe Integration Tests / Metadata Subscribe Integration Tests (push) Failing after 3s
Multi-Master Tests / Multi-Master Failover Tests (push) Failing after 3s
Performance / CPU and Heap Profile (push) Failing after 2s
Performance / S3 Read/Write Benchmark (rust volume) (push) Failing after 3s
pjdfstest POSIX Compliance / pjdfstest (push) Failing after 2s
Plugin Worker Integration Tests / Plugin Worker: erasure_coding (push) Failing after 3s
Plugin Worker Integration Tests / Plugin Worker: vacuum (push) Failing after 3s
Rust Volume Server Tests / Rust Integration Tests (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 1) (push) Failing after 2s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 1) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 2) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 2) (push) Failing after 3s
Rust Volume Server Tests / Go Tests with Rust Volume (grpc - Shard 3) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Distributed Tests (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Performance Tests (push) Failing after 3s
Performance / Throughput Benchmark (go volume) (push) Failing after 3s
Performance / Throughput Benchmark (rust volume) (push) Failing after 2s
Performance / S3 Read/Write Benchmark (go volume) (push) Failing after 3s
Plugin Worker Integration Tests / Plugin Worker: volume_balance (push) Failing after 3s
PostgreSQL Gateway Tests / PostgreSQL Basic Tests (push) Failing after 3s
Rust Volume Server Tests / Rust Unit Tests (push) Failing after 2s
Rust Volume Server Tests / Go Tests with Rust Volume (http - Shard 3) (push) Failing after 3s
Rust Plugin Worker Tests / Rust Plugin Worker Build and Unit Tests (push) Failing after 3s
rust: build dev volume server binaries / cleanup (push) Successful in 3s
S3 ETag and ACL Tests / S3 ETag + ACL Integration Tests (push) Failing after 3s
S3 IAM Integration Tests / IAM Unit Tests (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (advanced) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (basic) (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Integration Tests (group) (push) Failing after 3s
S3 IAM Integration Tests / S3 IAM Integration Tests (policy-enforcement) (push) Failing after 2s
S3 IAM Integration Tests / S3 IAM Integration Tests (sts) (push) Failing after 4s
S3 Keycloak Integration Tests / S3 Keycloak Integration Tests (push) Failing after 3s
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.11) (push) Failing after 3s
S3 PyArrow Parquet Tests / Go Unit Tests (Implicit Directory) (push) Has been cancelled
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.12) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-darwin (darwin-amd64, x86_64-apple-darwin) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-darwin (darwin-arm64, aarch64-apple-darwin) (push) Has been cancelled
rust: build dev volume server binaries / build-rust-volume-dev-linux (linux-amd64, x86_64-unknown-linux-gnu) (push) Has been cancelled
S3 PyArrow Parquet Tests / PyArrow Parquet Tests (Python 3.9) (push) Has been cancelled
S3 Proxy Signature Tests / S3 Proxy Signature Verification Tests (push) Has been cancelled
S3 SDK V2 Route Disambiguation Tests / S3 SDK V2 Routing Tests (push) Has been cancelled
S3 SSE Tests / S3 SSE Integration Tests (quick) (push) Has been cancelled
S3 SSE Tests / S3 SSE Compatibility Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Metadata Persistence Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Copy Operations Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Multipart Upload Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Performance Test (push) Has been cancelled
S3 SSE Tests / S3 Volume Encryption Test (push) Has been cancelled
S3 SSE Tests / S3 SSE Integration Tests (comprehensive) (push) Has been cancelled
Spark Integration Tests / Spark Integration Tests (push) Failing after 2s
Telemetry Integration Tests / telemetry-integration-test (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 1) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 1) (push) Failing after 3s
Ceph S3 tests / Basic S3 tests (KV store) (push) Has been cancelled
Ceph S3 tests / S3 Versioning & Object Lock tests (push) Has been cancelled
S3 Policy Integration Tests / S3 Policy Unit Tests (push) Failing after 3s
Ceph S3 tests / S3 CORS tests (push) Has been cancelled
Ceph S3 tests / SeaweedFS Custom S3 Copy tests (push) Has been cancelled
Ceph S3 tests / Basic S3 tests (SQL store) (push) Has been cancelled
test s3 over https using aws-cli / awscli-tests (push) Has been cancelled
TLS Rotation Integration Tests / TLS Rotation Integration Tests (push) Has been cancelled
Vacuum Integration Tests / Vacuum Integration Tests (push) Has been cancelled
S3 Policy Integration Tests / S3 Policy Variables Integration Tests (push) Failing after 3s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (advanced-policy) (push) Failing after 3s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (basic-policy) (push) Failing after 2s
S3 Policy Integration Tests / S3 Policy Enforcement Integration Tests (contextual-policy) (push) Failing after 4s
S3 Policy Integration Tests / Trusted Proxy Detection Tests (push) Failing after 2s
S3 Policy Integration Tests / S3 Policy Shell Integration Tests (push) Failing after 3s
Samba on FUSE Integration / samba-integration (push) Failing after 2s
SFTP Integration Tests / SFTP Integration Testing (push) Failing after 3s
terraform: validate and test modules / fmt, validate, plan-level tests (push) Failing after 3s
terraform: validate and test modules / local cluster smoke test (real weed) (push) Failing after 2s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 3) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (grpc - Shard 2) (push) Failing after 3s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 2) (push) Failing after 2s
Volume Server Integration Tests / Volume Server Integration Tests (http - Shard 3) (push) Failing after 5s
mount: windows conformance / WinFsp conformance (push) Has been cancelled
mount: windows / Mount on Windows (push) Has been cancelled
snapshot of https://github.com/seaweedfs/seaweedfs.git (master, 2026-09-16; blobs > 131072B omitted)
2026-09-16 03:23:42 +05:00

486 lines
13 KiB
Go

package kms
import (
"context"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// KMSManager manages KMS provider instances and configurations
type KMSManager struct {
mu sync.RWMutex
providers map[string]KMSProvider // provider name -> provider instance
configs map[string]*KMSConfig // provider name -> configuration
bucketKMS map[string]string // bucket name -> provider name
defaultKMS string // default KMS provider name
}
// KMSConfig represents a complete KMS provider configuration
type KMSConfig struct {
Provider string `json:"provider"` // Provider type (aws, azure, gcp, local)
Config map[string]interface{} `json:"config"` // Provider-specific configuration
CacheEnabled bool `json:"cache_enabled"` // Enable data key caching
CacheTTL time.Duration `json:"cache_ttl"` // Cache TTL (default: 1 hour)
MaxCacheSize int `json:"max_cache_size"` // Maximum cached keys (default: 1000)
}
// BucketKMSConfig represents KMS configuration for a specific bucket
type BucketKMSConfig struct {
Provider string `json:"provider"` // KMS provider to use
KeyID string `json:"key_id"` // Default KMS key ID for this bucket
BucketKey bool `json:"bucket_key"` // Enable S3 Bucket Keys optimization
Context map[string]string `json:"context"` // Additional encryption context
Enabled bool `json:"enabled"` // Whether KMS encryption is enabled
}
// configAdapter adapts KMSConfig.Config to util.Configuration interface
type configAdapter struct {
config map[string]interface{}
}
// GetConfigMap returns the underlying configuration map for direct access
func (c *configAdapter) GetConfigMap() map[string]interface{} {
return c.config
}
func (c *configAdapter) GetString(key string) string {
if val, ok := c.config[key]; ok {
if str, ok := val.(string); ok {
return str
}
}
return ""
}
func (c *configAdapter) GetBool(key string) bool {
if val, ok := c.config[key]; ok {
if b, ok := val.(bool); ok {
return b
}
}
return false
}
func (c *configAdapter) GetInt(key string) int {
if val, ok := c.config[key]; ok {
if i, ok := val.(int); ok {
return i
}
if f, ok := val.(float64); ok {
return int(f)
}
}
return 0
}
func (c *configAdapter) GetStringSlice(key string) []string {
if val, ok := c.config[key]; ok {
if slice, ok := val.([]string); ok {
return slice
}
if interfaceSlice, ok := val.([]interface{}); ok {
result := make([]string, len(interfaceSlice))
for i, v := range interfaceSlice {
if str, ok := v.(string); ok {
result[i] = str
}
}
return result
}
}
return nil
}
func (c *configAdapter) SetDefault(key string, value interface{}) {
if c.config == nil {
c.config = make(map[string]interface{})
}
if _, exists := c.config[key]; !exists {
c.config[key] = value
}
}
var (
globalKMSManager *KMSManager
globalKMSMutex sync.RWMutex
// Global KMS provider for legacy compatibility
globalKMSProvider KMSProvider
)
// InitializeGlobalKMS initializes the global KMS provider
func InitializeGlobalKMS(config *KMSConfig) error {
if config == nil || config.Provider == "" {
return fmt.Errorf("KMS configuration is required")
}
// Adapt the config to util.Configuration interface
var providerConfig util.Configuration
if config.Config != nil {
providerConfig = &configAdapter{config: config.Config}
}
provider, err := GetProvider(config.Provider, providerConfig)
if err != nil {
return err
}
provider = wrapWithCacheIfEnabled(provider, config)
globalKMSMutex.Lock()
defer globalKMSMutex.Unlock()
// Close existing provider if any
if globalKMSProvider != nil {
globalKMSProvider.Close()
}
globalKMSProvider = provider
return nil
}
// GetGlobalKMS returns the global KMS provider
func GetGlobalKMS() KMSProvider {
globalKMSMutex.RLock()
defer globalKMSMutex.RUnlock()
return globalKMSProvider
}
// IsKMSEnabled returns true if KMS is enabled globally
func IsKMSEnabled() bool {
return GetGlobalKMS() != nil
}
// SetGlobalKMSProvider sets the global KMS provider.
// This is mainly for backward compatibility.
func SetGlobalKMSProvider(provider KMSProvider) {
globalKMSMutex.Lock()
defer globalKMSMutex.Unlock()
// Close existing provider if any
if globalKMSProvider != nil {
globalKMSProvider.Close()
}
globalKMSProvider = provider
}
// InitializeKMSManager initializes the global KMS manager
func InitializeKMSManager() *KMSManager {
globalKMSMutex.Lock()
defer globalKMSMutex.Unlock()
if globalKMSManager == nil {
globalKMSManager = &KMSManager{
providers: make(map[string]KMSProvider),
configs: make(map[string]*KMSConfig),
bucketKMS: make(map[string]string),
}
glog.V(1).Infof("KMS Manager initialized")
}
return globalKMSManager
}
// GetKMSManager returns the global KMS manager
func GetKMSManager() *KMSManager {
globalKMSMutex.RLock()
manager := globalKMSManager
globalKMSMutex.RUnlock()
if manager == nil {
return InitializeKMSManager()
}
return manager
}
// AddKMSProvider adds a KMS provider configuration
func (km *KMSManager) AddKMSProvider(name string, config *KMSConfig) error {
if name == "" {
return fmt.Errorf("provider name cannot be empty")
}
if config == nil {
return fmt.Errorf("KMS configuration cannot be nil")
}
km.mu.Lock()
defer km.mu.Unlock()
// Close existing provider if it exists
if existingProvider, exists := km.providers[name]; exists {
if err := existingProvider.Close(); err != nil {
glog.Errorf("Failed to close existing KMS provider %s: %v", name, err)
}
}
// Create new provider instance
configAdapter := &configAdapter{config: config.Config}
provider, err := GetProvider(config.Provider, configAdapter)
if err != nil {
return fmt.Errorf("failed to create KMS provider %s: %w", name, err)
}
// Wrap with a decrypted-data-key cache when enabled so repeated reads of
// the same SSE-KMS object avoid a KMS round-trip per read.
provider = wrapWithCacheIfEnabled(provider, config)
// Store provider and configuration
km.providers[name] = provider
km.configs[name] = config
glog.V(1).Infof("Added KMS provider %s (type: %s)", name, config.Provider)
return nil
}
// SetDefaultKMSProvider sets the default KMS provider
func (km *KMSManager) SetDefaultKMSProvider(name string) error {
km.mu.RLock()
_, exists := km.providers[name]
km.mu.RUnlock()
if !exists {
return fmt.Errorf("KMS provider %s does not exist", name)
}
km.mu.Lock()
km.defaultKMS = name
km.mu.Unlock()
glog.V(1).Infof("Set default KMS provider to %s", name)
return nil
}
// SetBucketKMSProvider sets the KMS provider for a specific bucket
func (km *KMSManager) SetBucketKMSProvider(bucket, providerName string) error {
if bucket == "" {
return fmt.Errorf("bucket name cannot be empty")
}
km.mu.RLock()
_, exists := km.providers[providerName]
km.mu.RUnlock()
if !exists {
return fmt.Errorf("KMS provider %s does not exist", providerName)
}
km.mu.Lock()
km.bucketKMS[bucket] = providerName
km.mu.Unlock()
glog.V(2).Infof("Set KMS provider for bucket %s to %s", bucket, providerName)
return nil
}
// GetKMSProvider returns the KMS provider for a bucket (or default if not configured)
func (km *KMSManager) GetKMSProvider(bucket string) (KMSProvider, error) {
km.mu.RLock()
defer km.mu.RUnlock()
// Try bucket-specific provider first
if bucket != "" {
if providerName, exists := km.bucketKMS[bucket]; exists {
if provider, exists := km.providers[providerName]; exists {
return provider, nil
}
}
}
// Fall back to default provider
if km.defaultKMS != "" {
if provider, exists := km.providers[km.defaultKMS]; exists {
return provider, nil
}
}
// No provider configured
return nil, fmt.Errorf("no KMS provider configured for bucket %s", bucket)
}
// GetKMSProviderByName returns a specific KMS provider by name
func (km *KMSManager) GetKMSProviderByName(name string) (KMSProvider, error) {
km.mu.RLock()
defer km.mu.RUnlock()
provider, exists := km.providers[name]
if !exists {
return nil, fmt.Errorf("KMS provider %s not found", name)
}
return provider, nil
}
// ListKMSProviders returns all configured KMS provider names
func (km *KMSManager) ListKMSProviders() []string {
km.mu.RLock()
defer km.mu.RUnlock()
names := make([]string, 0, len(km.providers))
for name := range km.providers {
names = append(names, name)
}
return names
}
// GetBucketKMSProvider returns the KMS provider name for a bucket
func (km *KMSManager) GetBucketKMSProvider(bucket string) string {
km.mu.RLock()
defer km.mu.RUnlock()
if providerName, exists := km.bucketKMS[bucket]; exists {
return providerName
}
return km.defaultKMS
}
// RemoveKMSProvider removes a KMS provider
func (km *KMSManager) RemoveKMSProvider(name string) error {
km.mu.Lock()
defer km.mu.Unlock()
provider, exists := km.providers[name]
if !exists {
return fmt.Errorf("KMS provider %s does not exist", name)
}
// Close the provider
if err := provider.Close(); err != nil {
glog.Errorf("Failed to close KMS provider %s: %v", name, err)
}
// Remove from maps
delete(km.providers, name)
delete(km.configs, name)
// Remove from bucket associations
for bucket, providerName := range km.bucketKMS {
if providerName == name {
delete(km.bucketKMS, bucket)
}
}
// Clear default if it was this provider
if km.defaultKMS == name {
km.defaultKMS = ""
}
glog.V(1).Infof("Removed KMS provider %s", name)
return nil
}
// Close closes all KMS providers and cleans up resources
func (km *KMSManager) Close() error {
km.mu.Lock()
defer km.mu.Unlock()
var allErrors []error
for name, provider := range km.providers {
if err := provider.Close(); err != nil {
allErrors = append(allErrors, fmt.Errorf("failed to close KMS provider %s: %w", name, err))
}
}
// Clear all maps
km.providers = make(map[string]KMSProvider)
km.configs = make(map[string]*KMSConfig)
km.bucketKMS = make(map[string]string)
km.defaultKMS = ""
if len(allErrors) > 0 {
return fmt.Errorf("errors closing KMS providers: %v", allErrors)
}
glog.V(1).Infof("KMS Manager closed")
return nil
}
// GenerateDataKeyForBucket generates a data key using the appropriate KMS provider for a bucket
func (km *KMSManager) GenerateDataKeyForBucket(ctx context.Context, bucket, keyID string, keySpec KeySpec, encryptionContext map[string]string) (*GenerateDataKeyResponse, error) {
provider, err := km.GetKMSProvider(bucket)
if err != nil {
return nil, fmt.Errorf("failed to get KMS provider for bucket %s: %w", bucket, err)
}
req := &GenerateDataKeyRequest{
KeyID: keyID,
KeySpec: keySpec,
EncryptionContext: encryptionContext,
}
return provider.GenerateDataKey(ctx, req)
}
// DecryptForBucket decrypts a data key using the appropriate KMS provider for a bucket
func (km *KMSManager) DecryptForBucket(ctx context.Context, bucket string, ciphertextBlob []byte, encryptionContext map[string]string) (*DecryptResponse, error) {
provider, err := km.GetKMSProvider(bucket)
if err != nil {
return nil, fmt.Errorf("failed to get KMS provider for bucket %s: %w", bucket, err)
}
req := &DecryptRequest{
CiphertextBlob: ciphertextBlob,
EncryptionContext: encryptionContext,
}
return provider.Decrypt(ctx, req)
}
// ValidateKeyForBucket validates that a KMS key exists and is usable for a bucket
func (km *KMSManager) ValidateKeyForBucket(ctx context.Context, bucket, keyID string) error {
provider, err := km.GetKMSProvider(bucket)
if err != nil {
return fmt.Errorf("failed to get KMS provider for bucket %s: %w", bucket, err)
}
req := &DescribeKeyRequest{KeyID: keyID}
resp, err := provider.DescribeKey(ctx, req)
if err != nil {
return fmt.Errorf("failed to validate key %s for bucket %s: %w", keyID, bucket, err)
}
// Check key state
if resp.KeyState != KeyStateEnabled {
return fmt.Errorf("key %s is not enabled (state: %s)", keyID, resp.KeyState)
}
// Check key usage
if resp.KeyUsage != KeyUsageEncryptDecrypt && resp.KeyUsage != KeyUsageGenerateDataKey {
return fmt.Errorf("key %s cannot be used for encryption (usage: %s)", keyID, resp.KeyUsage)
}
return nil
}
// GetKMSHealth returns health status of all KMS providers
func (km *KMSManager) GetKMSHealth(ctx context.Context) map[string]error {
km.mu.RLock()
defer km.mu.RUnlock()
health := make(map[string]error)
for name, provider := range km.providers {
// Try to perform a basic operation to check health
// We'll use DescribeKey with a dummy key - the error will tell us if KMS is reachable
req := &DescribeKeyRequest{KeyID: "health-check-dummy-key"}
_, err := provider.DescribeKey(ctx, req)
// If it's a "not found" error, KMS is healthy but key doesn't exist (expected)
if kmsErr, ok := err.(*KMSError); ok && kmsErr.Code == ErrCodeNotFoundException {
health[name] = nil // Healthy
} else if err != nil {
health[name] = err // Unhealthy
} else {
health[name] = nil // Healthy (shouldn't happen with dummy key, but just in case)
}
}
return health
}