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

198 lines
7.4 KiB
Go

package security
import (
"context"
"net"
"strings"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
// CheckGrpcAdminPeer authenticates the peer of an admin-plane gRPC handler:
// a client certificate verified by the server's TLS config, or a Bearer token
// signed by signingKey (jwt.filer_signing.key) or one of previousKeys
// (jwt.filer_signing.previous_key). With no key configured remote
// callers cannot be told apart, so only local clients (unix socket, loopback,
// or an address assigned to this host) are allowed.
func CheckGrpcAdminPeer(ctx context.Context, signingKey SigningKey, previousKeys ...SigningKey) error {
if isMtlsVerifiedPeer(ctx) {
return nil
}
if len(signingKey) == 0 {
return CheckLocalGrpcPeer(ctx)
}
return CheckGrpcAdminToken(ctx, signingKey, previousKeys...)
}
var (
filerAdminKeysMu sync.Mutex
lastFilerAdminKeys *[2]SigningKey
)
// FilerAdminKeys returns jwt.filer_signing.key and previous_key as
// security.toml sets them now, for admin-plane handlers in processes that do
// not reload: they follow a rotation, and a previous_key removed from the file
// stops verifying. When the file cannot be read it returns the last pair read,
// else the merged keys.
func FilerAdminKeys() (signingKey, previousKey SigningKey) {
filerAdminKeysMu.Lock()
defer filerAdminKeysMu.Unlock()
if fresh, used, _ := util.ReadConfiguration("security", ""); used != "" {
lastFilerAdminKeys = &[2]SigningKey{SigningKey(freshKey(fresh, "jwt.filer_signing.key")), SigningKey(fresh.GetString("jwt.filer_signing.previous_key"))}
return lastFilerAdminKeys[0], lastFilerAdminKeys[1]
}
if last := lastFilerAdminKeys; last != nil {
return last[0], last[1]
}
v := util.GetViper()
return SigningKey(v.GetString("jwt.filer_signing.key")), SigningKey(v.GetString("jwt.filer_signing.previous_key"))
}
// maxGrpcAdminAuthValues bounds the JWT parses one request can trigger; a
// caller sends its own token plus at most one forwarded from its context.
const maxGrpcAdminAuthValues = 4
// CheckGrpcAdminToken accepts the call when one of the first
// maxGrpcAdminAuthValues authorization values is a Bearer admin token signed
// by signingKey or one of previousKeys, so a fresh token still counts when the
// caller's context also forwards an older one.
func CheckGrpcAdminToken(ctx context.Context, signingKey SigningKey, previousKeys ...SigningKey) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Error(codes.Unauthenticated, "missing metadata")
}
authHeaders := md.Get("authorization")
if len(authHeaders) == 0 {
return status.Error(codes.Unauthenticated, "missing authorization metadata")
}
if len(authHeaders) > maxGrpcAdminAuthValues {
authHeaders = authHeaders[:maxGrpcAdminAuthValues]
}
err := status.Error(codes.Unauthenticated, "authorization header must use Bearer scheme")
for _, raw := range authHeaders {
parts := strings.Fields(raw)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || parts[1] == "" {
continue
}
if IsFilerAdminToken(signingKey, EncodedJwt(parts[1]), previousKeys...) {
return nil
}
err = status.Error(codes.Unauthenticated, "invalid admin token")
}
return err
}
// IsFilerAdminToken reports whether token is an admin token signed by
// signingKey or one of previousKeys. An STS session token, or a filer token
// scoped to paths or methods, signed with the same key does not count.
func IsFilerAdminToken(signingKey SigningKey, token EncodedJwt, previousKeys ...SigningKey) bool {
if len(signingKey) == 0 || token == "" {
return false
}
parsed, err := DecodeJwt(signingKey, token, &SeaweedFilerAdminClaims{}, previousKeys...)
if err != nil || parsed == nil || !parsed.Valid {
return false
}
claims, ok := parsed.Claims.(*SeaweedFilerAdminClaims)
return ok && claims.SessionId == "" && len(claims.AllowedPrefixes) == 0 && len(claims.AllowedMethods) == 0 && len(claims.ReadPrefixes) == 0
}
// IsFilerAdminTokenWithLeeway is IsFilerAdminToken under the filer's gRPC
// clock policy: expiry and not-before are checked with leeway, as for scoped
// tokens. Callers outside that policy keep IsFilerAdminToken's strict check.
func IsFilerAdminTokenWithLeeway(signingKey, previousKey SigningKey, token EncodedJwt, leeway time.Duration) bool {
if len(signingKey) == 0 || token == "" {
return false
}
claims := &SeaweedFilerAdminClaims{}
parsed, err := DecodeJwtWith(signingKey, previousKey, token, claims, leeway)
if err != nil || parsed == nil || !parsed.Valid {
return false
}
return claims.SessionId == "" && len(claims.AllowedPrefixes) == 0 && len(claims.AllowedMethods) == 0 && len(claims.ReadPrefixes) == 0
}
// GrpcAdminPeerCredentials returns outgoing metadata carrying a Bearer token
// for admin-plane gRPC handlers, or nil when no signing key is configured.
func GrpcAdminPeerCredentials(signingKey SigningKey, expiresAfterSec int) metadata.MD {
token := GenJwtForFilerAdmin(signingKey, expiresAfterSec)
if token == "" {
return nil
}
return metadata.Pairs("authorization", "Bearer "+string(token))
}
// WithFilerPeerCredentials authenticates one filer-owned RPC attempt. The caller
// resolves the current key for each attempt; the connection carries no authority.
func WithFilerPeerCredentials(ctx context.Context, signingKey SigningKey) context.Context {
md, _ := metadata.FromOutgoingContext(ctx)
md = md.Copy()
md.Delete("authorization")
if auth := GrpcAdminPeerCredentials(signingKey, 10); auth != nil {
md.Set("authorization", auth.Get("authorization")...)
}
return metadata.NewOutgoingContext(ctx, md)
}
func isMtlsVerifiedPeer(ctx context.Context) bool {
pr, ok := peer.FromContext(ctx)
if !ok {
return false
}
tlsInfo, ok := pr.AuthInfo.(credentials.TLSInfo)
return ok && len(tlsInfo.State.VerifiedChains) > 0
}
// CheckLocalGrpcPeer admits only clients on this host: unix sockets, loopback,
// or an address assigned to a local interface.
func CheckLocalGrpcPeer(ctx context.Context) error {
if ctx == nil {
return status.Error(codes.Unauthenticated, "admin gRPC calls require jwt.filer_signing.key or a local client")
}
pr, ok := peer.FromContext(ctx)
if !ok {
return status.Error(codes.Unauthenticated, "admin gRPC calls require jwt.filer_signing.key or a local client")
}
if _, isUnix := pr.Addr.(*net.UnixAddr); isUnix {
return nil
}
var ip net.IP
if tcpAddr, ok := pr.Addr.(*net.TCPAddr); ok {
ip = tcpAddr.IP
} else if h, _, err := net.SplitHostPort(pr.Addr.String()); err == nil {
ip = net.ParseIP(h)
} else {
ip = net.ParseIP(pr.Addr.String())
}
if ip != nil && (ip.IsLoopback() || isLocalAddress(ip)) {
return nil
}
glog.V(1).Infof("rejected unauthenticated admin gRPC call from %s: no jwt.filer_signing.key configured", pr.Addr)
return status.Error(codes.Unauthenticated, "admin gRPC calls require jwt.filer_signing.key or a local client")
}
// isLocalAddress enumerates interfaces per call: only reachable for
// non-loopback TCP peers on the no-key admin path, which is low-volume —
// and a cached set would keep trusting an address after it is removed from
// the host and reassigned.
func isLocalAddress(ip net.IP) bool {
addrs, err := net.InterfaceAddrs()
if err != nil {
return false
}
for _, a := range addrs {
if ipNet, ok := a.(*net.IPNet); ok && ipNet.IP.Equal(ip) {
return true
}
}
return false
}