Files
seaweedfs/weed/kms/config_loader.go
T
7c41ed0635 kms: swap a reload's providers in as a whole, after S3 parses its identities (#13344)
* kms: build every provider before a reload swaps them in

A reload replaced the providers one at a time, closing each old instance
as its replacement went in, and kept the providers and bucket mappings
the config no longer listed. Between closing the old default instance and
setting the new global provider, S3 could get the closed instance. A
reload now builds every provider first and swaps the whole set in at
once, along with the default, the bucket mappings and the global
provider. The default provider failing still fails the reload, and then
nothing changes. Any other provider that fails keeps its previous
instance. Providers the config no longer lists are dropped, and a bucket
mapped to one falls back to the default. A manager other than the global
one no longer sets the global provider. The manager no longer keeps the
provider configurations, which nothing read. Each load health-checks
every provider once, after the swap, for filer.toml as for the identities
file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: parse the identities before loading KMS

Loading the S3 config loaded KMS before parsing the identities, so a file
whose identities didn't parse still replaced the KMS providers. A file
without a kms block left the previous providers in place, and one with a
number out of float64 range, which protojson accepts, skipped KMS without
an error.

The identities are now parsed first, and a file that fails there changes
neither. A file without a kms block drops the providers, so a reload that
took the block out turns SSE-KMS off. A file encoding/json can't read
fails the KMS load with an error that doesn't quote it, as it could quote
key material. A KMS load that fails is logged as an error, not a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kms: skip a bucket mapping with an empty bucket name

SetBucketKMSProvider refused an empty bucket name, which the rebuilt
mappings no longer went through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* kms: check a rejected load leaves the installed provider open

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-12-03 10:34:45 -08:00

253 lines
7.4 KiB
Go

