Files
seaweedfs/weed/server/filer_basic_auth_test.go
T
Chris LuandClaude Opus 5.5 22df63ad22 security: accept a previous JWT signing key during rotation (#12844)
* security: verify JWTs against an optional previous signing key

DecodeJwt, the admin token checks and the volume expiry classifier take
previous keys to try after the current one, and Guard keeps a previous
write and read key next to the current ones. Signing still uses only the
current key. Callers pass no previous key yet.

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

* volume, filer, s3, admin: accept tokens signed with jwt.*.previous_key

jwt.signing.previous_key, jwt.signing.read.previous_key,
jwt.filer_signing.previous_key and jwt.filer_signing.read.previous_key
(WEED_JWT_*_PREVIOUS_KEY from the environment) name a key the verifiers
still accept next to the current one, and SIGHUP reloads them. Keys can
then rotate without an error window: add the new key as previous
everywhere, swap current and previous, then remove previous.

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

* scaffold: document jwt previous_key for key rotation

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

* volume(rs): accept tokens signed with jwt.signing previous_key

Mirrors the Go volume server: [jwt.signing] and [jwt.signing.read] take
previous_key (WEED_JWT_SIGNING_PREVIOUS_KEY,
WEED_JWT_SIGNING_READ_PREVIOUS_KEY), the guard verifies against it after
the current key, and SIGHUP reloads it.

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

* volume, filer, s3: drop a removed previous_key on SIGHUP

LoadConfiguration merges, so a previous_key line deleted from
security.toml kept verifying until a restart. Read the previous keys
without the merge on reload, as the Rust volume server already does.

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

* volume, filer, s3: keep previous keys when a reload cannot read the file

A SIGHUP that found security.toml unreadable or malformed cleared the
previous keys while the merged current keys stayed. Fall back to the
merged configuration then, so the keys in effect stay in effect.

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

* filer: IAM and metadata subscription admin checks follow the filer guard

The IAM gRPC service checked the jwt.filer_signing keys read at startup,
and the metadata subscription read them from the merged configuration,
so adding or removing previous_key with SIGHUP did not reach them. Both
now read the filer guard that Reload updates.

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

* security: reload jwt keys in one place, keeping the guard's previous keys

When security.toml could not be read, the reloads fell back to the merged
configuration, which still holds a previous_key an earlier reload removed.
Guard.ReloadSigningKeys keeps the previous keys the guard already has
instead, and the volume, filer and S3 reloads share it.

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

* security: take reloaded current keys from the same read as previous keys

The current keys came from the merged configuration and the previous keys
from a second read of the file, so a file swapped between the two reads
could publish the same key as both. Take every key the fresh read sets
from it; a current key the file no longer sets keeps its merged value.

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

* admin: worker streams read the filer admin keys as security.toml sets them

Both worker stream handlers read jwt.filer_signing keys from the merged
configuration. Under weed mini a reload merges the file, which keeps a
previous_key the operator removed, so new streams still accepted it; a
standalone admin never picked up a rotation at all. Read the keys the file
sets now, falling back to the merged values.

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

* scaffold: wait for old-key tokens to expire before clearing previous_key

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

* volume(rs): keep the keys in effect when SIGHUP cannot read security.toml

parse_security_config falls back to defaults when the file is missing or
unreadable, so a SIGHUP then cleared every key and turned JWT checks off.
Skip the key and whitelist update in that case, as the Go reload keeps
its merged configuration and the guard's previous keys.

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

* security: keep every key in effect when a reload cannot read security.toml

A failed read took the current keys from the merged configuration while
keeping the active previous keys, so after a swapped pair the guard could
publish the old key twice and reject tokens signed with the new one. The
reload now leaves the keys untouched, as the Rust volume server does.

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

* security: filer admin keys fall back to the last pair read, not merged values

When security.toml stopped being readable, FilerAdminKeys returned the
merged configuration, which still holds a previous_key the file had
already dropped, so tokens signed with the retired key verified again.

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

* filer: STS store gates check the admin token against one key snapshot

The OIDC provider and role RPCs read the reloadable admin key twice, in
checkAdminAuth and in the store gate. A reload that set the key between
the two reads let a call without a token pass both. The gate now takes
one snapshot for the empty-key refusal and the token check.

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

* security: read and cache filer admin keys under one lock

Concurrent callers could store their reads out of order, so an older
pair that still had previous_key could overwrite a newer one and come
back when a later read of security.toml failed.

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

* security: unlock the filer admin key mutex on every exit of its test

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

---------

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

225 lines
7.5 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")
}
}