diff --git a/weed/command/scaffold/security.toml b/weed/command/scaffold/security.toml index eda89c30a0..a539431f53 100644 --- a/weed/command/scaffold/security.toml +++ b/weed/command/scaffold/security.toml @@ -41,6 +41,20 @@ ui = false [filer.expose_directory_metadata] enabled = true +# HTTP Basic Auth on the filer HTTP ports (-port and -port.readonly). Once the +# password is set, every request needs these credentials or a valid filer JWT +# (see [jwt.filer_signing]), and an access level without a JWT key is no longer +# open. /healthz and /readyz stay open. A browser request from another website +# (an Origin other than the filer's own host) can use these credentials only if +# its origin is listed in cors.allowed_origins. Components that call the filer HTTP +# port (mount, filer.sync and filer.backup with -filerProxy, sftp, volume.fsck) +# authenticate with the filer JWT, so set jwt.filer_signing.key, and +# jwt.filer_signing.read.key for their reads, if you run them. +# Env: WEED_FILER_BASIC_AUTH_USER, WEED_FILER_BASIC_AUTH_PASSWORD +[filer.basic_auth] +user = "" +password = "" + # this jwt signing key is read by master and volume server, and it is used for read operations: # - the Master server generates the JWT, which can be used to read a certain file on a volume server # - the Volume server validates the JWT on reading diff --git a/weed/security/basic_auth.go b/weed/security/basic_auth.go new file mode 100644 index 0000000000..358ddfbcb4 --- /dev/null +++ b/weed/security/basic_auth.go @@ -0,0 +1,46 @@ +package security + +import ( + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "net/http" +) + +// BasicAuth checks HTTP Basic credentials against one configured user and +// password. Values are compared as MACs under a random per-process key, so +// the check takes the same time whatever the lengths of the configured and +// supplied values, and no plain digest of the password is kept. +type BasicAuth struct { + key []byte + user []byte + password []byte +} + +// NewBasicAuth returns nil, meaning Basic Auth is off, when password is empty. +func NewBasicAuth(user, password string) *BasicAuth { + if password == "" { + return nil + } + a := &BasicAuth{key: make([]byte, sha256.Size)} + rand.Read(a.key) + a.user = a.mac(user) + a.password = a.mac(password) + return a +} + +// Allows reports whether r carries the configured credentials. +func (a *BasicAuth) Allows(r *http.Request) bool { + user, password, ok := r.BasicAuth() + if !ok { + return false + } + return subtle.ConstantTimeCompare(a.mac(user), a.user)&subtle.ConstantTimeCompare(a.mac(password), a.password) == 1 +} + +func (a *BasicAuth) mac(s string) []byte { + h := hmac.New(sha256.New, a.key) + h.Write([]byte(s)) + return h.Sum(nil) +} diff --git a/weed/server/filer_basic_auth_test.go b/weed/server/filer_basic_auth_test.go new file mode 100644 index 0000000000..5434f6b12f --- /dev/null +++ b/weed/server/filer_basic_auth_test.go @@ -0,0 +1,224 @@ +package weed_server + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +func TestFilerBasicAuth(t *testing.T) { + signingKey := "secret" + token := func() string { + claims := security.SeaweedFilerClaims{ + RegisteredClaims: jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour))}, + } + s, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(signingKey)) + if err != nil { + t.Fatal(err) + } + return s + }() + + type creds struct { + user, password string + bearer string + } + request := func(method string, c *creds) *http.Request { + r := httptest.NewRequest(method, "/dir/file", nil) + if c == nil { + return r + } + if c.bearer != "" { + r.Header.Set("Authorization", "Bearer "+c.bearer) + } else { + r.SetBasicAuth(c.user, c.password) + } + return r + } + + tests := []struct { + name string + password string + jwtKey string + creds *creds + wantRead bool + wantWrite bool + }{ + {name: "off, no keys, anonymous", wantRead: true, wantWrite: true}, + {name: "on, no keys, anonymous", password: "pw"}, + {name: "on, no keys, valid", password: "pw", creds: &creds{user: "admin", password: "pw"}, wantRead: true, wantWrite: true}, + {name: "on, no keys, wrong password", password: "pw", creds: &creds{user: "admin", password: "pwx"}}, + {name: "on, no keys, wrong user", password: "pw", creds: &creds{user: "root", password: "pw"}}, + {name: "on, no keys, bearer ignored", password: "pw", creds: &creds{bearer: token}}, + {name: "on, keys, valid basic", password: "pw", jwtKey: signingKey, creds: &creds{user: "admin", password: "pw"}, wantRead: true, wantWrite: true}, + {name: "on, keys, valid jwt", password: "pw", jwtKey: signingKey, creds: &creds{bearer: token}, wantRead: true, wantWrite: true}, + {name: "on, keys, anonymous", password: "pw", jwtKey: signingKey}, + {name: "off, keys, basic is not a jwt", jwtKey: signingKey, creds: &creds{user: "admin", password: "pw"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fs := &FilerServer{filerGuard: security.NewGuard(nil, tt.jwtKey, 0, tt.jwtKey, 0)} + fs.basicAuth.Store(security.NewBasicAuth("admin", tt.password)) + if got := fs.maybeCheckJwtAuthorization(request(http.MethodGet, tt.creds), false); got != tt.wantRead { + t.Errorf("read: got %v, want %v", got, tt.wantRead) + } + if got := fs.maybeCheckJwtAuthorization(request(http.MethodPut, tt.creds), true); got != tt.wantWrite { + t.Errorf("write: got %v, want %v", got, tt.wantWrite) + } + }) + } +} + +func TestFilerBasicAuthOrigin(t *testing.T) { + fs := &FilerServer{ + filerGuard: security.NewGuard(nil, "", 0, "", 0), + option: &FilerOption{AllowedOrigins: []string{"https://ui.example.com"}}, + } + fs.basicAuth.Store(security.NewBasicAuth("admin", "pw")) + tests := []struct { + origin string + want bool + }{ + {origin: "", want: true}, + {origin: "http://filer:8888", want: true}, + {origin: "http://FILER:8888", want: true}, + {origin: "https://ui.example.com", want: true}, + {origin: "https://evil.example.com"}, + {origin: "http://filer:9999"}, + {origin: "null"}, + } + for _, tt := range tests { + r := httptest.NewRequest(http.MethodPost, "http://filer:8888/new?mv.from=/old", nil) + r.SetBasicAuth("admin", "pw") + if tt.origin != "" { + r.Header.Set("Origin", tt.origin) + } + if got := fs.maybeCheckJwtAuthorization(r, true); got != tt.want { + t.Errorf("origin %q: got %v, want %v", tt.origin, got, tt.want) + } + } + + fs.option.AllowedOrigins = []string{"*"} + r := httptest.NewRequest(http.MethodPost, "http://filer:8888/new", nil) + r.SetBasicAuth("admin", "pw") + r.Header.Set("Origin", "https://evil.example.com") + if fs.maybeCheckJwtAuthorization(r, true) { + t.Error("the default allowed origin \"*\" let another website use Basic credentials") + } +} + +func TestFilerBasicAuthChallenge(t *testing.T) { + fs := &FilerServer{filerGuard: security.NewGuard(nil, "", 0, "", 0)} + fs.basicAuth.Store(security.NewBasicAuth("admin", "pw")) + w := httptest.NewRecorder() + fs.readonlyFilerHandler(w, httptest.NewRequest(http.MethodGet, "/dir/", nil)) + if w.Code != http.StatusUnauthorized { + t.Fatalf("status %d, want %d", w.Code, http.StatusUnauthorized) + } + if got := w.Header().Get("WWW-Authenticate"); got == "" { + t.Error("missing WWW-Authenticate challenge") + } + + fs.basicAuth.Store(security.NewBasicAuth("", "")) + w = httptest.NewRecorder() + fs.writeUnauthorized(w, httptest.NewRequest(http.MethodGet, "/", nil)) + if got := w.Header().Get("WWW-Authenticate"); got != "" { + t.Errorf("challenge %q with Basic Auth off", got) + } +} + +func TestFilerBasicAuthReloadDropsRemovedPassword(t *testing.T) { + dir := t.TempDir() + saved := util.ConfigurationFileDirectory + util.ConfigurationFileDirectory = util.DirectoryValueType(dir) + t.Cleanup(func() { util.ConfigurationFileDirectory = saved }) + write := func(content string) { + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + + fs := &FilerServer{ + filerGuard: security.NewGuard(nil, "", 0, "", 0), + volumeGuard: security.NewGuard(nil, "", 0, "", 0), + } + write("[filer.basic_auth]\nuser = \"admin\"\npassword = \"pw\"\n") + fs.Reload() + if fs.basicAuth.Load() == nil { + t.Fatal("Basic Auth off after reloading a file that sets it") + } + + write("[filer.basic_auth]\nuser = \"admin\"\npassword = \"pw2\"\n") + fs.Reload() + r := httptest.NewRequest(http.MethodGet, "/", nil) + r.SetBasicAuth("admin", "pw2") + if !fs.basicAuth.Load().Allows(r) { + t.Fatal("changed password not applied") + } + + write("# Basic Auth removed\n") + fs.Reload() + if fs.basicAuth.Load() != nil { + t.Error("Basic Auth still on after its section was removed") + } + + write("[filer.basic_auth\n") + fs.basicAuth.Store(security.NewBasicAuth("admin", "pw")) + fs.Reload() + if fs.basicAuth.Load() == nil { + t.Error("an unparsable file turned Basic Auth off") + } + if err := os.Remove(filepath.Join(dir, "security.toml")); err != nil { + t.Fatal(err) + } + fs.Reload() + if fs.basicAuth.Load() == nil { + t.Error("a missing file turned Basic Auth off") + } + + write("[filer.basic_auth\n") + t.Setenv("WEED_FILER_BASIC_AUTH_PASSWORD", "env") + if auth, _ := loadBasicAuth(nil, ""); auth == nil { + t.Error("an unparsable file dropped the environment password at startup") + } +} + +func TestFilerBasicAuthReloadStaysOnItsFile(t *testing.T) { + primary, fallback := t.TempDir(), t.TempDir() + saved := util.ConfigurationFileDirectory + util.ConfigurationFileDirectory = util.DirectoryValueType(primary) + t.Cleanup(func() { util.ConfigurationFileDirectory = saved }) + t.Chdir(fallback) + for dir, content := range map[string]string{ + primary: "[filer.basic_auth]\nuser = \"admin\"\npassword = \"pw\"\n", + fallback: "# no Basic Auth\n", + } { + if err := os.WriteFile(filepath.Join(dir, "security.toml"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + + fs := &FilerServer{ + filerGuard: security.NewGuard(nil, "", 0, "", 0), + volumeGuard: security.NewGuard(nil, "", 0, "", 0), + } + fs.Reload() + if fs.basicAuth.Load() == nil { + t.Fatal("Basic Auth off after reloading a file that sets it") + } + + // The search no longer reaches the primary directory, as when it turns + // unsearchable, so a fresh search would find the fallback file. + util.ConfigurationFileDirectory = util.DirectoryValueType(t.TempDir()) + fs.Reload() + if fs.basicAuth.Load() == nil { + t.Error("reload switched to a lower-priority security.toml without Basic Auth") + } +} diff --git a/weed/server/filer_server.go b/weed/server/filer_server.go index f30cab70f7..12082fef91 100644 --- a/weed/server/filer_server.go +++ b/weed/server/filer_server.go @@ -131,6 +131,8 @@ type FilerServer struct { option *FilerOption filer *filer.Filer filerGuard *security.Guard + basicAuth atomic.Pointer[security.BasicAuth] + basicAuthFile string volumeGuard *security.Guard grpcDialOption grpc.DialOption grpcDialOptionMaster grpc.DialOption @@ -326,6 +328,9 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption) glog.Warningf("filer: guard.white_list is configured but the IP whitelist feature is currently disabled. See https://github.com/seaweedfs/seaweedfs/issues/7094") } fs.filerGuard = security.NewGuard([]string{}, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec) + basicAuth, basicAuthFile := loadBasicAuth(nil, "") + fs.basicAuth.Store(basicAuth) + fs.basicAuthFile = basicAuthFile fs.volumeGuard = security.NewGuard([]string{}, volumeSigningKey, volumeExpiresAfterSec, volumeReadSigningKey, volumeReadExpiresAfterSec) fs.checkWithMaster() @@ -756,17 +761,42 @@ func (fs *FilerServer) leaveLockRing(removalTimeout time.Duration) { time.Sleep(time.Until(until)) } +// loadBasicAuth reads [filer.basic_auth] from security.toml and the WEED_ +// environment alone: the shared viper merges every reload into what it held, +// so it would keep a password the file no longer sets. Once a file is read, +// later reads stay on it rather than search again, so a directory that turns +// unsearchable cannot hand over a lower-priority security.toml. A non-nil +// current is kept when the file cannot be read. +func loadBasicAuth(current *security.BasicAuth, file string) (*security.BasicAuth, string) { + v, used := util.ReadConfiguration("security", file) + if used == "" { + if current != nil { + return current, file + } + used = file + } + return security.NewBasicAuth(v.GetString("filer.basic_auth.user"), v.GetString("filer.basic_auth.password")), used +} + func (fs *FilerServer) Reload() { glog.V(0).Infoln("Reload filer server...") util.LoadConfiguration("security", false) v := util.GetViper() + // Turn the new credential on before the old one goes off, so a switch + // between Basic Auth and JWT never leaves a window with neither. + basicAuth, basicAuthFile := loadBasicAuth(fs.basicAuth.Load(), fs.basicAuthFile) + fs.basicAuthFile = basicAuthFile + if basicAuth != nil { + fs.basicAuth.Store(basicAuth) + } fs.filerGuard.UpdateSigningKeys( v.GetString("jwt.filer_signing.key"), v.GetInt("jwt.filer_signing.expires_after_seconds"), v.GetString("jwt.filer_signing.read.key"), v.GetInt("jwt.filer_signing.read.expires_after_seconds"), ) + fs.basicAuth.Store(basicAuth) fs.volumeGuard.UpdateSigningKeys( v.GetString("jwt.signing.key"), v.GetInt("jwt.signing.expires_after_seconds"), diff --git a/weed/server/filer_server_handlers.go b/weed/server/filer_server_handlers.go index bedf8c6595..c76833f978 100644 --- a/weed/server/filer_server_handlers.go +++ b/weed/server/filer_server_handlers.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/http" + "net/url" "path" "slices" "strconv" @@ -68,7 +69,7 @@ func (fs *FilerServer) filerHandler(w http.ResponseWriter, r *http.Request) { isReadHttpCall := r.Method == http.MethodGet || r.Method == http.MethodHead if !fs.maybeCheckJwtAuthorization(r, !isReadHttpCall) { - writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) + fs.writeUnauthorized(w, r) return } @@ -214,7 +215,7 @@ func (fs *FilerServer) readonlyFilerHandler(w http.ResponseWriter, r *http.Reque } if !fs.maybeCheckJwtAuthorization(r, false) { - writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) + fs.writeUnauthorized(w, r) return } @@ -257,10 +258,16 @@ func (fs *FilerServer) checkJwtAuthorization(r *http.Request, isWrite bool, scop } // authenticateFilerJwt verifies the JWT signature and method claims. A nil claims -// with ok true means authentication is disabled for this access level. Splitting +// with ok true means authentication is disabled for this access level, or the +// request passed Basic Auth, which grants every access level. With Basic Auth +// on, an access level without a signing key is no longer open. Splitting // authentication from path authorization lets a handler load an indirect resource // (the TUS session target) only after the caller's credential is verified. func (fs *FilerServer) authenticateFilerJwt(r *http.Request, isWrite bool) (*security.SeaweedFilerClaims, bool) { + basicAuth := fs.basicAuth.Load() + if basicAuth != nil && basicAuth.Allows(r) && fs.basicAuthOriginAllowed(r) { + return nil, true + } var signingKey security.SigningKey if isWrite { @@ -269,7 +276,10 @@ func (fs *FilerServer) authenticateFilerJwt(r *http.Request, isWrite bool) (*sec signingKey = fs.filerGuard.ReadSigningKey() } if len(signingKey) == 0 { - return nil, true + // Reload turns the new credential on before the old one off, so + // loading Basic Auth on both sides of the key read never sees both off + // while a switch is in flight. + return nil, basicAuth == nil && fs.basicAuth.Load() == nil } tokenStr := security.GetJwt(r) @@ -315,6 +325,37 @@ func (fs *FilerServer) authenticateFilerJwt(r *http.Request, isWrite bool) (*sec return claims, true } +// basicAuthOriginAllowed keeps other websites from riding on Basic credentials +// a browser cached for the filer: a request with an Origin header must come +// from the filer's own host or an origin listed in cors.allowed_origins. +func (fs *FilerServer) basicAuthOriginAllowed(r *http.Request) bool { + origin := r.Header.Get("Origin") + if origin == "" { + return true + } + if u, err := url.Parse(origin); err == nil && u.Host != "" && strings.EqualFold(u.Host, r.Host) { + return true + } + if fs.option != nil { + for _, allowed := range fs.option.AllowedOrigins { + if allowed != "*" && origin == allowed { + return true + } + } + } + glog.V(1).Infof("basic auth refused for origin %q from %s", origin, r.RemoteAddr) + return false +} + +// writeUnauthorized answers a request that failed authentication. With Basic +// Auth on, the challenge makes browsers prompt for the credentials. +func (fs *FilerServer) writeUnauthorized(w http.ResponseWriter, r *http.Request) { + if fs.basicAuth.Load() != nil { + w.Header().Set("WWW-Authenticate", `Basic realm="SeaweedFS Filer", charset="UTF-8"`) + } + writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) +} + // authorizeFilerJwtPaths checks the resource scope after authentication. A // prefix-restricted token must name at least one resource path; an empty list // fails closed, so a caller that cannot resolve its target never falls open. diff --git a/weed/server/filer_server_tus_handlers.go b/weed/server/filer_server_tus_handlers.go index a203f6ff3e..275364e37e 100644 --- a/weed/server/filer_server_tus_handlers.go +++ b/weed/server/filer_server_tus_handlers.go @@ -41,7 +41,7 @@ func (fs *FilerServer) tusHandler(w http.ResponseWriter, r *http.Request) { var authenticated bool if claims, authenticated = fs.authenticateFilerJwt(r, r.Method != http.MethodHead); !authenticated { - writeJsonError(w, r, http.StatusUnauthorized, errors.New("wrong jwt")) + fs.writeUnauthorized(w, r) return } } diff --git a/weed/util/config.go b/weed/util/config.go index 533d7134f3..203190f1e2 100644 --- a/weed/util/config.go +++ b/weed/util/config.go @@ -45,14 +45,7 @@ func LoadConfiguration(configFileName string, required bool) (loaded bool) { vp.Lock() defer vp.Unlock() - // find a filer store - viper.SetConfigName(configFileName) // name of config file (without extension) - viper.AddConfigPath(ResolvePath(ConfigurationFileDirectory.String())) // path to look for the config file in - viper.AddConfigPath(".") // optionally look for config in the working directory - viper.AddConfigPath("$HOME/.seaweedfs") // call multiple times to add many search paths - viper.AddConfigPath("/usr/local/etc/seaweedfs/") // search path for bsd-style config directory in - viper.AddConfigPath("/etc/seaweedfs/") // path to look for the config file in - + 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) @@ -77,6 +70,41 @@ func LoadConfiguration(configFileName string, required bool) (loaded bool) { 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. +func ReadConfiguration(configFileName, configFile string) (v *ViperProxy, used string) { + fresh := viper.New() + setEnvOverrides(fresh) + if configFile != "" { + fresh.SetConfigFile(configFile) + } else { + setConfigurationPaths(fresh, configFileName) + } + if err := fresh.ReadInConfig(); err != nil { + glog.V(1).Infof("Reading %s: %v", configFileName, err) + return NewViperProxy(fresh), "" + } + return NewViperProxy(fresh), fresh.ConfigFileUsed() +} + +func setConfigurationPaths(v *viper.Viper, configFileName string) { + v.SetConfigName(configFileName) + v.AddConfigPath(ResolvePath(ConfigurationFileDirectory.String())) + v.AddConfigPath(".") + v.AddConfigPath("$HOME/.seaweedfs") + v.AddConfigPath("/usr/local/etc/seaweedfs/") + v.AddConfigPath("/etc/seaweedfs/") +} + +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 @@ -207,9 +235,7 @@ func GetViper() *ViperProxy { if vp.v == nil { vp.v = viper.GetViper() - vp.v.AutomaticEnv() - vp.v.SetEnvPrefix("weed") - vp.v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) + setEnvOverrides(vp.v) } return vp diff --git a/weed/util/config_test.go b/weed/util/config_test.go index 86a0cd4d07..ae34e58125 100644 --- a/weed/util/config_test.go +++ b/weed/util/config_test.go @@ -2,6 +2,8 @@ package util import ( "fmt" + "os" + "path/filepath" "sync" "testing" @@ -51,3 +53,56 @@ func TestNewViperProxyWrapsGivenViper(t *testing.T) { assert.Equal(t, "z", p.GetString("x.y")) assert.Equal(t, map[string]interface{}{"y": "z"}, p.GetStringMap("x")) } + +func TestReadConfigurationDropsKeysTheFileNoLongerSets(t *testing.T) { + dir := t.TempDir() + saved := ConfigurationFileDirectory + ConfigurationFileDirectory = DirectoryValueType(dir) + t.Cleanup(func() { ConfigurationFileDirectory = saved }) + t.Setenv("WEED_READCONF_ENV", "from-env") + write := func(content string) { + if err := os.WriteFile(filepath.Join(dir, "readconf_test.toml"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + + v, used := ReadConfiguration("readconf_test", "") + assert.Empty(t, used, "missing file") + assert.Equal(t, "from-env", v.GetString("readconf.env")) + + write("[readconf]\nkey = \"v1\"\n") + v, used = ReadConfiguration("readconf_test", "") + assert.Equal(t, filepath.Join(dir, "readconf_test.toml"), used) + assert.Equal(t, "v1", v.GetString("readconf.key")) + + write("[readconf]\n") + v, used = ReadConfiguration("readconf_test", "") + assert.NotEmpty(t, used) + assert.Empty(t, v.GetString("readconf.key")) + assert.Equal(t, "from-env", v.GetString("readconf.env")) + + write("[readconf\n") + v, used = ReadConfiguration("readconf_test", "") + assert.Empty(t, used, "unparsable file") + assert.Equal(t, "from-env", v.GetString("readconf.env")) +} + +func TestReadConfigurationReadsTheGivenFile(t *testing.T) { + searched, given := t.TempDir(), filepath.Join(t.TempDir(), "readconf_test.toml") + saved := ConfigurationFileDirectory + ConfigurationFileDirectory = DirectoryValueType(searched) + t.Cleanup(func() { ConfigurationFileDirectory = saved }) + if err := os.WriteFile(filepath.Join(searched, "readconf_test.toml"), []byte("[readconf]\nkey = \"searched\"\n"), 0o600); err != nil { + t.Fatal(err) + } + + _, used := ReadConfiguration("readconf_test", given) + assert.Empty(t, used, "missing given file must not fall back to a search") + + if err := os.WriteFile(given, []byte("[readconf]\nkey = \"given\"\n"), 0o600); err != nil { + t.Fatal(err) + } + v, used := ReadConfiguration("readconf_test", given) + assert.Equal(t, given, used) + assert.Equal(t, "given", v.GetString("readconf.key")) +}