package kms
import (
"context"
"fmt"
"sort"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
)
// ViperConfig interface extends Configuration with additional methods needed for KMS configuration
type ViperConfig interface {
GetString(key string) string
GetBool(key string) bool
GetInt(key string) int
GetStringSlice(key string) []string
SetDefault(key string, value interface{})
GetStringMap(key string) map[string]interface{}
IsSet(key string) bool
}
// ConfigLoader handles loading KMS configurations from filer.toml
type ConfigLoader struct {
viper ViperConfig
manager *KMSManager
}
// NewConfigLoader creates a new KMS configuration loader
func NewConfigLoader(v ViperConfig) *ConfigLoader {
return &ConfigLoader{
viper: v,
manager: GetKMSManager(),
}
}
// LoadConfigurations loads all KMS provider configurations from filer.toml
func (loader *ConfigLoader) LoadConfigurations() error {
// Check if KMS section exists
if !loader.viper.IsSet("kms") {
glog.V(1).Infof("No KMS configuration found in filer.toml")
return nil
}
// Viper lowercases table names but not string values, so the values that name a provider
// are lowercased to match.
settings, err := parseKMSSettings(loader.viper.GetStringMap("kms"), strings.ToLower)
if err != nil {
return err
}
return loader.load(settings)
}
func (loader *ConfigLoader) load(s *kmsSettings) error {
// S3 wraps and unwraps data keys with the default provider alone, so it comes from this
// config.
if _, listed := s.providers[s.defaultProvider]; s.defaultProvider != "" && !listed {
return fmt.Errorf("default KMS provider %s isn't listed under providers", s.defaultProvider)
}
if s.defaultProvider == "" && len(s.names) > 0 {
s.defaultProvider = s.names[0]
if len(s.names) > 1 {
glog.Warningf("KMS default_provider isn't set, so S3 uses %s, the first provider by name. Adding a provider whose name sorts first would switch S3 to it, and objects encrypted before would be unreadable until default_provider names %s", s.defaultProvider, s.defaultProvider)
}
}
if err := loader.manager.load(s); err != nil {
return fmt.Errorf("failed to load KMS providers: %w", err)
}
glog.V(1).Infof("KMS configuration loaded successfully")
return loader.ValidateConfiguration()
}
type kmsSettings struct {
// providers holds each provider's entry as given, parsed when it's built, so an invalid
// one fails the load only if it's the default provider, like one that fails to build.
providers map[string]interface{}
names []string
defaultProvider string
buckets map[string]string
}
func parseKMSSettings(kmsConfig map[string]interface{}, providerName func(string) string) (*kmsSettings, error) {
s := &kmsSettings{providers: make(map[string]interface{}), buckets: make(map[string]string)}
providers, err := section(kmsConfig, "providers")
if err != nil {
return nil, err
}
for name, raw := range providers {
if name == "" {
glog.Errorf("Skipping a KMS provider with an empty name")
continue
}
s.providers[name] = raw
s.names = append(s.names, name)
}
sort.Strings(s.names)
switch defaultProvider := kmsConfig["default_provider"].(type) {
case nil:
case string:
s.defaultProvider = providerName(defaultProvider)
default:
return nil, fmt.Errorf("default_provider must be a string, got %T", defaultProvider)
}
buckets, err := section(kmsConfig, "buckets")
if err != nil {
return nil, err
}
for bucket, raw := range buckets {
if bucket == "" {
glog.Errorf("Skipping a KMS bucket mapping with an empty bucket name")
continue
}
fields, ok := raw.(map[string]interface{})
if !ok {
glog.Errorf("Invalid KMS configuration for bucket %s, skipping the mapping", bucket)
continue
}
provider, exists := fields["provider"]
if !exists {
continue
}
name, ok := provider.(string)
if !ok {
glog.Errorf("KMS provider for bucket %s must be a string, got %T, skipping the mapping", bucket, provider)
continue
}
s.buckets[bucket] = providerName(name)
}
return s, nil
}
func section(config map[string]interface{}, key string) (map[string]interface{}, error) {
switch table := config[key].(type) {
case nil:
return nil, nil
case map[string]interface{}:
return table, nil
default:
return nil, fmt.Errorf("invalid KMS %s configuration", key)
}
}
func kmsProviderConfig(providerName string, raw interface{}) (*KMSConfig, error) {
config, ok := raw.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("invalid configuration for KMS provider %s", providerName)
}
// Get provider type
providerType, exists := config["type"]
if !exists {
return nil, fmt.Errorf("provider type not specified for %s", providerName)
}
providerTypeStr, ok := providerType.(string)
if !ok {
return nil, fmt.Errorf("invalid provider type for %s", providerName)
}
// Get provider-specific configuration
providerConfig := make(map[string]interface{})
for key, value := range config {
if key != "type" {
providerConfig[key] = value
}
}
// Set default cache settings if not specified
settings := &configAdapter{config: providerConfig}
settings.SetDefault("cache_enabled", true)
settings.SetDefault("cache_ttl", "1h")
settings.SetDefault("max_cache_size", DefaultDataKeyCacheSize)
cacheEnabled, err := typed[bool](settings, "cache_enabled")
if err != nil {
return nil, fmt.Errorf("invalid configuration for KMS provider %s: %w", providerName, err)
}
ttl, err := typed[string](settings, "cache_ttl")
if err != nil {
return nil, fmt.Errorf("invalid configuration for KMS provider %s: %w", providerName, err)
}
cacheTTL, err := time.ParseDuration(ttl)
if err != nil {
return nil, fmt.Errorf("invalid configuration for KMS provider %s: cache_ttl: %w", providerName, err)
}
maxCacheSize, err := typed[int](settings, "max_cache_size")
if err != nil {
return nil, fmt.Errorf("invalid configuration for KMS provider %s: %w", providerName, err)
}
return &KMSConfig{
Provider: providerTypeStr,
Config: providerConfig,
CacheEnabled: cacheEnabled,
CacheTTL: cacheTTL,
MaxCacheSize: maxCacheSize,
}, nil
}
// ValidateConfiguration validates the KMS configuration
func (loader *ConfigLoader) ValidateConfiguration() error {
providers := loader.manager.ListKMSProviders()
if len(providers) == 0 {
glog.V(1).Infof("No KMS providers configured")
return nil
}
// Test connectivity to all providers
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
health := loader.manager.GetKMSHealth(ctx)
hasHealthyProvider := false
for providerName, err := range health {
if err != nil {
glog.Warningf("KMS provider %s is unhealthy: %v", providerName, err)
} else {
hasHealthyProvider = true
glog.V(2).Infof("KMS provider %s is healthy", providerName)
}
}
if !hasHealthyProvider {
glog.Warningf("No healthy KMS providers found")
}
return nil
}
// LoadKMSFromConfig loads KMS configuration directly from parsed JSON data. A nil section,
// which is what a missing or null one in the JSON gives, loads as empty and drops the providers.
func LoadKMSFromConfig(kmsConfig interface{}) error {
if kmsConfig == nil {
kmsConfig = map[string]interface{}{}
}
kmsMap, ok := kmsConfig.(map[string]interface{})
if !ok {
return fmt.Errorf("invalid KMS configuration format")
}
settings, err := parseKMSSettings(kmsMap, func(name string) string { return name })
if err != nil {
return err
}
loader := &ConfigLoader{manager: GetKMSManager()}
return loader.load(settings)
}