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

150 lines
5.4 KiB
Go

package security
import (
"context"
"path"
"strings"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// The filer gRPC methods a scoped subscription token may name in allowed_methods.
const (
MethodSubscribeMetadata = "SubscribeMetadata"
MethodSubscribeLocalMetadata = "SubscribeLocalMetadata"
)
// GenJwtForMetadataSubscription mints a read-only token for the filer's
// metadata subscription calls, limited to events under prefixes. It carries
// allowed_prefixes and allowed_methods, so it is never an admin token.
// Returns an empty string without a key, an expiry, or an absolute prefix.
func GenJwtForMetadataSubscription(signingKey SigningKey, expiresAfterSec int, prefixes []string) EncodedJwt {
prefixes, ok := cleanMetadataPrefixes(prefixes)
if len(signingKey) == 0 || expiresAfterSec <= 0 || !ok {
return ""
}
claims := SeaweedFilerClaims{
AllowedPrefixes: prefixes,
AllowedMethods: []string{MethodSubscribeMetadata, MethodSubscribeLocalMetadata},
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * time.Duration(expiresAfterSec))),
},
}
encoded, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(signingKey))
if err != nil {
glog.V(0).Infof("Failed to sign metadata subscription claims: %v", err)
return ""
}
return EncodedJwt(encoded)
}
// cleanMetadataPrefixes cleans prefixes; ok is false when the list is empty
// or any prefix is not absolute.
func cleanMetadataPrefixes(prefixes []string) (cleaned []string, ok bool) {
for _, p := range prefixes {
if !strings.HasPrefix(p, "/") {
return nil, false
}
cleaned = append(cleaned, path.Clean(p))
}
return cleaned, len(cleaned) > 0
}
// MetadataPathInScope reports whether fullPath is one of the prefixes or below
// one, by whole path segments: "/buckets/a" holds "/buckets/a/x", not "/buckets/ab".
func MetadataPathInScope(fullPath string, prefixes []string) bool {
fullPath = path.Clean("/" + fullPath)
for _, p := range prefixes {
if p == "/" || fullPath == p || strings.HasPrefix(fullPath, p+"/") {
return true
}
}
return false
}
// MetadataSubscriptionScope limits a subscription to events under Prefixes
// until ExpiresAt.
type MetadataSubscriptionScope struct {
Prefixes []string
ExpiresAt time.Time
}
func metadataSubscriptionScope(signingKey SigningKey, token EncodedJwt, method string) (*MetadataSubscriptionScope, bool) {
parsed, err := decodeJwt(signingKey, nil, token, &SeaweedFilerClaims{}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil || parsed == nil || !parsed.Valid {
return nil, false
}
claims, ok := parsed.Claims.(*SeaweedFilerClaims)
if !ok || claims.SessionId != "" || claims.ExpiresAt == nil {
return nil, false
}
allowsMethod := false
for _, m := range claims.AllowedMethods {
if m != MethodSubscribeMetadata && m != MethodSubscribeLocalMetadata {
return nil, false
}
allowsMethod = allowsMethod || m == method
}
if !allowsMethod {
return nil, false
}
prefixes, ok := cleanMetadataPrefixes(claims.AllowedPrefixes)
if !ok {
return nil, false
}
return &MetadataSubscriptionScope{Prefixes: prefixes, ExpiresAt: claims.ExpiresAt.Time}, true
}
// CheckGrpcMetadataSubscription authorizes a metadata subscription call.
// Without subscribeKey every caller is unrestricted (nil scope). With it, an
// mTLS-verified peer or an admin token signed by adminKey or previousAdminKey
// is unrestricted, and a token signed by subscribeKey is limited to the
// returned scope.
func CheckGrpcMetadataSubscription(ctx context.Context, subscribeKey, adminKey, previousAdminKey SigningKey, method string) (scope *MetadataSubscriptionScope, err error) {
if len(subscribeKey) == 0 || isMtlsVerifiedPeer(ctx) {
return nil, nil
}
md, _ := metadata.FromIncomingContext(ctx)
authHeaders := md.Get("authorization")
if len(authHeaders) > maxGrpcAdminAuthValues {
authHeaders = authHeaders[:maxGrpcAdminAuthValues]
}
for _, raw := range authHeaders {
parts := strings.Fields(raw)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || parts[1] == "" {
continue
}
token := EncodedJwt(parts[1])
if IsFilerAdminToken(adminKey, token, previousAdminKey) {
return nil, nil
}
if scope, ok := metadataSubscriptionScope(subscribeKey, token, method); ok {
return scope, nil
}
}
return nil, status.Error(codes.Unauthenticated, "metadata subscription requires mTLS, an admin token, or a subscription token for this method")
}
// WithMetadataSubscriptionCredentials adds an admin token to a subscription
// call: from jwtProvider when the caller has per-cluster keys, else when this
// process has both jwt.filer_signing.key and jwt.filer_signing.subscribe.key,
// so internal subscribers keep full access.
func WithMetadataSubscriptionCredentials(ctx context.Context, jwtProvider FilerJwtProvider) context.Context {
var token EncodedJwt
if jwtProvider != nil {
token = jwtProvider(true)
} else if v := util.GetViper(); v.GetString("jwt.filer_signing.subscribe.key") != "" {
token = GenJwtForFilerAdmin(SigningKey(v.GetString("jwt.filer_signing.key")), v.GetInt("jwt.filer_signing.expires_after_seconds"))
}
if token == "" {
return ctx
}
return metadata.AppendToOutgoingContext(ctx, "authorization", BearerPrefix+string(token))
}