mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 02:27:26 +01:00
* Add per-call filer authentication sources and pooled client wrappers * Authenticate gateway filer calls with per-call admin tokens * Authenticate shell admin and synchronization filer calls * Authenticate workers MQ and remaining filer client paths * Cache filer client signing keys and sign subscriptions with the shared key Re-reading security.toml on every filer RPC cost about 125us against 8us for signing. Keep the keys for up to a second, re-reading at once when a WEED_ override or the configuration directory changes. When the file exists but cannot be read, keep the last keys read, else the startup keys, as FilerAdminKeys does, so a process without a key stays tokenless. Metadata subscriptions prefer the shared key, as filer peers do, because older filers verify subscription admin tokens only with it. * Authenticate admin-script, maintenance and filer.conf shell paths Plugin worker admin scripts and master maintenance scripts build their own shell options and carried no filer token source; fs.configure and s3.bucket.quota.check read filer.conf without it. * filer.cat: report a failed read; isolate key overrides in the admin-script test filer.cat ignored the error from its filer call and exited successfully, leaving a truncated -output file. Report the error and exit with failure. The admin-script token test now clears the WEED_ signing-key overrides, which take precedence over security.toml. * security: refuse gRPC keys too short to sign; query engine uses client TLS Under GODEBUG=fips140=only, hmac.New panics on keys under 14 bytes. The startup check now covers jwt.filer_signing.grpc_key and grpc_previous_key, and filer client token sources check the keys they read, so a reloaded or per-endpoint security file with a short key is refused instead of panicking when the next RPC signs. The query engine's broker client dialed every master, filer and broker in plaintext, so the admin token it now sends could cross the network in the clear. It dials with the grpc.client TLS settings instead, and weed-sql loads security.toml as weed-db does. * security: per-endpoint admin tokens ignore WEED_ key overrides FilerAdminTokenFromFile honored WEED_JWT_FILER_SIGNING_GRPC_KEY and WEED_JWT_FILER_SIGNING_KEY. Those are process-wide, so filer.sync with -a.security and -b.security signed both clusters' admin tokens with the one key, handing each cluster a token valid on the other. A per-endpoint file now supplies its own keys only. * weed-sql, weed-db: refuse to start on an unreadable security.toml Both only warned when security.toml was present but could not be read or parsed. They then dialed without the grpc.client TLS settings while the filer token source could still sign admin tokens from WEED_ environment keys, so the tokens could travel in plaintext. They now exit with an error that does not quote the file; a missing file is still fine. * pb: take the filer token source in WithGrpcFilerClient and WithOneOfGrpcFilerClients Fold WithGrpcFilerClientAuth and WithOneOfGrpcFilerClientsAuth into the existing helpers instead of keeping two names for each. Callers without a token source pass nil. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * util: return the read error from ReadConfiguration Fold ReadConfigurationWithError into ReadConfiguration. The error is returned and not logged, since parser errors can quote values; the existing reload callers already warn when no file was read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * security: keep the test-only filerAdminToken helper in the test It had no production caller. The test helper now resolves keys through filerClientKeysFrom, as the token sources do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * util: read security.toml once in LoadSecurityConfigurationOrError It validated the file, then merged it with a second read whose failure was ignored and whose parser error was logged. It now merges with one read and logs nothing from the parser. Viper's search also treats a directory the process cannot search as holding no file; a candidate that cannot be checked for lack of permission is now refused too. * security: verify admin subscription tokens with the gRPC clock leeway CheckGrpcMetadataSubscription checked admin tokens strictly, while unary filer calls allow jwt.filer_signing.clock_leeway_seconds. With ten-second client admin tokens, a subscriber whose clock trailed the filer's by more than ten seconds was refused with a matching key. It now takes the leeway, and the filer passes its configured one. The leeway check moves from the server package to security.IsFilerAdminTokenWithLeeway so both use it. * util: start without security.toml only when every candidate is confirmed absent A candidate whose check fails for any reason other than not existing, such as a symlink loop, is refused like one the process cannot search. --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
317 lines
9.1 KiB
Go
317 lines
9.1 KiB
Go
package util
|
|
|
|
import (
|
|
"errors"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
)
|
|
|
|
var (
|
|
ConfigurationFileDirectory DirectoryValueType
|
|
loadSecurityConfigOnce sync.Once
|
|
)
|
|
|
|
type DirectoryValueType string
|
|
|
|
func (s *DirectoryValueType) Set(value string) error {
|
|
*s = DirectoryValueType(value)
|
|
return nil
|
|
}
|
|
func (s *DirectoryValueType) String() string {
|
|
return string(*s)
|
|
}
|
|
|
|
type Configuration interface {
|
|
GetString(key string) string
|
|
GetBool(key string) bool
|
|
GetInt(key string) int
|
|
GetStringSlice(key string) []string
|
|
SetDefault(key string, value interface{})
|
|
}
|
|
|
|
// securityConfigFile names the security.toml that LoadConfiguration read, or
|
|
// "security.toml" when the settings came from the environment only.
|
|
func securityConfigFile() string {
|
|
if f := viper.ConfigFileUsed(); f != "" {
|
|
return f
|
|
}
|
|
return "security.toml"
|
|
}
|
|
|
|
// LoadSecurityConfiguration merges security.toml once per process and exits
|
|
// when fips.mode does not match the fips140 GODEBUG (RequireFipsMode) or a
|
|
// JWT signing key is too short for GODEBUG=fips140=only; outside that mode it
|
|
// warns about such a key.
|
|
func LoadSecurityConfiguration() {
|
|
loadSecurityConfigOnce.Do(func() {
|
|
LoadConfiguration("security", false)
|
|
RequireFipsMode()
|
|
if err := CheckFips140SigningKeys(securityConfigFile(), GetViper()); err != nil {
|
|
glog.Fatalf("%s: this process runs with GODEBUG=fips140=only, and stops because %v; replace them on every server that uses them, with or without downtime, see %s",
|
|
securityConfigFile(), err, JwtSigningKeysWiki)
|
|
}
|
|
})
|
|
}
|
|
|
|
// errSecurityConfigUnreadable leaves out the parser error, which can quote
|
|
// configuration values.
|
|
var errSecurityConfigUnreadable = errors.New("security.toml exists but cannot be read or parsed; fix it or remove it, since running without its TLS settings would send credentials in plaintext")
|
|
|
|
// LoadSecurityConfigurationOrError is LoadConfiguration("security", false) for
|
|
// clients that must not start without the settings a present security.toml
|
|
// holds: a missing file is fine, an unreadable or malformed one is an error.
|
|
// The file is read once, and its parser error is not logged because it can
|
|
// quote configuration values.
|
|
func LoadSecurityConfigurationOrError() error {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
setConfigurationPaths(viper.GetViper(), "security")
|
|
err := viper.MergeInConfig()
|
|
var notFound viper.ConfigFileNotFoundError
|
|
if err == nil || (errors.As(err, ¬Found) && !configurationSearchDenied("security")) {
|
|
return nil
|
|
}
|
|
return errSecurityConfigUnreadable
|
|
}
|
|
|
|
// configurationSearchDenied reports whether a candidate configFileName file
|
|
// could not be confirmed absent: its check failed for a reason other than the
|
|
// file, or a directory on its path, not existing (lack of permission, a symlink
|
|
// loop). Viper's search treats any such failure as absence, which would hide a
|
|
// file the process cannot read.
|
|
func configurationSearchDenied(configFileName string) bool {
|
|
for _, dir := range configurationPaths() {
|
|
dir = os.ExpandEnv(dir)
|
|
for _, ext := range viper.SupportedExts {
|
|
_, err := os.Stat(filepath.Join(dir, configFileName+"."+ext))
|
|
if err != nil && !errors.Is(err, fs.ErrNotExist) && !errors.Is(err, syscall.ENOTDIR) {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func LoadConfiguration(configFileName string, required bool) (loaded bool) {
|
|
// MergeInConfig mutates the shared viper that ViperProxy serializes;
|
|
// take the same lock so a merge cannot race a reader or SetDefault.
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
|
|
setConfigurationPaths(viper.GetViper(), configFileName)
|
|
if err := viper.MergeInConfig(); err != nil { // Handle errors reading the config file
|
|
if strings.Contains(err.Error(), "Not Found") {
|
|
glog.V(1).Infof("Reading %s: %v", viper.ConfigFileUsed(), err)
|
|
} else {
|
|
// If the config is required, fail immediately
|
|
if required {
|
|
glog.Fatalf("Reading %s: %v", viper.ConfigFileUsed(), err)
|
|
}
|
|
// If the config is optional, log a warning but don't crash
|
|
glog.Warningf("Reading %s: %v. Skipping optional configuration.", viper.ConfigFileUsed(), err)
|
|
}
|
|
if required {
|
|
glog.Fatalf("Failed to load %s.toml file from current directory, or $HOME/.seaweedfs/, or /etc/seaweedfs/"+
|
|
"\n\nPlease use this command to generate the default %s.toml file\n"+
|
|
" weed scaffold -config=%s -output=.\n\n\n",
|
|
configFileName, configFileName, configFileName)
|
|
}
|
|
return false
|
|
}
|
|
glog.V(1).Infof("Reading %s.toml from %s", configFileName, viper.ConfigFileUsed())
|
|
|
|
return true
|
|
}
|
|
|
|
// ReadConfiguration reads configFileName into a new viper with the WEED_
|
|
// environment overrides. Unlike LoadConfiguration it does not merge, so a key
|
|
// the file no longer sets reads as unset. A non-empty configFile is read in
|
|
// place of searching the configuration directories. used is the file read, or
|
|
// empty when none could be; the environment still applies then. The read
|
|
// error is returned rather than logged: parser errors can quote values.
|
|
func ReadConfiguration(configFileName, configFile string) (v *ViperProxy, used string, readErr error) {
|
|
fresh := viper.New()
|
|
setEnvOverrides(fresh)
|
|
if configFile != "" {
|
|
fresh.SetConfigFile(configFile)
|
|
} else {
|
|
setConfigurationPaths(fresh, configFileName)
|
|
}
|
|
if err := fresh.ReadInConfig(); err != nil {
|
|
return NewViperProxy(fresh), "", err
|
|
}
|
|
return NewViperProxy(fresh), fresh.ConfigFileUsed(), nil
|
|
}
|
|
|
|
// configurationPaths are the directories searched for configuration files,
|
|
// in order.
|
|
func configurationPaths() []string {
|
|
return []string{ResolvePath(ConfigurationFileDirectory.String()), ".", "$HOME/.seaweedfs", "/usr/local/etc/seaweedfs/", "/etc/seaweedfs/"}
|
|
}
|
|
|
|
func setConfigurationPaths(v *viper.Viper, configFileName string) {
|
|
v.SetConfigName(configFileName)
|
|
for _, dir := range configurationPaths() {
|
|
v.AddConfigPath(dir)
|
|
}
|
|
}
|
|
|
|
func setEnvOverrides(v *viper.Viper) {
|
|
v.AutomaticEnv()
|
|
v.SetEnvPrefix("weed")
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
|
}
|
|
|
|
// ViperProxy serializes access to the global viper. The wrapped Viper is a
|
|
// named field, not embedded, so every method must be declared here under the
|
|
// mutex — a promoted method would take no lock and race, e.g. GetStringMap
|
|
// against a concurrent SetDefault during `weed server` startup.
|
|
type ViperProxy struct {
|
|
v *viper.Viper
|
|
sync.Mutex
|
|
}
|
|
|
|
var (
|
|
vp = &ViperProxy{}
|
|
)
|
|
|
|
func (vp *ViperProxy) SetDefault(key string, value interface{}) {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
vp.v.SetDefault(key, value)
|
|
}
|
|
|
|
func (vp *ViperProxy) AutomaticEnv() {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
vp.v.AutomaticEnv()
|
|
}
|
|
|
|
// Get returns the value at key as viper holds it, without converting it, so
|
|
// a caller can tell a string from an array or a table.
|
|
func (vp *ViperProxy) Get(key string) interface{} {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return deepCopyValue(vp.v.Get(key))
|
|
}
|
|
|
|
func (vp *ViperProxy) GetString(key string) string {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.GetString(key)
|
|
}
|
|
|
|
func (vp *ViperProxy) GetBool(key string) bool {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.GetBool(key)
|
|
}
|
|
|
|
func (vp *ViperProxy) GetInt(key string) int {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.GetInt(key)
|
|
}
|
|
|
|
func (vp *ViperProxy) GetStringSlice(key string) []string {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
// a []string value comes back uncast — the same shared subtree issue
|
|
// GetStringMap has, so hand the caller a copy
|
|
return append([]string(nil), vp.v.GetStringSlice(key)...)
|
|
}
|
|
|
|
func (vp *ViperProxy) GetStringMap(key string) map[string]interface{} {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
// viper hands back its internal subtree, so a caller iterating it after
|
|
// the lock is released would race the next SetDefault — copy it out.
|
|
return deepCopyStringMap(vp.v.GetStringMap(key))
|
|
}
|
|
|
|
func deepCopyStringMap(m map[string]interface{}) map[string]interface{} {
|
|
out := make(map[string]interface{}, len(m))
|
|
for k, v := range m {
|
|
out[k] = deepCopyValue(v)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func deepCopyValue(v interface{}) interface{} {
|
|
switch nested := v.(type) {
|
|
case map[string]interface{}:
|
|
return deepCopyStringMap(nested)
|
|
case []interface{}:
|
|
out := make([]interface{}, len(nested))
|
|
for i, item := range nested {
|
|
out[i] = deepCopyValue(item)
|
|
}
|
|
return out
|
|
default:
|
|
return v
|
|
}
|
|
}
|
|
|
|
func (vp *ViperProxy) GetUint32(key string) uint32 {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.GetUint32(key)
|
|
}
|
|
|
|
func (vp *ViperProxy) GetFloat64(key string) float64 {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.GetFloat64(key)
|
|
}
|
|
|
|
func (vp *ViperProxy) GetDuration(key string) time.Duration {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.GetDuration(key)
|
|
}
|
|
|
|
func (vp *ViperProxy) Set(key string, value interface{}) {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
vp.v.Set(key, value)
|
|
}
|
|
|
|
func (vp *ViperProxy) IsSet(key string) bool {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.IsSet(key)
|
|
}
|
|
|
|
func (vp *ViperProxy) AllKeys() []string {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
return vp.v.AllKeys()
|
|
}
|
|
|
|
// NewViperProxy wraps a specific viper — for configuration loaded from a
|
|
// source other than the shared instance GetViper returns.
|
|
func NewViperProxy(v *viper.Viper) *ViperProxy {
|
|
return &ViperProxy{v: v}
|
|
}
|
|
|
|
func GetViper() *ViperProxy {
|
|
vp.Lock()
|
|
defer vp.Unlock()
|
|
|
|
if vp.v == nil {
|
|
vp.v = viper.GetViper()
|
|
setEnvOverrides(vp.v)
|
|
}
|
|
|
|
return vp
|
|
}
|