Files
seaweedfs/weed/server/filer_basic_auth_test.go
T
Chris LuandClaude Opus 5.5 f7323f2b63 filer: optional HTTP Basic Auth on the filer HTTP ports (#12778)
* security: add a constant-time HTTP Basic Auth check

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

* filer: require HTTP Basic Auth on the HTTP ports when configured

With filer.basic_auth.password set in security.toml (or
WEED_FILER_BASIC_AUTH_PASSWORD), a request on the filer HTTP ports, TUS
included, must carry those credentials or a valid filer JWT, and an
access level with no JWT signing key is no longer open. Valid Basic
credentials grant read and write. 401 responses then carry a Basic
challenge so browsers prompt. The credentials reload on SIGHUP with the
signing keys.

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

* scaffold: document filer.basic_auth in security.toml

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

* filer: enable reloaded Basic Auth before swapping the JWT keys

Reload cleared the old signing keys before storing the new Basic
credentials, so a switch from JWT to Basic Auth briefly left both off
and admitted anonymous requests. Store new credentials first and clear
old ones last.

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

* filer: refuse Basic credentials on cross-origin browser requests

Browsers resend cached Basic credentials on requests other websites
trigger, such as a form POST with mv.from, and the default
cors.allowed_origins "*" lets them through. Accept Basic credentials
only on requests without an Origin, from the filer's own host, or from
an origin explicitly listed in cors.allowed_origins. A JWT is still
accepted from any origin.

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

* filer: recheck Basic Auth after reading an empty signing key

A request that loaded Basic Auth as off, then read the signing key after
a JWT-to-Basic Reload had cleared it, was let through anonymously. Open
access now also needs Basic Auth to be off after the key read; with
Reload enabling the new credential before disabling the old one, the
two loads cannot both miss a credential that was on throughout.

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

* security: compare Basic Auth credentials as MACs under a per-process key

A plain SHA-256 of the password is what password-hash scanners flag;
keying the digests with a random per-process HMAC key keeps the
length-independent constant-time compare without holding one.

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

* util: read a configuration file without merging into the shared viper

LoadConfiguration merges each read into the shared viper, so a key
removed from the file keeps its old value after a reload.
ReadConfiguration reads the file into a fresh viper with the same search
path and WEED_ environment overrides.

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

* filer: turn Basic Auth off when security.toml no longer sets it

The shared viper merges each SIGHUP reload into what it held, so
removing [filer.basic_auth] kept the old password valid. Read the
credentials from security.toml alone at startup and on reload; an
unreadable file keeps the current setting.

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

* filer: keep Basic Auth when security.toml cannot be read

A malformed file at startup dropped a WEED_FILER_BASIC_AUTH_PASSWORD
from the environment, and viper reports an unsearchable config
directory as a missing file, which turned Basic Auth off on reload.
ReadConfiguration now always returns the environment overrides and
reports whether the file was read; a reload that could not read it
keeps the current credentials.

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

* filer: keep reloading Basic Auth from the security.toml first read

A search directory that turned unsearchable made viper fall through to a
lower-priority security.toml, and a reload from a file without
[filer.basic_auth] turned Basic Auth off. ReadConfiguration now takes the
file to read, and the filer reads the file it first found on every reload.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:19:46 -08:00

225 lines
7.4 KiB
Go

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")
}
}