mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 10:07:28 +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>
234 lines
8.2 KiB
Go
234 lines
8.2 KiB
Go
package security
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
jwt "github.com/golang-jwt/jwt/v5"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/util"
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
type EncodedJwt string
|
|
type SigningKey []byte
|
|
|
|
// BearerPrefix is the RFC 6750 Authorization header scheme prefix for bearer
|
|
// tokens. Used when constructing "Authorization: Bearer <token>" headers; the
|
|
// scheme name itself is matched case-insensitively when parsing (see GetJwt).
|
|
const BearerPrefix = "Bearer "
|
|
|
|
// SeaweedFileIdClaims is created by Master server(s) and consumed by Volume server(s),
|
|
// restricting the access this JWT allows to only a single file.
|
|
type SeaweedFileIdClaims struct {
|
|
Fid string `json:"fid"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
// SeaweedFilerClaims is created e.g. by S3 proxy server and consumed by Filer server.
|
|
// Right now, it only contains the standard claims; but this might be extended later
|
|
// for more fine-grained permissions.
|
|
type SeaweedFilerClaims struct {
|
|
AllowedPrefixes []string `json:"allowed_prefixes,omitempty"`
|
|
AllowedMethods []string `json:"allowed_methods,omitempty"`
|
|
// SessionId is present only on STS session tokens; a token carrying it is
|
|
// an S3 session credential, not a filer API credential.
|
|
SessionId string `json:"sid,omitempty"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
// SeaweedFilerAdminClaims is presented by callers of the filer's IAM gRPC
|
|
// service to prove they are authorised to administer users, access keys, and
|
|
// policies. The token is signed with the filer write-signing key
|
|
// (jwt.filer_signing.key in security.toml).
|
|
//
|
|
// Validation is delegated to DecodeJwt below: it enforces HS256 via the
|
|
// SigningMethodHMAC type check, and jwt/v5 validates exp/nbf on the embedded
|
|
// RegisteredClaims. Extra JSON fields in the payload are silently ignored by
|
|
// encoding/json, which is the desired behaviour here (forward-compat).
|
|
type SeaweedFilerAdminClaims struct {
|
|
// SessionId is present only on STS session tokens; a token carrying it is
|
|
// an S3 session credential, not a filer admin credential.
|
|
SessionId string `json:"sid,omitempty"`
|
|
// A filer token scoped to paths or methods is not an admin credential.
|
|
AllowedPrefixes []string `json:"allowed_prefixes,omitempty"`
|
|
AllowedMethods []string `json:"allowed_methods,omitempty"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
// GenJwtForFilerAdmin mints a Bearer token for the filer IAM gRPC service.
|
|
// Returns an empty string if the signing key is not configured.
|
|
func GenJwtForFilerAdmin(signingKey SigningKey, expiresAfterSec int) EncodedJwt {
|
|
if len(signingKey) == 0 {
|
|
return ""
|
|
}
|
|
|
|
claims := SeaweedFilerAdminClaims{
|
|
RegisteredClaims: jwt.RegisteredClaims{},
|
|
}
|
|
if expiresAfterSec > 0 {
|
|
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(expiresAfterSec)))
|
|
}
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
encoded, e := t.SignedString([]byte(signingKey))
|
|
if e != nil {
|
|
glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
|
|
return ""
|
|
}
|
|
return EncodedJwt(encoded)
|
|
}
|
|
|
|
func GenJwtForVolumeServer(signingKey SigningKey, expiresAfterSec int, fileId string) EncodedJwt {
|
|
if len(signingKey) == 0 {
|
|
return ""
|
|
}
|
|
|
|
claims := SeaweedFileIdClaims{
|
|
fileId,
|
|
jwt.RegisteredClaims{},
|
|
}
|
|
if expiresAfterSec > 0 {
|
|
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(expiresAfterSec)))
|
|
}
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
encoded, e := t.SignedString([]byte(signingKey))
|
|
if e != nil {
|
|
glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
|
|
return ""
|
|
}
|
|
return EncodedJwt(encoded)
|
|
}
|
|
|
|
// GenJwtForFilerServer creates a JSON-web-token for using the authenticated Filer API. Used f.e. inside
|
|
// the S3 API
|
|
func GenJwtForFilerServer(signingKey SigningKey, expiresAfterSec int) EncodedJwt {
|
|
if len(signingKey) == 0 {
|
|
return ""
|
|
}
|
|
|
|
claims := SeaweedFilerClaims{
|
|
RegisteredClaims: jwt.RegisteredClaims{},
|
|
}
|
|
if expiresAfterSec > 0 {
|
|
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(expiresAfterSec)))
|
|
}
|
|
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
encoded, e := t.SignedString([]byte(signingKey))
|
|
if e != nil {
|
|
glog.V(0).Infof("Failed to sign claims %+v: %v", t.Claims, e)
|
|
return ""
|
|
}
|
|
return EncodedJwt(encoded)
|
|
}
|
|
|
|
func GetJwt(r *http.Request) EncodedJwt {
|
|
|
|
// Get token from query params
|
|
tokenStr := r.URL.Query().Get("jwt")
|
|
|
|
// Get token from authorization header
|
|
if tokenStr == "" {
|
|
bearer := r.Header.Get("Authorization")
|
|
if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
|
|
tokenStr = bearer[7:]
|
|
}
|
|
}
|
|
|
|
// Get token from http only cookie
|
|
if tokenStr == "" {
|
|
token, err := r.Cookie("AT")
|
|
if err == nil {
|
|
tokenStr = token.Value
|
|
}
|
|
}
|
|
|
|
return EncodedJwt(tokenStr)
|
|
}
|
|
|
|
// DecodeJwt verifies tokenString against signingKey, then against each
|
|
// non-empty previousKeys entry, so tokens signed before a key rotation still
|
|
// verify while the previous key is configured.
|
|
func DecodeJwt(signingKey SigningKey, tokenString EncodedJwt, claims jwt.Claims, previousKeys ...SigningKey) (token *jwt.Token, err error) {
|
|
return decodeJwt(signingKey, previousKeys, tokenString, claims)
|
|
}
|
|
|
|
func decodeJwt(signingKey SigningKey, previousKeys []SigningKey, tokenString EncodedJwt, claims jwt.Claims, options ...jwt.ParserOption) (token *jwt.Token, err error) {
|
|
var key interface{} = []byte(signingKey)
|
|
if keySet := verificationKeySet(signingKey, previousKeys); len(keySet.Keys) > 1 {
|
|
key = keySet
|
|
}
|
|
// check exp, nbf
|
|
return jwt.ParseWithClaims(string(tokenString), claims, func(token *jwt.Token) (interface{}, error) {
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, fmt.Errorf("unknown token method")
|
|
}
|
|
return key, nil
|
|
}, options...)
|
|
}
|
|
|
|
func verificationKeySet(signingKey SigningKey, previousKeys []SigningKey) jwt.VerificationKeySet {
|
|
keySet := jwt.VerificationKeySet{Keys: []jwt.VerificationKey{[]byte(signingKey)}}
|
|
for _, previous := range previousKeys {
|
|
if len(previous) > 0 && string(previous) != string(signingKey) {
|
|
keySet.Keys = append(keySet.Keys, []byte(previous))
|
|
}
|
|
}
|
|
return keySet
|
|
}
|
|
|
|
// FilerJwtProvider signs the credential a filer's HTTP API expects. A nil
|
|
// provider means the process-wide jwt.filer_signing configuration applies.
|
|
type FilerJwtProvider func(isWrite bool) EncodedJwt
|
|
|
|
// LoadFilerJwtFromFile reads jwt.filer_signing from a security file the way
|
|
// LoadClientTLSFromFile reads the TLS section, honoring the same WEED_
|
|
// environment precedence. A nil provider means the file configures no filer
|
|
// signing keys and the process-wide configuration applies. A file that sets
|
|
// only one access level falls back to the process-wide key for the other.
|
|
func LoadFilerJwtFromFile(configFile string) (FilerJwtProvider, error) {
|
|
v := viper.New()
|
|
v.SetConfigFile(configFile)
|
|
v.AutomaticEnv()
|
|
v.SetEnvPrefix("weed")
|
|
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
|
if err := v.ReadInConfig(); err != nil {
|
|
return nil, fmt.Errorf("failed to read security config %s: %v", configFile, err)
|
|
}
|
|
|
|
signingKey := SigningKey(v.GetString("jwt.filer_signing.key"))
|
|
readSigningKey := SigningKey(v.GetString("jwt.filer_signing.read.key"))
|
|
if len(signingKey) == 0 && len(readSigningKey) == 0 {
|
|
return nil, nil
|
|
}
|
|
signingKeyExpires := v.GetInt("jwt.filer_signing.expires_after_seconds")
|
|
readSigningKeyExpires := v.GetInt("jwt.filer_signing.read.expires_after_seconds")
|
|
if len(signingKey) == 0 || len(readSigningKey) == 0 {
|
|
gv := util.GetViper()
|
|
if len(signingKey) == 0 {
|
|
signingKey = SigningKey(gv.GetString("jwt.filer_signing.key"))
|
|
signingKeyExpires = gv.GetInt("jwt.filer_signing.expires_after_seconds")
|
|
}
|
|
if len(readSigningKey) == 0 {
|
|
readSigningKey = SigningKey(gv.GetString("jwt.filer_signing.read.key"))
|
|
readSigningKeyExpires = gv.GetInt("jwt.filer_signing.read.expires_after_seconds")
|
|
}
|
|
}
|
|
if signingKeyExpires < 0 || readSigningKeyExpires < 0 {
|
|
return nil, fmt.Errorf("jwt.filer_signing lifetimes must not be negative")
|
|
}
|
|
if signingKeyExpires == 0 {
|
|
signingKeyExpires = 10
|
|
}
|
|
if readSigningKeyExpires == 0 {
|
|
readSigningKeyExpires = 60
|
|
}
|
|
return func(isWrite bool) EncodedJwt {
|
|
if isWrite {
|
|
return GenJwtForFilerServer(signingKey, signingKeyExpires)
|
|
}
|
|
return GenJwtForFilerServer(readSigningKey, readSigningKeyExpires)
|
|
}, nil
|
|
}
|