mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
* 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>
214 lines
9.1 KiB
Go
214 lines
9.1 KiB
Go
package weed_server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
"github.com/seaweedfs/seaweedfs/weed/filer"
|
|
"github.com/seaweedfs/seaweedfs/weed/security"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
)
|
|
|
|
const (
|
|
tusTestWriteKey = "write-secret"
|
|
tusTestReadKey = "read-secret"
|
|
tusTestUploadID = "9f6f0d4b-6556-48f6-b953-0d8fca1966f1"
|
|
)
|
|
|
|
// signFilerToken builds a signed filer JWT for tests.
|
|
func signFilerToken(t *testing.T, signingKey string, allowedPrefixes, allowedMethods []string) string {
|
|
t.Helper()
|
|
claims := security.SeaweedFilerClaims{
|
|
AllowedPrefixes: allowedPrefixes,
|
|
AllowedMethods: allowedMethods,
|
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(1 * time.Hour)),
|
|
},
|
|
}
|
|
str, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(signingKey))
|
|
if err != nil {
|
|
t.Fatalf("failed to sign token: %v", err)
|
|
}
|
|
return str
|
|
}
|
|
|
|
// newTusTestServer builds a FilerServer backed by an in-memory store seeded with
|
|
// TUS sessions (uploadID -> stored TargetPath), so the handler can resolve a
|
|
// session's target the way production does. The store is returned so a test can
|
|
// mutate or inspect the seeded session.
|
|
func newTusTestServer(t *testing.T, sessions map[string]string) (*FilerServer, *renameTestStore) {
|
|
t.Helper()
|
|
store := newRenameTestStore()
|
|
fs := &FilerServer{
|
|
filer: newRenameTestFiler(t, store),
|
|
filerGuard: security.NewGuard(nil, tusTestWriteKey, 0, tusTestReadKey, 0, "", ""),
|
|
option: &FilerOption{TusBasePath: "/.tus", TusMaxSize: TusDefaultMaxSize},
|
|
entryLockTable: util.NewLockTable[util.FullPath](),
|
|
}
|
|
for uploadID, targetPath := range sessions {
|
|
seedTusSession(t, fs, store, TusSession{ID: uploadID, TargetPath: targetPath, Size: 1})
|
|
}
|
|
return fs, store
|
|
}
|
|
|
|
// seedTusSession writes a session directory and its .info metadata into the store.
|
|
func seedTusSession(t *testing.T, fs *FilerServer, store *renameTestStore, session TusSession) {
|
|
t.Helper()
|
|
data, err := json.Marshal(&session)
|
|
if err != nil {
|
|
t.Fatalf("marshal session %s: %v", session.ID, err)
|
|
}
|
|
dir := &filer.Entry{FullPath: util.FullPath(fs.tusSessionPath(session.ID)), Attr: filer.Attr{Mode: os.ModeDir | 0755}}
|
|
info := &filer.Entry{FullPath: util.FullPath(fs.tusSessionInfoPath(session.ID)), Content: data}
|
|
for _, entry := range []*filer.Entry{dir, info} {
|
|
if err := store.InsertEntry(context.Background(), entry); err != nil {
|
|
t.Fatalf("seed session %s: %v", session.ID, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestFilerServer_checkJwtAuthorization(t *testing.T) {
|
|
fs := &FilerServer{
|
|
filerGuard: security.NewGuard(nil, tusTestWriteKey, 0, tusTestReadKey, 0, "", ""),
|
|
option: &FilerOption{TusBasePath: "/.tus"},
|
|
}
|
|
victim := []string{"/buckets/secret/victim.bin"}
|
|
uploadPath := "/.tus/.uploads/" + tusTestUploadID
|
|
|
|
tests := []struct {
|
|
name string
|
|
method string
|
|
path string
|
|
token string
|
|
scopedPaths []string
|
|
expectAuthorized bool
|
|
}{
|
|
// With a filer signing key configured, an unauthenticated request is denied.
|
|
{"post without token denied", http.MethodPost, "/.tus/buckets/secret/owned.txt", "", []string{"/buckets/secret/owned.txt"}, false},
|
|
{"patch without token denied", http.MethodPatch, uploadPath, "", victim, false},
|
|
{"head without token denied", http.MethodHead, uploadPath, "", victim, false},
|
|
|
|
// A valid token for the right access level is accepted.
|
|
{"post write token allowed", http.MethodPost, "/.tus/buckets/data/ok.txt", signFilerToken(t, tusTestWriteKey, nil, nil), []string{"/buckets/data/ok.txt"}, true},
|
|
{"head read token allowed", http.MethodHead, uploadPath, signFilerToken(t, tusTestReadKey, nil, nil), victim, true},
|
|
|
|
// HEAD is a read, so a write token must not authorize it, nor a read token a write.
|
|
{"head write token denied", http.MethodHead, uploadPath, signFilerToken(t, tusTestWriteKey, nil, nil), victim, false},
|
|
{"post read token denied", http.MethodPost, "/.tus/buckets/data/ok.txt", signFilerToken(t, tusTestReadKey, nil, nil), []string{"/buckets/data/ok.txt"}, false},
|
|
|
|
// Prefix-restricted tokens are scoped against the resolved target path.
|
|
{"within allowed prefix", http.MethodPost, "/.tus/buckets/allowed/ok.txt", signFilerToken(t, tusTestWriteKey, []string{"/buckets/allowed"}, nil), []string{"/buckets/allowed/ok.txt"}, true},
|
|
{"outside allowed prefix denied", http.MethodPost, "/.tus/buckets/secret/owned.txt", signFilerToken(t, tusTestWriteKey, []string{"/buckets/allowed"}, nil), []string{"/buckets/secret/owned.txt"}, false},
|
|
|
|
// Fail closed: a prefix-restricted token with no resolved resource is denied.
|
|
{"restricted token without resource denied", http.MethodPatch, uploadPath, signFilerToken(t, tusTestWriteKey, []string{"/buckets/allowed"}, nil), nil, false},
|
|
|
|
// Method-restricted tokens are checked against the actual HTTP method.
|
|
{"matching method allowed", http.MethodPatch, uploadPath, signFilerToken(t, tusTestWriteKey, nil, []string{"POST", "PATCH", "DELETE"}), victim, true},
|
|
{"method not allowed denied", http.MethodPatch, uploadPath, signFilerToken(t, tusTestWriteKey, nil, []string{"POST"}), victim, false},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
req := httptest.NewRequest(tt.method, tt.path, nil)
|
|
if tt.token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+tt.token)
|
|
}
|
|
if got := fs.checkJwtAuthorization(req, tt.method != http.MethodHead, tt.scopedPaths); got != tt.expectAuthorized {
|
|
t.Errorf("checkJwtAuthorization(%s %s) = %v, want %v", tt.method, tt.path, got, tt.expectAuthorized)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestFilerServer_tusHandler_UnauthenticatedRejected exercises the full handler
|
|
// entry point: OPTIONS discovery stays open, but an unauthenticated request is
|
|
// rejected with 401 before any session is created or looked up.
|
|
func TestFilerServer_tusHandler_UnauthenticatedRejected(t *testing.T) {
|
|
fs, _ := newTusTestServer(t, map[string]string{tusTestUploadID: "/buckets/secret/victim.bin"})
|
|
|
|
// OPTIONS is capability discovery and must not require a token.
|
|
optionsReq := httptest.NewRequest(http.MethodOptions, "/.tus/buckets/secret/owned.txt", nil)
|
|
optionsRec := httptest.NewRecorder()
|
|
fs.tusHandler(optionsRec, optionsReq)
|
|
if optionsRec.Code != http.StatusOK {
|
|
t.Errorf("OPTIONS without token = %d, want %d", optionsRec.Code, http.StatusOK)
|
|
}
|
|
|
|
// POST without a token must be rejected before touching the filer store.
|
|
postReq := httptest.NewRequest(http.MethodPost, "/.tus/buckets/secret/owned.txt", nil)
|
|
postReq.Header.Set("Tus-Resumable", TusVersion)
|
|
postReq.Header.Set("Upload-Length", "5")
|
|
postRec := httptest.NewRecorder()
|
|
fs.tusHandler(postRec, postReq)
|
|
if postRec.Code != http.StatusUnauthorized {
|
|
t.Errorf("unauthenticated POST = %d, want %d", postRec.Code, http.StatusUnauthorized)
|
|
}
|
|
|
|
// A missing credential is rejected before the upload id triggers a metadata
|
|
// lookup, so an existing session is not an unauthenticated resource oracle.
|
|
headReq := httptest.NewRequest(http.MethodHead, "/.tus/.uploads/"+tusTestUploadID, nil)
|
|
headReq.Header.Set("Tus-Resumable", TusVersion)
|
|
headRec := httptest.NewRecorder()
|
|
fs.tusHandler(headRec, headReq)
|
|
if headRec.Code != http.StatusUnauthorized {
|
|
t.Errorf("unauthenticated HEAD = %d, want %d", headRec.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
// TestFilerServer_refreshTusSessionChunks_RevalidatesPinnedSession verifies a
|
|
// pinned session cannot complete after it is deleted or its target is replaced
|
|
// between authorization and completion.
|
|
func TestFilerServer_refreshTusSessionChunks_RevalidatesPinnedSession(t *testing.T) {
|
|
pin := func(t *testing.T) (*FilerServer, *renameTestStore, *TusSession) {
|
|
t.Helper()
|
|
fs, store := newTusTestServer(t, nil)
|
|
seedTusSession(t, fs, store, TusSession{
|
|
ID: tusTestUploadID,
|
|
TargetPath: "/buckets/secret/victim.bin",
|
|
Size: 1,
|
|
CreatedAt: time.Unix(1700000000, 123),
|
|
})
|
|
session, err := fs.readTusSessionInfo(context.Background(), tusTestUploadID)
|
|
if err != nil {
|
|
t.Fatalf("pin session: %v", err)
|
|
}
|
|
return fs, store, session
|
|
}
|
|
|
|
t.Run("deleted before completion", func(t *testing.T) {
|
|
fs, store, session := pin(t)
|
|
if err := store.DeleteEntry(context.Background(), util.FullPath(fs.tusSessionInfoPath(tusTestUploadID))); err != nil {
|
|
t.Fatalf("delete session info: %v", err)
|
|
}
|
|
if err := fs.refreshTusSessionChunks(context.Background(), session); err == nil {
|
|
t.Fatal("refresh succeeded after the session was deleted")
|
|
}
|
|
})
|
|
|
|
t.Run("replaced before completion", func(t *testing.T) {
|
|
fs, store, session := pin(t)
|
|
replaced := *session
|
|
replaced.TargetPath = "/buckets/other/replacement.bin"
|
|
data, err := json.Marshal(&replaced)
|
|
if err != nil {
|
|
t.Fatalf("marshal replacement: %v", err)
|
|
}
|
|
if err := store.InsertEntry(context.Background(), &filer.Entry{
|
|
FullPath: util.FullPath(fs.tusSessionInfoPath(tusTestUploadID)),
|
|
Content: data,
|
|
}); err != nil {
|
|
t.Fatalf("replace session info: %v", err)
|
|
}
|
|
if err := fs.refreshTusSessionChunks(context.Background(), session); err == nil {
|
|
t.Fatal("refresh succeeded after the session target was replaced")
|
|
}
|
|
})
|
|
}
|