Files
seaweedfs/weed/security/jwt.go
T
430ca2b585 filer: path- and method-scoped gRPC tokens (scope enforcement, fail closed) (#12904)
* filer: path- and method-scoped tokens on the filesystem gRPC service

* filer: close scoped admission and compatibility gaps

* filer: test subscription key ambiguity and retained write success

* filer: assert verified peer chains survive subscription fallback

* filer: keep a hard link's count and chunks together under a scoped token

A scoped write may keep a hard link the target already has, but the link
count it sends was stored as is, and its chunks could stay on the name
with the link dropped. Either let a scoped token delete its own name and
take the chunks of a name outside its grants with it: the forged count
reaches zero, or the detached name owns the shared chunks.

The handler recheck now refuses a scoped write that changes a stored
link's count or keeps its chunks without the link. Dropping the link
together with the data, and appending to a linked file, are unchanged.

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

* filer: leave subscriptions with a non-scope bearer to the existing verifier

The stream interceptor refused a SubscribeMetadata or SubscribeLocalMetadata
call whose bearer does not verify under the filer key unless the bearer was
a subscription token, and it checked that token with the peer stripped. With
no subscription key, or on an mTLS peer, the existing verifier admits such a
call, so filer.sync sending another cluster's admin token stopped.

When the bearer is no filer scope, the subscription verifier now decides on
the original context, as before scoped tokens. A scoped token still reaches
the refusal for scoped subscriptions, and malformed metadata is still refused.

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

* filer: refuse scoped writes that would make ancestors outside the grant

A scoped create, append or rename checked only its target. The filer then
creates the target's missing ancestors up to the first one it finds, and
turns that one into a directory if it is a file, dropping its ttl. A token
granted /data/proj/ws could so promote the file /data/proj, or create /q and
/q/r for a grant /q/r/ws.

The scope now walks the same ancestors before admitting the write and
refuses one outside the write grants that is missing or not a directory. A
create with skip_check_parent_directory makes no ancestors and is not
walked.

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

* filer: require write grants for scoped lock mutations

* filer: document scoped signatures and read-only token upgrades

* filer: enforce WORM retention for scoped mutations

* filer: refuse scoped writes through shared hard links

* filer: drop series notes from scope comments

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

* filer: refuse scoped subtree mutations across WORM rules

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:45:34 -08:00

274 lines
9.9 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"`
ReadPrefixes []string `json:"read_prefixes,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
}
// IsScoped reports whether the token restricts the paths it may touch.
func (c *SeaweedFilerClaims) IsScoped() bool {
return c != nil && (len(c.AllowedPrefixes) > 0 || len(c.ReadPrefixes) > 0)
}
// GenJwtForFilerScope mints a filer credential restricted to allowedPrefixes
// (read and write) and readPrefixes (read only). id becomes the "jti" claim:
// the identity used in authorization diagnostics. Returns an empty string
// if the signing key is not configured, the token would not expire, or no
// path grant was supplied.
func GenJwtForFilerScope(signingKey SigningKey, expiresAfter time.Duration, id string, allowedPrefixes, readPrefixes []string) EncodedJwt {
if len(signingKey) == 0 || expiresAfter <= 0 || len(allowedPrefixes) == 0 && len(readPrefixes) == 0 {
return ""
}
claims := SeaweedFilerClaims{
AllowedPrefixes: allowedPrefixes,
ReadPrefixes: readPrefixes,
RegisteredClaims: jwt.RegisteredClaims{
ID: id,
IssuedAt: jwt.NewNumericDate(time.Now()),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expiresAfter)),
},
}
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)
}
// 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"`
ReadPrefixes []string `json:"read_prefixes,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
}
// DecodeJwtWith verifies a filer token with optional previous-key and clock
// leeway support, using the same verification path as DecodeJwt.
func DecodeJwtWith(signingKey, previousKey SigningKey, tokenString EncodedJwt, claims jwt.Claims, leeway time.Duration) (*jwt.Token, error) {
return decodeJwt(signingKey, []SigningKey{previousKey}, tokenString, claims, jwt.WithLeeway(leeway))
}
// 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
}