Files
seaweedfs/weed/security/metadata_subscribe.go
T
a9fda6b50f filer clients: authenticate filer gRPC calls with per-call admin tokens (#13039)
* Add per-call filer authentication sources and pooled client wrappers

* Authenticate gateway filer calls with per-call admin tokens

* Authenticate shell admin and synchronization filer calls

* Authenticate workers MQ and remaining filer client paths

* Cache filer client signing keys and sign subscriptions with the shared key

Re-reading security.toml on every filer RPC cost about 125us against 8us for
signing. Keep the keys for up to a second, re-reading at once when a WEED_
override or the configuration directory changes. When the file exists but
cannot be read, keep the last keys read, else the startup keys, as
FilerAdminKeys does, so a process without a key stays tokenless. Metadata
subscriptions prefer the shared key, as filer peers do, because older filers
verify subscription admin tokens only with it.

* Authenticate admin-script, maintenance and filer.conf shell paths

Plugin worker admin scripts and master maintenance scripts build their own
shell options and carried no filer token source; fs.configure and
s3.bucket.quota.check read filer.conf without it.

* filer.cat: report a failed read; isolate key overrides in the admin-script test

filer.cat ignored the error from its filer call and exited successfully,
leaving a truncated -output file. Report the error and exit with failure.
The admin-script token test now clears the WEED_ signing-key overrides,
which take precedence over security.toml.

* security: refuse gRPC keys too short to sign; query engine uses client TLS

Under GODEBUG=fips140=only, hmac.New panics on keys under 14 bytes. The
startup check now covers jwt.filer_signing.grpc_key and grpc_previous_key,
and filer client token sources check the keys they read, so a reloaded or
per-endpoint security file with a short key is refused instead of
panicking when the next RPC signs.

The query engine's broker client dialed every master, filer and broker in
plaintext, so the admin token it now sends could cross the network in the
clear. It dials with the grpc.client TLS settings instead, and weed-sql
loads security.toml as weed-db does.

* security: per-endpoint admin tokens ignore WEED_ key overrides

FilerAdminTokenFromFile honored WEED_JWT_FILER_SIGNING_GRPC_KEY and
WEED_JWT_FILER_SIGNING_KEY. Those are process-wide, so filer.sync with
-a.security and -b.security signed both clusters' admin tokens with the
one key, handing each cluster a token valid on the other. A per-endpoint
file now supplies its own keys only.

* weed-sql, weed-db: refuse to start on an unreadable security.toml

Both only warned when security.toml was present but could not be read or
parsed. They then dialed without the grpc.client TLS settings while the
filer token source could still sign admin tokens from WEED_ environment
keys, so the tokens could travel in plaintext. They now exit with an
error that does not quote the file; a missing file is still fine.

* pb: take the filer token source in WithGrpcFilerClient and WithOneOfGrpcFilerClients

Fold WithGrpcFilerClientAuth and WithOneOfGrpcFilerClientsAuth into the
existing helpers instead of keeping two names for each. Callers without a
token source pass nil.

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

* util: return the read error from ReadConfiguration

Fold ReadConfigurationWithError into ReadConfiguration. The error is
returned and not logged, since parser errors can quote values; the
existing reload callers already warn when no file was read.

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

* security: keep the test-only filerAdminToken helper in the test

It had no production caller. The test helper now resolves keys through
filerClientKeysFrom, as the token sources do.

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

* util: read security.toml once in LoadSecurityConfigurationOrError

It validated the file, then merged it with a second read whose failure
was ignored and whose parser error was logged. It now merges with one
read and logs nothing from the parser. Viper's search also treats a
directory the process cannot search as holding no file; a candidate
that cannot be checked for lack of permission is now refused too.

* security: verify admin subscription tokens with the gRPC clock leeway

CheckGrpcMetadataSubscription checked admin tokens strictly, while unary
filer calls allow jwt.filer_signing.clock_leeway_seconds. With ten-second
client admin tokens, a subscriber whose clock trailed the filer's by more
than ten seconds was refused with a matching key. It now takes the leeway,
and the filer passes its configured one. The leeway check moves from the
server package to security.IsFilerAdminTokenWithLeeway so both use it.

* util: start without security.toml only when every candidate is confirmed absent

A candidate whose check fails for any reason other than not existing,
such as a symlink loop, is refused like one the process cannot search.

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:53:59 -08:00

151 lines
5.5 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. Admin tokens are checked with leeway, the filer's gRPC
// clock leeway, as unary filer calls check them.
func CheckGrpcMetadataSubscription(ctx context.Context, subscribeKey, adminKey, previousAdminKey SigningKey, method string, leeway time.Duration) (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 IsFilerAdminTokenWithLeeway(adminKey, previousAdminKey, token, leeway) {
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))
}