Files
seaweedfs/weed/security/guard.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

243 lines
8.0 KiB
Go

package security
import (
"errors"
"fmt"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
)
var (
ErrUnauthorized = errors.New("unauthorized token")
)
/*
Guard is to ensure data access security.
There are 2 ways to check access:
1. white list. It's checking request ip address.
2. JSON Web Token(JWT) generated from secretKey.
The jwt can come from:
1. url parameter jwt=...
2. request header "Authorization"
3. cookie with the name "jwt"
The white list is checked first because it is easy.
Then the JWT is checked.
The Guard will also check these claims if provided:
1. "exp" Expiration Time
2. "nbf" Not Before
Generating JWT:
1. use HS256 to sign
2. optionally set "exp", "nbf" fields, in Unix time,
the number of seconds elapsed since January 1, 1970 UTC.
Referenced:
https://github.com/pkieltyka/jwtauth/blob/master/jwtauth.go
*/
// guardState is the immutable snapshot of all hot-reloadable Guard state. The
// Update* methods build a new snapshot from the current one and swap it in
// atomically, so request-path readers (WhiteList, IsWhiteListed, the SigningKey
// accessors) always observe a consistent set of keys and whitelist — never a
// torn slice header or a mix of old and new state across a SIGHUP.
type guardState struct {
signingKey SigningKey
expiresAfterSec int
readSigningKey SigningKey
readExpiresAfterSec int
// previous keys are accepted when verifying, never used to sign
previousSigningKey SigningKey
previousReadSigningKey SigningKey
whiteListIp map[string]struct{}
whiteListCIDR map[string]*net.IPNet
isWriteActive bool
isEmptyWhiteList bool
}
type Guard struct {
// state is swapped atomically by the Update* methods. Read it via Load.
state atomic.Pointer[guardState]
// updateMu serializes the read-modify-write inside the Update* methods so
// concurrent reloads don't clobber each other; readers stay lock-free.
updateMu sync.Mutex
}
func NewGuard(whiteList []string, signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int, previousSigningKey string, previousReadSigningKey string) *Guard {
g := &Guard{}
g.state.Store(&guardState{
signingKey: SigningKey(signingKey),
expiresAfterSec: expiresAfterSec,
readSigningKey: SigningKey(readSigningKey),
readExpiresAfterSec: readExpiresAfterSec,
previousSigningKey: SigningKey(previousSigningKey),
previousReadSigningKey: SigningKey(previousReadSigningKey),
})
g.UpdateWhiteList(whiteList)
return g
}
func (g *Guard) SigningKey() SigningKey { return g.state.Load().signingKey }
func (g *Guard) ExpiresAfterSec() int { return g.state.Load().expiresAfterSec }
func (g *Guard) ReadSigningKey() SigningKey { return g.state.Load().readSigningKey }
func (g *Guard) ReadExpiresAfterSec() int { return g.state.Load().readExpiresAfterSec }
// VerificationKeys returns the write (or read) signing key and the previous
// key still accepted for it, from one snapshot.
func (g *Guard) VerificationKeys(isWrite bool) (signingKey, previousSigningKey SigningKey) {
st := g.state.Load()
if isWrite {
return st.signingKey, st.previousSigningKey
}
return st.readSigningKey, st.previousReadSigningKey
}
func (g *Guard) WhiteList(f http.HandlerFunc) http.HandlerFunc {
if !g.state.Load().isWriteActive {
//if no security needed, just skip all checking
return f
}
return func(w http.ResponseWriter, r *http.Request) {
if err := g.checkWhiteList(w, r); err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
f(w, r)
}
}
func GetActualRemoteHost(r *http.Request) string {
// For security reasons, only use RemoteAddr to determine the client's IP address.
// Do not trust headers like X-Forwarded-For, as they can be easily spoofed by clients.
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err == nil {
return host
}
// If SplitHostPort fails, it may be because of a missing port.
// We try to parse RemoteAddr as a raw host (IP or hostname).
host = strings.TrimSpace(r.RemoteAddr)
// It might be an IPv6 address without a port, but with brackets.
// e.g. "[::1]"
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = host[1 : len(host)-1]
}
// Return the host (can be IP or hostname, just like headers)
return host
}
func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
host := GetActualRemoteHost(r)
if g.IsWhiteListed(host) {
return nil
}
glog.V(0).Infof("Not in whitelist: %s (original RemoteAddr: %s)", host, r.RemoteAddr)
return fmt.Errorf("Not in whitelist: %s", host)
}
// IsWhiteListed returns true if the given host IP is allowed by the guard.
// When no whitelist is configured (security inactive), all hosts are allowed.
func (g *Guard) IsWhiteListed(host string) bool {
st := g.state.Load()
if !st.isWriteActive {
return true
}
if st.isEmptyWhiteList {
return true
}
if _, ok := st.whiteListIp[host]; ok {
return true
}
remote := net.ParseIP(host)
if remote != nil {
for _, cidrnet := range st.whiteListCIDR {
if cidrnet.Contains(remote) {
return true
}
}
}
return false
}
// UpdateSigningKeys refreshes the JWT signing keys and their expirations so
// operators can rotate keys (e.g. via SIGHUP) without restarting the process.
// It swaps in a new snapshot carrying the existing whitelist, so a concurrent
// reader sees either the old keys or the new ones, never a torn slice header.
func (g *Guard) UpdateSigningKeys(signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int, previousSigningKey string, previousReadSigningKey string) {
g.updateMu.Lock()
defer g.updateMu.Unlock()
next := *g.state.Load()
next.signingKey = SigningKey(signingKey)
next.expiresAfterSec = expiresAfterSec
next.readSigningKey = SigningKey(readSigningKey)
next.readExpiresAfterSec = readExpiresAfterSec
next.previousSigningKey = SigningKey(previousSigningKey)
next.previousReadSigningKey = SigningKey(previousReadSigningKey)
next.isWriteActive = !next.isEmptyWhiteList || len(next.signingKey) != 0
g.state.Store(&next)
}
// ReloadSigningKeys applies the [section] keys after util.LoadConfiguration
// merged security.toml again. The merge keeps a key the file no longer sets,
// so the keys are read from the file anew: a removed previous key stops
// verifying, and a swapped pair comes from one read. A file that cannot be
// read keeps the keys in effect.
func (g *Guard) ReloadSigningKeys(section string) {
fresh, used := util.ReadConfiguration("security", "")
if used == "" {
glog.Warningf("reload %s: security.toml cannot be read, keeping the keys in effect", section)
return
}
v := util.GetViper()
g.UpdateSigningKeys(
freshKey(fresh, section+".key"),
v.GetInt(section+".expires_after_seconds"),
freshKey(fresh, section+".read.key"),
v.GetInt(section+".read.expires_after_seconds"),
fresh.GetString(section+".previous_key"),
fresh.GetString(section+".read.previous_key"),
)
}
// freshKey returns name as the fresh read sets it, else its merged value, so
// removing a current key from the file does not turn verification off.
func freshKey(fresh *util.ViperProxy, name string) string {
if fresh.IsSet(name) {
return fresh.GetString(name)
}
return util.GetViper().GetString(name)
}
func (g *Guard) UpdateWhiteList(whiteList []string) {
whiteListIp := make(map[string]struct{})
whiteListCIDR := make(map[string]*net.IPNet)
for _, ip := range whiteList {
if strings.Contains(ip, "/") {
_, cidrnet, err := net.ParseCIDR(ip)
if err != nil {
glog.Errorf("Parse CIDR %s in whitelist failed: %v", ip, err)
continue
}
whiteListCIDR[ip] = cidrnet
} else {
whiteListIp[ip] = struct{}{}
}
}
g.updateMu.Lock()
defer g.updateMu.Unlock()
next := *g.state.Load()
next.isEmptyWhiteList = len(whiteListIp) == 0 && len(whiteListCIDR) == 0
next.isWriteActive = !next.isEmptyWhiteList || len(next.signingKey) != 0
next.whiteListIp = whiteListIp
next.whiteListCIDR = whiteListCIDR
g.state.Store(&next)
}