filer: grpc_require_token with authenticated filer-to-filer peer calls (#13011)

* filer: require bearer tokens for configured gRPC calls

* filer: authenticate owned peer RPCs with per-call admin tokens

* filer: retain scoped forwarding refusals with required authentication

* filer: preserve tokenless HTTP forwarding outside require mode

* filer: honor clock tolerance for gRPC admin fallback

* filer: preserve caller token on lock owner forwards

* filer: forward caller auth on target ping

* filer: authenticate startup peer digest checks

* filer: verify required subscription bearers independently of mTLS

* filer: assert exact caller bearer on forwarded ping

* filer: sign peer tokens with the gRPC verification key

peerContext signed filer-owned RPCs with jwt.filer_signing.key only. With
grpc_key as the only key and require-mode on, peer calls went out tokenless
and were refused. With both keys set, peers that verify with grpc_key and
lack the shared-key admin fallback refused the shared-key token even with
require-mode off. Sign with the key filesystem gRPC verifies, and keep the
shared key for metadata subscriptions, whose verifier accepts admin tokens
signed only with it.

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

* filer: keep a subscription token's scope over mTLS in require-mode

Require-mode admitted a dedicated subscription bearer without the mTLS
shortcut, but the handler re-checked it with the certificate, which
granted the full stream past the token's prefixes and expiry.

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

* filer: delete uploaded chunks when the write owner refuses authentication

A forwarded HTTP append or offset write that the owner refused as
Unauthenticated kept its new chunks as if the outcome were unknown,
orphaning them.

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

* filer: hand the admitted subscription scope to the handler

The handler re-verified a dedicated subscription token after reading the
request. If the token expired in between, an mTLS peer fell back to the
certificate and got an unrestricted stream. The interceptor now passes
the scope it admitted, and the handler refuses it once expired.

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

* filer: accept grpc_key admin tokens on metadata subscriptions

A filer with only grpc_key signs peer subscriptions with it, but the
subscription verifier checked admin tokens against the shared key only,
so with a subscribe key set the aggregator's peer streams were refused.
An unscoped grpc_key token already has full filer gRPC access.

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

* filer: delete the generated manifest when the write owner refuses authentication

A forwarded HTTP append that crossed the manifest threshold left the
manifest blob it had uploaded orphaned when the owner refused the call
as Unauthenticated. The blob alone is deleted, since the manifest also
lists committed chunks.

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

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-26 08:18:28 -08:00
1 parent 519c2af3c8
commit f079b68f2b
30 files changed
+1900 -48

No files matched your search

+11 -1
View File
@@ -17,7 +17,11 @@ import (
)
type LockClient struct {
grpcDialOption grpc.DialOption
grpcDialOption grpc.DialOption
// RequestContext, when set before using the client, supplies per-attempt
// metadata for lock, renewal and unlock RPCs. Generic clients retain their
// existing authority when it is nil.
RequestContext func(context.Context) context.Context
maxLockDuration time.Duration
sleepDuration time.Duration
seedFiler pb.ServerAddress
@@ -435,6 +439,9 @@ func (lock *LiveLock) StopShortLivedLock() error {
return pb.WithFilerClient(false, 0, lock.hostFiler, lock.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
ctx, cancel := context.WithTimeout(context.Background(), lock.lc.lockRpcTimeout)
defer cancel()
if lock.lc.RequestContext != nil {
ctx = lock.lc.RequestContext(ctx)
}
_, err := client.DistributedUnlock(ctx, &filer_pb.UnlockRequest{
Name: lock.key,
RenewToken: lock.renewToken,
@@ -493,6 +500,9 @@ func (lock *LiveLock) doLock(lockDuration, attemptTimeout time.Duration) (errorM
// but not from this filer would otherwise block on the connect timeout.
ctx, cancel := context.WithTimeout(context.Background(), attemptTimeout)
defer cancel()
if lock.lc.RequestContext != nil {
ctx = lock.lc.RequestContext(ctx)
}
resp, err := client.DistributedLock(ctx, &filer_pb.LockRequest{
Name: lock.key,
SecondsToLock: int64(lockDuration.Seconds()),
+4
View File
@@ -137,6 +137,10 @@ previous_key = ""
# When grpc_key is unset, the shared HTTP current/previous pair is used.
# grpc_key = ""
# grpc_previous_key = ""
# Require every filesystem gRPC call to carry a valid bearer token. This also
# refuses verified mTLS peers that do not present a token. The setting is off
# by default for compatibility with existing tokenless callers.
# grpc_require_token = false
# AssignVolume returns a proof bound to the holder, chunk-ID range and resolved
# collection in assign_auth. Return it under the chunk's file id in chunk_auth
# when storing the entry. Auth remains the separate volume-upload credential.
+15 -9
View File
@@ -61,12 +61,18 @@ type Filer struct {
MasterClient *wdclient.MasterClient
FileIdDeletionQueue *util.UnboundedQueue
GrpcDialOption grpc.DialOption
dialOptions *DialOptions
DirBucketsPath string
Cipher bool
LocalMetaLogBuffer *log_buffer.LogBuffer
metaLogCollection string
metaLogReplication string
// PeerContext supplies fresh per-call authentication for filer-owned RPCs.
// Set it before bootstrap or peer aggregation starts.
PeerContext func(context.Context) context.Context
// PeerSubscriptionContext authenticates peer metadata subscriptions; when
// nil, PeerContext is used.
PeerSubscriptionContext func(context.Context) context.Context
dialOptions *DialOptions
DirBucketsPath string
Cipher bool
LocalMetaLogBuffer *log_buffer.LogBuffer
metaLogCollection string
metaLogReplication string
// Override where system metadata-log chunks are assigned, keeping the
// internal log out of the default collection; empty keeps today's
// behaviour. Set via viper: filer.options.metaLog.collection / .replication.
@@ -281,7 +287,7 @@ func (f *Filer) readPeerDigest(ctx context.Context, peer pb.ServerAddress) (sign
ctx, cancel := context.WithTimeout(ctx, peerDigestReadTimeout)
defer cancel()
err = pb.WithFilerClient(false, f.UniqueFilerId, peer, f.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
resp, err := client.GetFilerConfiguration(f.peerCallContext(ctx), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return err
}
@@ -306,14 +312,14 @@ func (f *Filer) MaybeBootstrapFromOnePeer(ctx context.Context, self pb.ServerAdd
glog.V(0).Infof("bootstrap from %v clientId:%d", earliestNode.Address, f.UniqueFilerId)
return pb.WithFilerClient(false, f.UniqueFilerId, pb.ServerAddress(earliestNode.Address), f.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
resp, err := client.GetFilerConfiguration(f.peerCallContext(ctx), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return fmt.Errorf("read configuration of %s: %w", earliestNode.Address, err)
}
if err := checkPeerDigest(pb.ServerAddress(earliestNode.Address), resp.Digest, false); err != nil {
return err
}
return filer_pb.StreamBfs(ctx, client, "/", snapshotTime.UnixNano(), func(parentPath util.FullPath, pbEntry *filer_pb.Entry, entryTsNs int64) error {
return filer_pb.StreamBfs(f.peerCallContext(ctx), client, "/", snapshotTime.UnixNano(), func(parentPath util.FullPath, pbEntry *filer_pb.Entry, entryTsNs int64) error {
entry := FromPbEntry(string(parentPath), pbEntry)
peerTsNs := entryTsNs
if peerTsNs == 0 {
+37
View File
@@ -0,0 +1,37 @@
package filer
import (
"context"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc"
)
func (f *Filer) peerCallContext(ctx context.Context) context.Context {
if f != nil && f.PeerContext != nil {
return f.PeerContext(ctx)
}
return ctx
}
func (f *Filer) peerSubscriptionContext(ctx context.Context) context.Context {
if f != nil && f.PeerSubscriptionContext != nil {
return f.PeerSubscriptionContext(ctx)
}
if f != nil && f.PeerContext != nil {
return f.PeerContext(ctx)
}
return security.WithMetadataSubscriptionCredentials(ctx, nil)
}
// A metadata stream can fetch many log chunks over its lifetime. Resolve the
// credential for each volume lookup, rather than retaining the stream's token.
type peerLookupClient struct {
filer_pb.SeaweedFilerClient
peerContext func(context.Context) context.Context
}
func (c peerLookupClient) LookupVolume(ctx context.Context, req *filer_pb.LookupVolumeRequest, opts ...grpc.CallOption) (*filer_pb.LookupVolumeResponse, error) {
return c.SeaweedFilerClient.LookupVolume(c.peerContext(ctx), req, opts...)
}
+139
View File
@@ -0,0 +1,139 @@
package filer
import (
"context"
"crypto/rand"
"net"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type authenticatedPeerServer struct {
filer_pb.UnimplementedSeaweedFilerServer
key atomic.Value
mu sync.Mutex
calls map[string]int
}
func (s *authenticatedPeerServer) authenticate(ctx context.Context, method string) error {
if err := security.CheckGrpcAdminToken(ctx, s.key.Load().(security.SigningKey)); err != nil {
return err
}
s.mu.Lock()
s.calls[method]++
s.mu.Unlock()
return nil
}
func (s *authenticatedPeerServer) GetFilerConfiguration(context.Context, *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) {
return &filer_pb.GetFilerConfigurationResponse{Signature: 7}, nil
}
func (s *authenticatedPeerServer) TraverseBfsMetadata(*filer_pb.TraverseBfsMetadataRequest, filer_pb.SeaweedFiler_TraverseBfsMetadataServer) error {
return nil
}
func (s *authenticatedPeerServer) SubscribeLocalMetadata(*filer_pb.SubscribeMetadataRequest, filer_pb.SeaweedFiler_SubscribeLocalMetadataServer) error {
return nil
}
func (s *authenticatedPeerServer) LookupVolume(context.Context, *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) {
return &filer_pb.LookupVolumeResponse{}, nil
}
func TestPeerMetadataAuthenticationOnEachAttempt(t *testing.T) {
peer := &authenticatedPeerServer{calls: make(map[string]int)}
rotate := func() {
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
t.Fatal(err)
}
peer.key.Store(security.SigningKey(key))
}
rotate()
lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
address := pb.NewServerAddressWithGrpcPort(lis.Addr().String(), lis.Addr().(*net.TCPAddr).Port)
server := grpc.NewServer(
grpc.UnaryInterceptor(func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if err := peer.authenticate(ctx, info.FullMethod); err != nil {
return nil, err
}
return handler(ctx, req)
}),
grpc.StreamInterceptor(func(srv any, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
if err := peer.authenticate(stream.Context(), info.FullMethod); err != nil {
return err
}
return handler(srv, stream)
}),
)
filer_pb.RegisterSeaweedFilerServer(server, peer)
go server.Serve(lis)
t.Cleanup(func() { server.Stop(); pb.InvalidateGrpcConnection(address.ToGrpcAddress()) })
dial := grpc.WithTransportCredentials(insecure.NewCredentials())
var resolved atomic.Int32
f := &Filer{Signature: 7, GrpcDialOption: dial, PeerContext: func(ctx context.Context) context.Context {
resolved.Add(1)
return security.WithFilerPeerCredentials(ctx, peer.key.Load().(security.SigningKey))
}}
ma := NewMetaAggregator(f, "127.0.0.1:1", dial)
t.Cleanup(ma.Shutdown)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for round := 0; round < 2; round++ {
rotate()
if err := f.CheckPeerDigests(ctx, "127.0.0.1:1", []*master_pb.ClusterNodeUpdate{{Address: string(address)}}); err != nil {
t.Fatal(err)
}
if err := f.MaybeBootstrapFromOnePeer(ctx, "127.0.0.1:1", []*master_pb.ClusterNodeUpdate{{Address: string(address)}}, time.Now()); err != nil {
t.Fatal(err)
}
if err := ma.traversePeerMetadata(ctx, f, address); err != nil {
t.Fatal(err)
}
if sig, digest, err := ma.readFilerStoreSignature(ctx, address); err != nil || sig != 7 || digest != "" {
t.Fatalf("configuration lookup: signature=%d digest=%q err=%v", sig, digest, err)
}
stop := make(chan struct{})
_, err := ma.doSubscribeToOneFiler(f, "127.0.0.1:1", address, 1, stop)
close(stop)
if err != nil {
t.Fatal(err)
}
err = pb.WithFilerClient(false, 0, address, dial, func(client filer_pb.SeaweedFilerClient) error {
wrapped := peerLookupClient{client, f.peerCallContext}
_, err := wrapped.LookupVolume(ctx, &filer_pb.LookupVolumeRequest{})
return err
})
if err != nil {
t.Fatal(err)
}
}
if got := resolved.Load(); got != 16 {
t.Fatalf("resolved authentication %d times, want once for each of 16 RPC attempts", got)
}
peer.mu.Lock()
defer peer.mu.Unlock()
for method, want := range map[string]int{
filer_pb.SeaweedFiler_GetFilerConfiguration_FullMethodName: 8,
filer_pb.SeaweedFiler_TraverseBfsMetadata_FullMethodName: 4,
filer_pb.SeaweedFiler_SubscribeLocalMetadata_FullMethodName: 2,
filer_pb.SeaweedFiler_LookupVolume_FullMethodName: 2,
} {
if got := peer.calls[method]; got != want {
t.Errorf("%s authenticated calls=%d, want %d", method, got, want)
}
}
}
+4 -5
View File
@@ -12,7 +12,6 @@ import (
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
@@ -762,12 +761,12 @@ func (ma *MetaAggregator) doSubscribeToOneFiler(f *Filer, self pb.ServerAddress,
// below stops promptly on removal or shutdown.
atomic.AddInt32(&ma.filer.UniqueFilerEpoch, 1)
// Construct a log file reader that reads chunks via the peer filer's LookupVolume.
lookupFn := LookupFn(filerClient{client})
lookupFn := LookupFn(filerClient{peerLookupClient{client, ma.filer.peerCallContext}})
logFileReaderFn := func(chunks []*filer_pb.FileChunk) (io.ReadCloser, error) {
return NewChunkStreamReaderFromLookup(ctx, lookupFn, chunks), nil
}
stream, err := client.SubscribeLocalMetadata(security.WithMetadataSubscriptionCredentials(ctx, nil), &filer_pb.SubscribeMetadataRequest{
stream, err := client.SubscribeLocalMetadata(ma.filer.peerSubscriptionContext(ctx), &filer_pb.SubscribeMetadataRequest{
ClientName: "filer:" + string(self),
PathPrefix: "/",
SinceNs: lastTsNs,
@@ -927,7 +926,7 @@ var errPeerSubscriptionStopped = errors.New("peer subscription stopped")
// out-wait a long traversal.
func (ma *MetaAggregator) traversePeerMetadata(ctx context.Context, f *Filer, peer pb.ServerAddress) error {
return pb.WithFilerClient(true, 0, peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
stream, err := client.TraverseBfsMetadata(ctx, &filer_pb.TraverseBfsMetadataRequest{
stream, err := client.TraverseBfsMetadata(f.peerCallContext(ctx), &filer_pb.TraverseBfsMetadataRequest{
Directory: "/",
ExcludedPrefixes: []string{SystemLogDir},
})
@@ -1013,7 +1012,7 @@ func (f *Filer) applyTraversedEntry(ctx context.Context, entry *Entry, peerTsNs
// digest it reports, empty for a filer that predates the setting.
func (ma *MetaAggregator) readFilerStoreSignature(ctx context.Context, peer pb.ServerAddress) (sig int32, digest string, err error) {
err = pb.WithFilerClient(false, 0, peer, ma.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{})
resp, err := client.GetFilerConfiguration(ma.filer.peerCallContext(ctx), &filer_pb.GetFilerConfigurationRequest{})
if err != nil {
return err
}
+55
View File
@@ -0,0 +1,55 @@
package security
import (
"context"
"crypto/rand"
"testing"
"time"
"google.golang.org/grpc/metadata"
)
func TestFilerPeerCredentialsPerCall(t *testing.T) {
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
original := metadata.Pairs("authorization", "stale", "authorization", "other", "trace-id", "test-trace")
ctx = metadata.NewOutgoingContext(ctx, original)
ctx = metadata.NewIncomingContext(ctx, metadata.Pairs("authorization", "caller-token"))
before := time.Now()
peerCtx := WithFilerPeerCredentials(ctx, key)
md, _ := metadata.FromOutgoingContext(peerCtx)
if got := md.Get("authorization"); len(got) != 1 {
t.Fatalf("authorization count=%d, want one", len(got))
}
if md.Get("trace-id")[0] != "test-trace" || len(original.Get("authorization")) != 2 {
t.Fatal("peer credentials changed unrelated metadata or mutated the caller's metadata")
}
if err := CheckGrpcAdminToken(metadata.NewIncomingContext(context.Background(), md), key); err != nil {
t.Fatalf("peer token was not accepted as admin: %v", err)
}
claims := &SeaweedFilerClaims{}
raw := EncodedJwt(md.Get("authorization")[0][len("Bearer "):])
if _, err := DecodeJwt(key, raw, claims); err != nil {
t.Fatalf("decode peer token: %v", err)
}
if claims.ExpiresAt == nil || claims.ExpiresAt.Time.Before(before.Add(9*time.Second)) || claims.ExpiresAt.Time.After(time.Now().Add(10*time.Second)) {
t.Fatal("peer token does not have the fixed ten-second lifetime")
}
deadline, ok := peerCtx.Deadline()
wantDeadline, _ := ctx.Deadline()
if !ok || !deadline.Equal(wantDeadline) {
t.Fatal("peer metadata changed the deadline")
}
cleared, _ := metadata.FromOutgoingContext(WithFilerPeerCredentials(peerCtx, nil))
if len(cleared.Get("authorization")) != 0 || cleared.Get("trace-id")[0] != "test-trace" {
t.Fatal("key removal did not remove only the authorization")
}
cancel()
if peerCtx.Err() != context.Canceled {
t.Fatal("peer metadata detached cancellation")
}
}
+12
View File
@@ -114,6 +114,18 @@ func GrpcAdminPeerCredentials(signingKey SigningKey, expiresAfterSec int) metada
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 {
+63
View File
@@ -0,0 +1,63 @@
package weed_server
import (
"context"
"net/http"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc/metadata"
)
// withCallerAuthContext carries the caller's bearer to the next filer hop.
// It deliberately copies only authorization; filer-owned calls use
// peerContext instead and therefore never inherit a caller's authority.
func withCallerAuthContext(ctx context.Context) context.Context {
incoming, _ := metadata.FromIncomingContext(ctx)
return withAuthorizationValues(ctx, incoming.Get("authorization"))
}
// withHTTPBearerContext adapts the bearer already authenticated on an HTTP
// request to the metadata form used by the outgoing filer RPC. An absent
// bearer remains absent, preserving tokenless compatibility when require-mode
// is disabled and allowing require-mode to reject it at the receiver.
func withHTTPBearerContext(ctx context.Context, token security.EncodedJwt) context.Context {
if token == "" {
return withAuthorizationValues(ctx, nil)
}
return withAuthorizationValues(ctx, []string{security.BearerPrefix + string(token)})
}
// withHTTPForwardAuthContext carries an HTTP caller's bearer only when
// require-mode is enabled. In the compatibility mode,
// explicitly remove authorization so a stale token from an outer call cannot
// change the request's existing tokenless behavior.
func (fs *FilerServer) withHTTPForwardAuthContext(ctx context.Context, r *http.Request) context.Context {
var token security.EncodedJwt
if settings := fs.grpcScopeSettings.Load(); settings != nil && settings.requireToken {
token = security.GetJwt(r)
}
return withHTTPBearerContext(ctx, token)
}
func withAuthorizationValues(ctx context.Context, values []string) context.Context {
outgoing, ok := metadata.FromOutgoingContext(ctx)
if len(values) == 0 {
if !ok || len(outgoing.Get("authorization")) == 0 {
return ctx
}
outgoing = outgoing.Copy()
delete(outgoing, "authorization")
return metadata.NewOutgoingContext(ctx, outgoing)
}
if outgoing == nil {
outgoing = metadata.MD{}
} else {
outgoing = outgoing.Copy()
}
// A context may already carry a metadata value from a caller or an earlier
// forwarding helper. Replace it so the next hop sees exactly the caller's
// original authorization values, never a duplicate or an admin token.
delete(outgoing, "authorization")
outgoing.Set("authorization", values...)
return metadata.NewOutgoingContext(ctx, outgoing)
}
@@ -0,0 +1,276 @@
package weed_server
import (
"context"
"fmt"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer/posixlock"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
func peerClient(t *testing.T, c *twoFilers, addr pb.ServerAddress, token string) filer_pb.SeaweedFilerClient {
t.Helper()
conn, err := grpc.NewClient(
"passthrough:///"+addr.ToGrpcAddress(),
c.dial,
grpc.WithPerRPCCredentials(scopeToken(token)),
)
if err != nil {
t.Fatalf("dial filer %s: %v", addr, err)
}
t.Cleanup(func() { _ = conn.Close() })
return filer_pb.NewSeaweedFilerClient(conn)
}
func peerAdminToken(key security.SigningKey) string {
return string(security.GenJwtForFilerServer(key, 60))
}
func peerScopedWriteToken(key security.SigningKey) string {
return string(security.GenJwtForFilerScope(key, time.Minute, "peer-forward", []string{"/"}, nil))
}
func peerPosixKey(c *twoFilers, owner pb.ServerAddress) string {
for i := 0; i < 4000; i++ {
key := fmt.Sprintf("s3.fuse.lock:/peer-%d", i)
if c.fsA.filer.Dlm.LockRing.GetPrimary(key) == owner && c.fsB.filer.Dlm.LockRing.GetPrimary(key) == owner {
return key
}
}
return ""
}
func peerLockKey(c *twoFilers, owner pb.ServerAddress) string {
for i := 0; i < 4000; i++ {
key := fmt.Sprintf("peer-lock-%d", i)
if c.fsA.filer.Dlm.LockRing.GetPrimary(key) == owner && c.fsB.filer.Dlm.LockRing.GetPrimary(key) == owner {
return key
}
}
return ""
}
func TestPeerRequireCreateDeleteForwarding(t *testing.T) {
for _, operation := range []string{"create", "delete"} {
for _, tc := range []struct {
name string
scoped, remote bool
}{
{"scoped remote", true, true},
{"scoped local", true, false},
{"admin remote", false, true},
} {
t.Run(operation+"/"+tc.name, func(t *testing.T) {
c, key := newPeerFilers(t)
owner := c.addrA
if tc.remote {
owner = c.addrB
}
p := c.keyOwnedBy(t, owner, owner)
dir, name := p.DirAndName()
token := peerAdminToken(key)
if tc.scoped {
token = string(security.GenJwtForFilerScope(key, time.Minute, "test-caller", []string{"/"}, nil))
}
client := peerClient(t, c, c.addrA, token)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var err error
var responseError string
if operation == "create" {
var resp *filer_pb.CreateEntryResponse
resp, err = client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
Directory: dir, OExcl: true,
Entry: &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{FileMode: 0644}, Extended: map[string][]byte{"v": []byte("created")}},
})
responseError = resp.GetError()
} else {
c.seed(t, p)
var resp *filer_pb.DeleteEntryResponse
resp, err = client.DeleteEntry(ctx, &filer_pb.DeleteEntryRequest{Directory: dir, Name: name, ExpectedExtended: map[string][]byte{"v": []byte("seed")}})
responseError = resp.GetError()
}
denied := tc.scoped && tc.remote
want := codes.OK
if denied {
want = codes.PermissionDenied
}
if status.Code(err) != want || (!denied && responseError != "") {
t.Fatalf("call code=%v response=%q, want %v", status.Code(err), responseError, want)
}
if operation == "create" && !denied {
if c.stored(t, p) != "created" {
t.Fatal("allowed create was not stored")
}
} else if operation == "delete" && denied {
if c.stored(t, p) != "seed" {
t.Fatal("refused delete changed the entry")
}
} else if _, findErr := c.store.FindEntry(ctx, p); findErr != filer_pb.ErrNotFound {
t.Fatalf("entry lookup error=%v, want absent", findErr)
}
})
}
}
}
func TestRequireModeUnscopedConditionalUpdateForwardsCaller(t *testing.T) {
c, key := newPeerFilers(t)
p := c.keyOwnedBy(t, c.addrB, c.addrB)
expected := c.seed(t, p)
dir, _ := p.DirAndName()
entry := proto.Clone(expected).(*filer_pb.Entry)
entry.Extended = map[string][]byte{"v": []byte("forwarded")}
client := peerClient(t, c, c.addrA, peerAdminToken(key))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
Directory: dir,
Entry: entry,
ExpectedExtended: map[string][]byte{"v": []byte("seed")},
})
if err != nil {
t.Fatalf("unscoped conditional update: %v", err)
}
if got := c.stored(t, p); got != "forwarded" {
t.Fatalf("forwarded update stored %q, want forwarded", got)
}
}
func TestRequireModeScopedConditionalUpdateRefusesRemoteOwner(t *testing.T) {
c, key := newPeerFilers(t)
p := c.keyOwnedBy(t, c.addrB, c.addrB)
expected := c.seed(t, p)
dir, _ := p.DirAndName()
entry := proto.Clone(expected).(*filer_pb.Entry)
entry.Extended = map[string][]byte{"v": []byte("must-refuse")}
client := peerClient(t, c, c.addrA, peerScopedWriteToken(key))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
Directory: dir,
Entry: entry,
ExpectedExtended: map[string][]byte{"v": []byte("seed")},
})
if status.Code(err) != codes.PermissionDenied {
t.Fatalf("scoped remote update error=%v, want PermissionDenied", err)
}
if got := c.stored(t, p); got != "seed" {
t.Fatalf("refused update changed the entry to %q", got)
}
if updates, _ := c.callsB.counts(); updates != 0 {
t.Fatalf("refused update reached the owner %d time(s)", updates)
}
}
func TestRequireModeScopedConditionalUpdateAllowsLocalOwner(t *testing.T) {
c, key := newPeerFilers(t)
p := c.keyOwnedBy(t, c.addrA, c.addrA)
expected := c.seed(t, p)
dir, _ := p.DirAndName()
entry := proto.Clone(expected).(*filer_pb.Entry)
entry.Extended = map[string][]byte{"v": []byte("local")}
client := peerClient(t, c, c.addrA, peerScopedWriteToken(key))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := client.UpdateEntry(ctx, &filer_pb.UpdateEntryRequest{
Directory: dir,
Entry: entry,
ExpectedExtended: map[string][]byte{"v": []byte("seed")},
}); err != nil {
t.Fatalf("scoped local update: %v", err)
}
if got := c.stored(t, p); got != "local" {
t.Fatalf("local update stored %q, want local", got)
}
}
func TestRequireModeUnscopedPosixForwardCarriesCaller(t *testing.T) {
c, key := newPeerFilers(t)
c.fsA.posixLocks = posixlock.NewManager()
c.fsB.posixLocks = posixlock.NewManager()
lockKey := peerPosixKey(c, c.addrB)
if lockKey == "" {
t.Fatal("no POSIX key owned by B")
}
client := peerClient(t, c, c.addrA, peerAdminToken(key))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := client.PosixLock(ctx, &filer_pb.PosixLockRequest{
Key: lockKey,
Op: filer_pb.PosixLockOp_TRY_LOCK,
Lock: &filer_pb.PosixLockRange{Start: 0, End: 99, Type: posixlock.Write, Sid: 1, Owner: 1, Pid: 1},
})
if err != nil || !resp.GetGranted() {
t.Fatalf("unscoped forwarded POSIX lock: err=%v granted=%v", err, resp.GetGranted())
}
}
func TestRequireModeScopedPosixForwardRefusesBeforeOwner(t *testing.T) {
c, key := newPeerFilers(t)
c.fsA.posixLocks = posixlock.NewManager()
c.fsB.posixLocks = posixlock.NewManager()
lockKey := peerPosixKey(c, c.addrB)
if lockKey == "" {
t.Fatal("no POSIX key owned by B")
}
client := peerClient(t, c, c.addrA, peerScopedWriteToken(key))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := client.PosixLock(ctx, &filer_pb.PosixLockRequest{
Key: lockKey,
Op: filer_pb.PosixLockOp_TRY_LOCK,
Lock: &filer_pb.PosixLockRange{Start: 0, End: 99, Type: posixlock.Write, Sid: 2, Owner: 2, Pid: 2},
})
if status.Code(err) != codes.PermissionDenied {
t.Fatalf("scoped forwarded POSIX lock error=%v response=%v, want PermissionDenied", err, resp)
}
if locks := c.fsB.posixLocks.Snapshot()[lockKey]; len(locks) != 0 {
t.Fatal("scoped POSIX refusal reached the owner")
}
}
func TestRequireModeUnscopedDistributedLockAndUnlockForwardCaller(t *testing.T) {
c, key := newPeerFilers(t)
lockKey := peerLockKey(c, c.addrB)
if lockKey == "" {
t.Fatal("no DLM key owned by B")
}
client := peerClient(t, c, c.addrA, peerAdminToken(key))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
locked, err := client.DistributedLock(ctx, &filer_pb.LockRequest{
Name: lockKey,
SecondsToLock: 5,
Owner: string(c.addrA),
})
if err != nil || locked.GetError() != "" || locked.GetRenewToken() == "" {
t.Fatalf("unscoped forwarded DLM lock: err=%v response=%v", err, locked)
}
if _, err := client.DistributedUnlock(ctx, &filer_pb.UnlockRequest{Name: lockKey, RenewToken: locked.GetRenewToken()}); err != nil {
t.Fatalf("unscoped forwarded DLM unlock: %v", err)
}
}
func TestWithCallerAuthContextLeavesTokenlessCallsTokenless(t *testing.T) {
if got := withCallerAuthContext(context.Background()); got != context.Background() {
t.Fatal("tokenless context was replaced")
}
if got := withHTTPBearerContext(context.Background(), ""); got != context.Background() {
t.Fatal("empty HTTP bearer context was replaced")
}
}
+119
View File
@@ -0,0 +1,119 @@
package weed_server
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc/metadata"
)
func TestWithCallerAuthContextCopiesOnlyIncomingAuthorization(t *testing.T) {
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
"authorization", "Bearer caller-token",
"x-unrelated", "must-not-forward",
))
ctx = metadata.AppendToOutgoingContext(ctx, "x-amz-request-id", "request-id")
forwarded := withCallerAuthContext(ctx)
outgoing, ok := metadata.FromOutgoingContext(forwarded)
if !ok {
t.Fatal("caller context lost outgoing metadata")
}
if got := outgoing.Get("authorization"); len(got) != 1 || got[0] != "Bearer caller-token" {
t.Fatalf("authorization = %v, want the caller bearer only", got)
}
if got := outgoing.Get("x-amz-request-id"); len(got) != 1 || got[0] != "request-id" {
t.Fatalf("request id = %v, want the existing outgoing metadata preserved", got)
}
if got := outgoing.Get("x-unrelated"); len(got) != 0 {
t.Fatalf("incoming unrelated metadata leaked to the peer: %v", got)
}
}
func TestWithCallerAuthContextReplacesExistingAuthorization(t *testing.T) {
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "Bearer caller-token"))
ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer stale-token")
outgoing, ok := metadata.FromOutgoingContext(withCallerAuthContext(ctx))
if !ok {
t.Fatal("caller context lost outgoing metadata")
}
if got := outgoing.Get("authorization"); len(got) != 1 || got[0] != "Bearer caller-token" {
t.Fatalf("authorization = %v, want exactly the caller bearer", got)
}
}
func TestWithCallerAuthContextRemovesStaleAuthorizationWhenCallerIsTokenless(t *testing.T) {
ctx := metadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer stale-token")
outgoing, ok := metadata.FromOutgoingContext(withCallerAuthContext(ctx))
if !ok || len(outgoing.Get("authorization")) != 0 {
t.Fatalf("tokenless caller retained stale authorization: %v", outgoing)
}
}
func TestWithHTTPBearerContext(t *testing.T) {
ctx := withHTTPBearerContext(context.Background(), security.EncodedJwt("http-token"))
outgoing, ok := metadata.FromOutgoingContext(ctx)
if !ok {
t.Fatal("HTTP bearer context has no outgoing metadata")
}
if got := outgoing.Get("authorization"); len(got) != 1 || got[0] != "Bearer http-token" {
t.Fatalf("authorization = %v, want the HTTP bearer", got)
}
ctx = metadata.AppendToOutgoingContext(context.Background(), "authorization", "Bearer stale-token")
if outgoing, ok := metadata.FromOutgoingContext(withHTTPBearerContext(ctx, "")); !ok || len(outgoing.Get("authorization")) != 0 {
t.Fatalf("empty HTTP bearer retained stale authorization: %v", outgoing)
}
}
func TestWithHTTPForwardAuthContextFollowsRequireMode(t *testing.T) {
r := httptest.NewRequest(http.MethodPut, "http://filer.test/file?op=append", nil)
r.Header.Set("Authorization", "Bearer http-token")
base, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
base = metadata.AppendToOutgoingContext(base, "x-request-id", "request-id", "authorization", "Bearer stale-token")
for _, tc := range []struct {
name string
requireToken bool
wantAuth string
}{
{name: "compatibility mode", wantAuth: ""},
{name: "require mode", requireToken: true, wantAuth: "Bearer http-token"},
} {
t.Run(tc.name, func(t *testing.T) {
fs := &FilerServer{}
fs.grpcScopeSettings.Store(&grpcScopeSettings{requireToken: tc.requireToken})
forwarded := fs.withHTTPForwardAuthContext(base, r)
deadline, ok := forwarded.Deadline()
if !ok {
t.Fatal("forwarded context lost its deadline")
}
wantDeadline, _ := base.Deadline()
if !deadline.Equal(wantDeadline) {
t.Fatalf("deadline = %v, want %v", deadline, wantDeadline)
}
outgoing, ok := metadata.FromOutgoingContext(forwarded)
if !ok {
t.Fatal("forwarded context lost outgoing metadata")
}
gotAuth := outgoing.Get("authorization")
if tc.wantAuth == "" {
if len(gotAuth) != 0 {
t.Fatalf("authorization = %v, want no values", gotAuth)
}
} else if len(gotAuth) != 1 || gotAuth[0] != tc.wantAuth {
t.Fatalf("authorization = %v, want exactly %q", gotAuth, tc.wantAuth)
}
if got := outgoing.Get("x-request-id"); len(got) != 1 || got[0] != "request-id" {
t.Fatalf("request id = %v, want request-id", got)
}
})
}
}
+40
View File
@@ -0,0 +1,40 @@
package weed_server
import (
"context"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/security"
)
// peerContext authenticates an RPC the filer makes on its own behalf. Resolve
// the key when sending each attempt, so pooled connections do not retain either
// a token or the authority of a previous caller. Sign with the key filesystem
// gRPC verifies, so a dedicated grpc_key works alone and peers without the
// shared-key admin fallback still accept the token.
func (fs *FilerServer) peerContext(ctx context.Context) context.Context {
var key security.SigningKey
if fs.filerGuard != nil {
key, _ = fs.grpcScopeVerificationKeys()
}
return security.WithFilerPeerCredentials(ctx, key)
}
// peerSubscriptionContext prefers the shared key for metadata subscriptions:
// older filers verify subscription admin tokens only with that key.
func (fs *FilerServer) peerSubscriptionContext(ctx context.Context) context.Context {
var key security.SigningKey
if fs.filerGuard != nil {
key = fs.filerGuard.SigningKey()
}
if len(key) == 0 {
return fs.peerContext(ctx)
}
return security.WithFilerPeerCredentials(ctx, key)
}
func (fs *FilerServer) newLockClient() *cluster.LockClient {
client := cluster.NewLockClient(fs.grpcDialOption, fs.option.Host)
client.RequestContext = fs.peerContext
return client
}
+273
View File
@@ -0,0 +1,273 @@
package weed_server
import (
"context"
"crypto/rand"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func newPeerFilers(t *testing.T) (*twoFilers, security.SigningKey) {
t.Helper()
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
t.Fatal(err)
}
c := newTwoFilers(t, func(fs *FilerServer) {
fs.filerGuard = security.NewGuard(nil, string(key), 10, "", 0, "", "")
fs.filer.PeerContext = fs.peerContext
fs.grpcScope = newFilerGrpcScope(scopeConfig{
signingKey: fs.filerGuard.SigningKey,
verificationKeys: func() (security.SigningKey, security.SigningKey) { return fs.filerGuard.VerificationKeys(true) },
requireToken: func() bool { return true },
}, fs)
})
sharedWriteRing(c)
return c, key
}
// A pooled connection is shared by address, so each caller must supply its own
// authority even when the previous caller reached the same filer as an admin.
func TestPeerAdminTokenConnectionReuse(t *testing.T) {
for _, adminFirst := range []bool{false, true} {
name := "tokenless first"
if adminFirst {
name = "admin first"
}
t.Run(name, func(t *testing.T) {
c, _ := newPeerFilers(t)
c.seed(t, util.FullPath("/cached"))
var firstConn *grpc.ClientConn
for _, authenticated := range []bool{adminFirst, !adminFirst, adminFirst} {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err := pb.WithGrpcClient(ctx, false, 0, func(conn *grpc.ClientConn) error {
if firstConn == nil {
firstConn = conn
} else if firstConn != conn {
t.Error("test did not reuse the real cached connection")
}
callCtx := ctx
if authenticated {
callCtx = c.fsA.peerContext(callCtx)
}
_, err := filer_pb.NewSeaweedFilerClient(conn).LookupDirectoryEntry(callCtx, &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "cached"})
return err
}, c.addrB.ToGrpcAddress(), false, c.fsA.grpcDialOption)
cancel()
want := codes.Unauthenticated
if authenticated {
want = codes.OK
}
if status.Code(err) != want {
t.Fatalf("authenticated=%v: code=%v, want %v", authenticated, status.Code(err), want)
}
}
})
}
}
func TestPeerAdminTokenLockAndReplication(t *testing.T) {
c, _ := newPeerFilers(t)
// Route every internal acquisition to B, including the client's seed A.
setRing(c.fsA, 0, []pb.ServerAddress{c.addrB})
setRing(c.fsB, 0, []pb.ServerAddress{c.addrB})
client := c.fsA.newLockClient()
client.SetRing([]pb.ServerAddress{c.addrB}, 1)
lock := client.NewBlockingLongLivedLock("internal-lock", string(c.addrA), 0)
if lock == nil {
t.Fatal("filer-owned lock acquisition failed under require-mode")
}
if err := lock.AttemptToLock(5 * time.Second); err != nil {
t.Fatalf("filer-owned lock renewal failed: %v", err)
}
if err := lock.Stop(); err != nil {
t.Fatalf("filer-owned unlock failed: %v", err)
}
if _, found := c.fsB.filer.Dlm.GetLock("internal-lock"); found {
t.Fatal("unlock left a lock")
}
c.fsA.SetupDlmReplication()
c.fsA.filer.Dlm.ReplicateFn(c.addrB, "replicated", time.Now().Add(time.Minute).UnixNano(), "test-lease", "", "test-owner", 7, 1, false)
backup, found := c.fsB.filer.Dlm.GetLock("replicated")
if !found || backup.Owner != "test-owner" || !backup.IsBackup || backup.Generation != 7 || backup.Seq != 1 {
t.Fatal("replication did not store the owner's backup lock")
}
}
func TestPeerAdminTokenReload(t *testing.T) {
c, oldKey := newPeerFilers(t)
c.seed(t, util.FullPath("/reload"))
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
oldCtx := c.fsA.peerContext(ctx)
var firstConn *grpc.ClientConn
lookup := func(callCtx context.Context, want codes.Code) {
t.Helper()
err := pb.WithGrpcClient(callCtx, false, 0, func(conn *grpc.ClientConn) error {
if firstConn == nil {
firstConn = conn
} else if firstConn != conn {
t.Fatal("key reload replaced the pooled connection")
}
_, err := filer_pb.NewSeaweedFilerClient(conn).LookupDirectoryEntry(callCtx, &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "reload"})
return err
}, c.addrB.ToGrpcAddress(), false, c.fsA.grpcDialOption)
if status.Code(err) != want {
t.Fatalf("lookup code=%v, want %v", status.Code(err), want)
}
}
lookup(oldCtx, codes.OK)
newKey := make([]byte, 32)
if _, err := rand.Read(newKey); err != nil {
t.Fatal(err)
}
c.fsB.filerGuard.UpdateSigningKeys(string(newKey), 10, "", 0, string(oldKey), "")
lookup(oldCtx, codes.OK)
c.fsA.filerGuard.UpdateSigningKeys(string(newKey), 10, "", 0, "", "")
lookup(c.fsA.peerContext(ctx), codes.OK)
c.fsB.filerGuard.UpdateSigningKeys(string(newKey), 10, "", 0, "", "")
lookup(oldCtx, codes.Unauthenticated)
lookup(c.fsA.peerContext(ctx), codes.OK)
c.fsA.filerGuard.UpdateSigningKeys("", 10, "", 0, "", "")
cleared := c.fsA.peerContext(oldCtx)
md, _ := metadata.FromOutgoingContext(cleared)
if len(md.Get("authorization")) != 0 {
t.Fatal("key removal retained stale peer authorization")
}
lookup(cleared, codes.Unauthenticated)
}
func TestPeerAdminTokenLockTransferAndLookup(t *testing.T) {
c, key := newPeerFilers(t)
setRing(c.fsA, 0, []pb.ServerAddress{c.addrA})
c.fsA.filer.Dlm.InsertLock("moved-lock", time.Now().Add(time.Minute).UnixNano(), "test-lease", "", "test-owner", 4, 2)
setRing(c.fsA, 0, []pb.ServerAddress{c.addrB})
setRing(c.fsB, 0, []pb.ServerAddress{c.addrB})
c.fsA.OnDlmChangeSnapshot([]pb.ServerAddress{c.addrB})
lock, found := c.fsB.filer.Dlm.GetLock("moved-lock")
if !found || lock.Owner != "test-owner" || lock.IsBackup || lock.Generation != 4 || lock.Seq != 2 {
t.Fatal("transfer did not preserve the primary lock")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// The owner trusts the caller's key, not A's newly rotated peer key. A
// caller-owned lookup must retain that caller's authority across the hop.
c.fsA.grpcScope.cfg.verificationKeys = func() (security.SigningKey, security.SigningKey) { return key, nil }
otherKey := make([]byte, 32)
if _, err := rand.Read(otherKey); err != nil {
t.Fatal(err)
}
c.fsA.filerGuard.UpdateSigningKeys(string(otherKey), 10, "", 0, "", "")
client := peerClient(t, c, c.addrA, peerAdminToken(key))
response, err := client.FindLockOwner(ctx, &filer_pb.FindLockOwnerRequest{Name: "moved-lock"})
if err != nil || response.GetOwner() != "test-owner" {
t.Fatalf("peer owner lookup failed: %v", err)
}
}
func TestPeerAdminTokenWithDedicatedGrpcKey(t *testing.T) {
c, httpKey := newPeerFilers(t)
c.seed(t, util.FullPath("/realm"))
grpcKey := make([]byte, 32)
if _, err := rand.Read(grpcKey); err != nil {
t.Fatal(err)
}
c.fsB.grpcScope.cfg.verificationKeys = func() (security.SigningKey, security.SigningKey) { return grpcKey, nil }
c.fsB.grpcScope.cfg.adminKeys = func() (security.SigningKey, security.SigningKey) { return c.fsB.filerGuard.VerificationKeys(true) }
for _, tc := range []struct {
name string
key security.SigningKey
admin bool
want codes.Code
}{
{"HTTP admin", httpKey, true, codes.OK},
{"HTTP scoped", httpKey, false, codes.Unauthenticated},
{"gRPC scoped", grpcKey, false, codes.OK},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if tc.admin {
ctx = c.fsA.peerContext(ctx)
} else {
token := security.GenJwtForFilerScope(tc.key, time.Minute, "test-caller", []string{"/"}, nil)
ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs("authorization", "Bearer "+string(token)))
}
err := pb.WithFilerClient(false, 0, c.addrB, c.fsA.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "realm"})
return err
})
if status.Code(err) != tc.want {
t.Fatalf("lookup code=%v, want %v", status.Code(err), tc.want)
}
})
}
}
// Filer-owned calls sign with the key filesystem gRPC verifies: a dedicated
// grpc_key alone must authenticate them in require-mode, and a peer without the
// shared-key admin fallback must accept them when both keys are configured.
func TestPeerAdminTokenSignedWithGrpcVerificationKey(t *testing.T) {
for _, tc := range []struct {
name string
sharedKey bool
requireMode bool
}{
{"gRPC key only in require-mode", false, true},
{"peer without admin fallback", true, false},
} {
t.Run(tc.name, func(t *testing.T) {
c, httpKey := newPeerFilers(t)
c.seed(t, util.FullPath("/realm"))
grpcKey := make([]byte, 32)
if _, err := rand.Read(grpcKey); err != nil {
t.Fatal(err)
}
for _, fs := range []*FilerServer{c.fsA, c.fsB} {
if !tc.sharedKey {
fs.filerGuard.UpdateSigningKeys("", 10, "", 0, "", "")
}
fs.grpcScopeSettings.Store(&grpcScopeSettings{key: grpcKey, requireToken: tc.requireMode})
fs.grpcScope.cfg.verificationKeys = fs.grpcScopeVerificationKeys
fs.grpcScope.cfg.requireToken = func() bool { return tc.requireMode }
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := pb.WithFilerClient(false, 0, c.addrB, c.fsA.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.LookupDirectoryEntry(c.fsA.peerContext(ctx), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "realm"})
return err
})
if err != nil {
t.Fatalf("filer-owned lookup: %v", err)
}
md, _ := metadata.FromOutgoingContext(c.fsA.peerSubscriptionContext(ctx))
auth := md.Get("authorization")
if len(auth) != 1 {
t.Fatalf("subscription authorization=%q, want one bearer", auth)
}
subscriptionKey := grpcKey
if tc.sharedKey {
subscriptionKey = httpKey
}
if !security.IsFilerAdminToken(subscriptionKey, security.EncodedJwt(strings.TrimPrefix(auth[0], security.BearerPrefix))) {
t.Fatal("subscription bearer is not an admin token for the key its verifier accepts")
}
v := util.GetViper()
v.Set("jwt.filer_signing.subscribe.key", subscriptionTokenKey)
t.Cleanup(func() { v.Set("jwt.filer_signing.subscribe.key", "") })
if scope, err := c.fsB.metadataSubscriptionScope(metadata.NewIncomingContext(ctx, md), security.MethodSubscribeLocalMetadata); err != nil || scope != nil {
t.Fatalf("peer subscription with a subscribe key set: scope=%+v err=%v, want the full stream", scope, err)
}
})
}
}
@@ -0,0 +1,105 @@
package weed_server
import (
"context"
"slices"
"strings"
"testing"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const pingForwardingKey = "ping-forwarding-test-key"
func newPingFilers(t *testing.T, requireToken bool) (*twoFilers, security.SigningKey) {
t.Helper()
c := newTwoFilers(t, func(fs *FilerServer) {
fs.filerGuard = security.NewGuard(nil, pingForwardingKey, 60, "", 0, "", "")
fs.grpcScope = newFilerGrpcScope(scopeConfig{
signingKey: fs.filerGuard.SigningKey,
verificationKeys: func() (security.SigningKey, security.SigningKey) { return fs.filerGuard.VerificationKeys(true) },
requireToken: func() bool { return requireToken },
}, fs)
})
// The fixture does not run the normal master peer subscription. Treat B as
// a known peer so A's real target gate admits the probe without starting a
// subscription goroutine solely for this test.
ma := filer.NewMetaAggregator(c.fsA.filer, c.addrB, nil)
c.fsA.filer.MetaAggregator = ma
t.Cleanup(ma.Shutdown)
return c, security.SigningKey(pingForwardingKey)
}
func TestFilerPingForwardsCallerBearerToRequireModePeer(t *testing.T) {
c, key := newPingFilers(t, true)
caller := peerAdminToken(key)
client := peerClient(t, c, c.addrA, caller)
_, err := client.Ping(context.Background(), &filer_pb.PingRequest{Target: string(c.addrB), TargetType: cluster.FilerType})
if err != nil {
t.Fatalf("target filer Ping: %v", err)
}
assertForwardedPingBearer(t, c.callsB, caller)
}
func assertForwardedPingBearer(t *testing.T, calls *receivedUpdates, caller string) {
t.Helper()
calls.mu.Lock()
defer calls.mu.Unlock()
if len(calls.pingAuthorizations) != 1 {
t.Fatalf("receiving filer saw %d Ping calls, want one", len(calls.pingAuthorizations))
}
if !slices.Equal(calls.pingAuthorizations[0], []string{"Bearer " + caller}) {
t.Fatal("receiving filer did not get exactly the caller's bearer")
}
}
func TestFilerPingRejectsTokenlessCallerInRequireMode(t *testing.T) {
c, _ := newPingFilers(t, true)
client := peerClient(t, c, c.addrA, "")
_, err := client.Ping(context.Background(), &filer_pb.PingRequest{Target: string(c.addrB), TargetType: cluster.FilerType})
if status.Code(err) != codes.Unauthenticated {
t.Fatalf("tokenless target Ping error=%v, want Unauthenticated", err)
}
}
func TestFilerPingDoesNotMintPeerAdminForTokenlessCaller(t *testing.T) {
c, _ := newPingFilers(t, false)
c.fsB.grpcScope.cfg.requireToken = func() bool { return true }
client := peerClient(t, c, c.addrA, "")
_, err := client.Ping(context.Background(), &filer_pb.PingRequest{Target: string(c.addrB), TargetType: cluster.FilerType})
if err == nil || !strings.Contains(err.Error(), "filer: gRPC token authentication is required") {
t.Fatalf("tokenless target Ping against require-mode peer error=%v, want remote Unauthenticated", err)
}
}
func TestFilerPingPreservesTokenlessCompatibilityWhenRequireModeOff(t *testing.T) {
c, _ := newPingFilers(t, false)
client := peerClient(t, c, c.addrA, "")
if _, err := client.Ping(context.Background(), &filer_pb.PingRequest{Target: string(c.addrB), TargetType: cluster.FilerType}); err != nil {
t.Fatalf("tokenless target Ping in compatibility mode: %v", err)
}
}
func TestFilerPingReplacesStaleOutgoingAuthorization(t *testing.T) {
c, key := newPingFilers(t, true)
caller := peerAdminToken(key)
stale := peerAdminToken(security.SigningKey("stale-ping-key"))
ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "Bearer "+caller))
ctx = metadata.NewOutgoingContext(ctx, metadata.Pairs("authorization", "Bearer "+stale))
if _, err := c.fsA.Ping(ctx, &filer_pb.PingRequest{Target: string(c.addrB), TargetType: cluster.FilerType}); err != nil {
t.Fatalf("target filer Ping with stale outgoing authorization: %v", err)
}
assertForwardedPingBearer(t, c.callsB, caller)
}
+33
View File
@@ -60,7 +60,9 @@ type scopeBackend interface {
type scopeConfig struct {
signingKey func() security.SigningKey
verificationKeys func() (security.SigningKey, security.SigningKey)
adminKeys func() (security.SigningKey, security.SigningKey)
subscriptionScope func(context.Context, string) (*security.MetadataSubscriptionScope, error)
requireToken func() bool
leeway func() time.Duration
assignLifetime func() time.Duration
}
@@ -162,6 +164,22 @@ func (s *filerGrpcScope) verificationKeys() (security.SigningKey, security.Signi
return nil, nil
}
// isFilerAdminTokenWithLeeway applies the scope verifier's clock policy to the
// shared filer-admin fallback. Keep the claim-shape checks here instead of
// changing security.IsFilerAdminToken, whose callers intentionally use strict
// JWT time validation.
func isFilerAdminTokenWithLeeway(signingKey, previousKey security.SigningKey, token security.EncodedJwt, leeway time.Duration) bool {
if len(signingKey) == 0 || token == "" {
return false
}
claims := &security.SeaweedFilerAdminClaims{}
parsed, err := security.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
}
func (s *filerGrpcScope) proven(sc *scope, chunkAuth map[string]string, fid, collection string) bool {
raw := chunkAuth[fid]
if raw == "" {
@@ -190,8 +208,12 @@ func (s *filerGrpcScope) proofVerifier(ctx context.Context, sc *scope, chunkAuth
// resolve authenticates the call. It returns (nil, nil) for an unscoped call,
// a *scope for a scoped token, and an error that refuses the call.
func (s *filerGrpcScope) resolve(ctx context.Context) (*scope, error) {
requireToken := s.cfg.requireToken != nil && s.cfg.requireToken()
key, previous := s.verificationKeys()
if len(key) == 0 {
if requireToken {
return nil, status.Error(codes.Unauthenticated, "filer: gRPC token authentication is required")
}
return nil, nil
}
raw, authErr := bearerFromMetadata(ctx)
@@ -199,6 +221,9 @@ func (s *filerGrpcScope) resolve(ctx context.Context) (*scope, error) {
return nil, authErr
}
if raw == "" {
if requireToken {
return nil, status.Error(codes.Unauthenticated, "filer: gRPC token authentication is required")
}
return nil, nil
}
leeway := time.Duration(0)
@@ -210,6 +235,14 @@ func (s *filerGrpcScope) resolve(ctx context.Context) (*scope, error) {
}
claims := &security.SeaweedFilerClaims{}
token, err := security.DecodeJwtWith(key, previous, security.EncodedJwt(raw), claims, leeway)
// Filer-owned RPCs use the shared admin key even when scoped callers have
// a dedicated gRPC key. Only an unscoped admin token can cross that boundary.
if (err != nil || token == nil || !token.Valid) && s.cfg.adminKeys != nil {
adminKey, previousAdminKey := s.cfg.adminKeys()
if isFilerAdminTokenWithLeeway(adminKey, previousAdminKey, security.EncodedJwt(raw), leeway) {
return nil, nil
}
}
if errors.Is(err, jwt.ErrTokenExpired) {
// The claims are parsed before validation, so the id names the holder.
glog.V(1).Infof("filer grpc: token %s (%s) expired", claims.ID, scopePeer(ctx))
@@ -0,0 +1,164 @@
package weed_server
import (
"context"
"testing"
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/spf13/viper"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const (
adminLeewayGrpcKey = "dedicated-grpc-key"
adminLeewayHttpKey = "shared-http-admin-key"
)
func signAdminLeewayToken(t *testing.T, claims security.SeaweedFilerAdminClaims) security.EncodedJwt {
t.Helper()
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(adminLeewayHttpKey))
if err != nil {
t.Fatalf("sign admin token: %v", err)
}
return security.EncodedJwt(token)
}
func adminLeewayContext(token security.EncodedJwt) context.Context {
return metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "Bearer "+string(token)))
}
func adminLeewayScope(leeway time.Duration) *filerGrpcScope {
fs := &FilerServer{}
config := util.NewViperProxy(viper.New())
config.Set("jwt.filer_signing.clock_leeway_seconds", int(leeway/time.Second))
fs.loadGrpcScopeConfig(config)
return newFilerGrpcScope(scopeConfig{
verificationKeys: func() (security.SigningKey, security.SigningKey) {
return security.SigningKey(adminLeewayGrpcKey), nil
},
adminKeys: func() (security.SigningKey, security.SigningKey) {
return security.SigningKey(adminLeewayHttpKey), nil
},
leeway: func() time.Duration { return fs.grpcScopeSettings.Load().leeway },
}, newScopeFakeFiler())
}
func TestFilerGrpcAdminFallbackHonorsClockLeeway(t *testing.T) {
now := time.Now()
for _, tc := range []struct {
name string
claims security.SeaweedFilerAdminClaims
leeway time.Duration
wantErr codes.Code
}{
{
name: "expired within leeway",
claims: security.SeaweedFilerAdminClaims{RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(-5 * time.Second)),
}},
leeway: 10 * time.Second,
wantErr: codes.OK,
},
{
name: "expired with zero leeway",
claims: security.SeaweedFilerAdminClaims{RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(-5 * time.Second)),
}},
wantErr: codes.Unauthenticated,
},
{
name: "expired beyond leeway",
claims: security.SeaweedFilerAdminClaims{RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(-30 * time.Second)),
}},
leeway: 10 * time.Second,
wantErr: codes.Unauthenticated,
},
{
name: "not before within leeway",
claims: security.SeaweedFilerAdminClaims{RegisteredClaims: jwt.RegisteredClaims{
NotBefore: jwt.NewNumericDate(now.Add(5 * time.Second)),
ExpiresAt: jwt.NewNumericDate(now.Add(time.Minute)),
}},
leeway: 10 * time.Second,
wantErr: codes.OK,
},
{
name: "not before beyond leeway",
claims: security.SeaweedFilerAdminClaims{RegisteredClaims: jwt.RegisteredClaims{
NotBefore: jwt.NewNumericDate(now.Add(30 * time.Second)),
ExpiresAt: jwt.NewNumericDate(now.Add(time.Minute)),
}},
leeway: 10 * time.Second,
wantErr: codes.Unauthenticated,
},
} {
t.Run(tc.name, func(t *testing.T) {
for _, requireToken := range []bool{false, true} {
scope := adminLeewayScope(tc.leeway)
scope.cfg.requireToken = func() bool { return requireToken }
_, err := scope.resolve(adminLeewayContext(signAdminLeewayToken(t, tc.claims)))
if got := status.Code(err); got != tc.wantErr {
t.Fatalf("require=%v: resolve code=%v, want %v (err=%v)", requireToken, got, tc.wantErr, err)
}
}
})
}
}
func TestFilerGrpcAdminFallbackRejectsScopedAndSessionClaims(t *testing.T) {
now := time.Now().Add(time.Minute)
for _, tc := range []struct {
name string
claims security.SeaweedFilerAdminClaims
}{
{
name: "session",
claims: security.SeaweedFilerAdminClaims{
SessionId: "session-id",
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now),
},
},
},
{
name: "allowed prefixes",
claims: security.SeaweedFilerAdminClaims{
AllowedPrefixes: []string{"/buckets/test"},
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now),
},
},
},
{
name: "allowed methods",
claims: security.SeaweedFilerAdminClaims{
AllowedMethods: []string{"LookupDirectoryEntry"},
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now),
},
},
},
{
name: "read prefixes",
claims: security.SeaweedFilerAdminClaims{
ReadPrefixes: []string{"/buckets/test"},
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now),
},
},
},
} {
t.Run(tc.name, func(t *testing.T) {
_, err := adminLeewayScope(time.Minute).resolve(adminLeewayContext(signAdminLeewayToken(t, tc.claims)))
if got := status.Code(err); got != codes.Unauthenticated {
t.Fatalf("resolve code=%v, want Unauthenticated (err=%v)", got, err)
}
})
}
}
+10 -1
View File
@@ -6,6 +6,7 @@ import (
"time"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"google.golang.org/grpc"
@@ -34,9 +35,17 @@ func TestScopeMethodOnlyTokenAllowsListedMethodWithoutPathGrant(t *testing.T) {
c := h.client(methodScopedToken(t, "alice", nil, []string{"Ping"}))
expectScopeForwarded(t, h, "Ping", "method-only Ping", func() error {
_, err := c.Ping(scopeCtx(t), &filer_pb.PingRequest{})
_, err := c.Ping(scopeCtx(t), &filer_pb.PingRequest{Target: "127.0.0.1:1", TargetType: cluster.FilerType})
return err
})
pingCalls := h.fake.received("Ping")
if len(pingCalls) != 1 {
t.Fatalf("method-only Ping reached handler %d times, want 1", len(pingCalls))
}
pingReq, ok := pingCalls[0].(*filer_pb.PingRequest)
if !ok || pingReq.GetTarget() != "" || pingReq.GetTargetType() != "" {
t.Fatalf("scoped Ping forwarded target %q/%q, want empty target", pingReq.GetTarget(), pingReq.GetTargetType())
}
expectScopeDenied(t, h, "LookupDirectoryEntry", "method-only lookup without a path grant", func() error {
_, err := c.LookupDirectoryEntry(scopeCtx(t), &filer_pb.LookupDirectoryEntryRequest{Directory: aliceWS, Name: "file"})
return err
@@ -0,0 +1,222 @@
package weed_server
import (
"context"
"crypto/tls"
"crypto/x509"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/spf13/viper"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
)
func tokenlessVerifiedPeerContext() context.Context {
return peer.NewContext(context.Background(), &peer.Peer{
AuthInfo: credentials.TLSInfo{State: tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{}}}},
})
}
func TestFilerGrpcRequireTokenConfigDefaultsOffAndReloads(t *testing.T) {
fs := &FilerServer{filerGuard: security.NewGuard(nil, "http-key", 10, "", 0, "", "")}
config := util.NewViperProxy(viper.New())
config.Set("jwt.filer_signing.grpc_key", scopeTestKey)
fs.loadGrpcScopeConfig(config)
if got := fs.grpcScopeSettings.Load().requireToken; got {
t.Fatal("grpc_require_token defaulted on")
}
config.Set("jwt.filer_signing.grpc_require_token", true)
fs.loadGrpcScopeConfig(config)
if got := fs.grpcScopeSettings.Load().requireToken; !got {
t.Fatal("grpc_require_token reload did not enable require-mode")
}
}
func TestFilerGrpcRequireTokenRefusesTokenlessUnaryAndStreamingCalls(t *testing.T) {
h := newScopeHarness(t)
h.scope.cfg.requireToken = func() bool { return true }
c := h.client("")
beforeUnary := len(h.fake.received("LookupDirectoryEntry"))
_, err := c.LookupDirectoryEntry(scopeCtx(t), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "file"})
if status.Code(err) != codes.Unauthenticated {
t.Fatalf("tokenless unary error=%v, want Unauthenticated", err)
}
if got := len(h.fake.received("LookupDirectoryEntry")); got != beforeUnary {
t.Fatalf("tokenless unary reached handler: %d calls before=%d", got, beforeUnary)
}
beforeStream := len(h.fake.received("ListEntries"))
stream, err := c.ListEntries(scopeCtx(t), &filer_pb.ListEntriesRequest{Directory: "/"})
if err == nil {
_, err = stream.Recv()
}
if status.Code(err) != codes.Unauthenticated {
t.Fatalf("tokenless stream error=%v, want Unauthenticated", err)
}
if got := len(h.fake.received("ListEntries")); got != beforeStream {
t.Fatalf("tokenless stream reached handler: %d calls before=%d", got, beforeStream)
}
}
func TestFilerGrpcRequireTokenRefusesTokenlessVerifiedMTLSUnaryAndStreaming(t *testing.T) {
scope := newFilerGrpcScope(scopeConfig{
verificationKeys: func() (security.SigningKey, security.SigningKey) {
return security.SigningKey(scopeTestKey), nil
},
requireToken: func() bool { return true },
}, newScopeFakeFiler())
ctx := tokenlessVerifiedPeerContext()
calledUnary := false
_, err := scope.unary(ctx, &filer_pb.PingRequest{}, &grpc.UnaryServerInfo{
FullMethod: filer_pb.SeaweedFiler_Ping_FullMethodName,
}, func(context.Context, any) (any, error) {
calledUnary = true
return &filer_pb.PingResponse{}, nil
})
if status.Code(err) != codes.Unauthenticated || calledUnary {
t.Fatalf("tokenless verified mTLS unary error=%v called=%v, want Unauthenticated before dispatch", err, calledUnary)
}
calledStream := false
err = scope.stream(nil, &scopeExpiryServerStream{ctx: ctx}, &grpc.StreamServerInfo{
FullMethod: filer_pb.SeaweedFiler_ListEntries_FullMethodName,
}, func(any, grpc.ServerStream) error {
calledStream = true
return nil
})
if status.Code(err) != codes.Unauthenticated || calledStream {
t.Fatalf("tokenless verified mTLS stream error=%v called=%v, want Unauthenticated before dispatch", err, calledStream)
}
}
func TestFilerGrpcRequireTokenFailsClosedWithoutVerificationKey(t *testing.T) {
scope := newFilerGrpcScope(scopeConfig{
verificationKeys: func() (security.SigningKey, security.SigningKey) { return nil, nil },
requireToken: func() bool { return true },
}, newScopeFakeFiler())
called := false
_, err := scope.unary(context.Background(), &filer_pb.PingRequest{}, &grpc.UnaryServerInfo{
FullMethod: filer_pb.SeaweedFiler_Ping_FullMethodName,
}, func(context.Context, any) (any, error) {
called = true
return &filer_pb.PingResponse{}, nil
})
if status.Code(err) != codes.Unauthenticated || called {
t.Fatalf("missing-key require-mode error=%v called=%v, want Unauthenticated before dispatch", err, called)
}
}
func TestFilerGrpcRequireTokenDoesNotBypassTokenlessMTLSSubscription(t *testing.T) {
scope := subscriptionScopeServer(true)
scope.cfg.requireToken = func() bool { return true }
called := false
err := callSubscriptionStream(t, scope, security.MethodSubscribeMetadata, tokenlessVerifiedPeerContext(), func() {
called = true
})
if status.Code(err) != codes.Unauthenticated || called {
t.Fatalf("tokenless verified mTLS subscription error=%v called=%v, want Unauthenticated before dispatch", err, called)
}
}
func TestFilerGrpcRequireTokenPreservesDedicatedSubscriptionTokenFallback(t *testing.T) {
scope := subscriptionScopeServer(true)
scope.cfg.requireToken = func() bool { return true }
token := string(security.GenJwtForMetadataSubscription(security.SigningKey(subscriptionTokenKey), 60, []string{aliceWS}))
for _, method := range []string{security.MethodSubscribeMetadata, security.MethodSubscribeLocalMetadata} {
for _, transport := range []struct {
name string
ctx func(string) context.Context
}{
{"plain", subscriptionStreamContext},
{"mtls", verifiedSubscriptionContext},
} {
for _, bearer := range []struct {
name, token string
allowed bool
}{
{"valid", token, true},
{"invalid", "invalid", false},
{"missing", "", false},
} {
t.Run(method+"/"+transport.name+"/"+bearer.name, func(t *testing.T) {
ctx := transport.ctx(bearer.token)
called := false
err := scope.stream(nil, &scopeExpiryServerStream{ctx: ctx}, &grpc.StreamServerInfo{
FullMethod: scopeFilerMethodPrefix + method,
}, func(_ any, stream grpc.ServerStream) error {
called = true
want, _ := peer.FromContext(ctx)
if got, _ := peer.FromContext(stream.Context()); got != want {
t.Fatal("subscription admission replaced the handler's transport peer")
}
return nil
})
if bearer.allowed {
if err != nil || !called {
t.Fatalf("valid subscription bearer error=%v called=%v, want dispatch", err, called)
}
} else if status.Code(err) != codes.Unauthenticated || called {
t.Fatalf("invalid or missing subscription bearer error=%v called=%v, want rejection", err, called)
}
})
}
}
}
}
func TestFilerGrpcRequireTokenRejectsInvalidBearerWithPermissiveSubscriptionVerifier(t *testing.T) {
scope := subscriptionScopeServerWithKeys(true, security.SigningKey(subscriptionFilerKey), nil, nil)
scope.cfg.requireToken = func() bool { return true }
called := false
err := callSubscriptionStream(t, scope, security.MethodSubscribeMetadata, subscriptionStreamContext("invalid"), func() {
called = true
})
if status.Code(err) != codes.Unauthenticated || called {
t.Fatalf("invalid bearer with permissive subscription verifier error=%v called=%v, want Unauthenticated before dispatch", err, called)
}
}
func TestFilerGrpcRequireTokenSubscriptionKeepsTokenScopeOverMtls(t *testing.T) {
v := util.GetViper()
v.Set("jwt.filer_signing.subscribe.key", subscriptionTokenKey)
t.Cleanup(func() { v.Set("jwt.filer_signing.subscribe.key", "") })
fs := &FilerServer{}
fs.grpcScopeSettings.Store(&grpcScopeSettings{requireToken: true})
scope := subscriptionScopeServer(true)
scope.cfg.subscriptionScope = fs.metadataSubscriptionScope
scope.cfg.requireToken = func() bool { return true }
token := string(security.GenJwtForMetadataSubscription(security.SigningKey(subscriptionTokenKey), 60, []string{aliceWS}))
for _, method := range []string{security.MethodSubscribeMetadata, security.MethodSubscribeLocalMetadata} {
var got *security.MetadataSubscriptionScope
err := scope.stream(nil, &scopeExpiryServerStream{ctx: verifiedSubscriptionContext(token)}, &grpc.StreamServerInfo{
FullMethod: scopeFilerMethodPrefix + method,
}, func(_ any, stream grpc.ServerStream) (err error) {
got, err = fs.metadataSubscriptionScope(stream.Context(), method)
return err
})
if err != nil || got == nil || len(got.Prefixes) != 1 || got.Prefixes[0] != aliceWS {
t.Fatalf("%s over mTLS in require-mode: scope=%+v err=%v, want the token's prefixes", method, got, err)
}
// The token can expire before the handler reads the request; the
// certificate must not then widen the stream.
admitted := context.WithValue(verifiedSubscriptionContext("expired-subscription-token"), scopeSubscriptionContextKey{},
&security.MetadataSubscriptionScope{Prefixes: []string{aliceWS}, ExpiresAt: time.Now().Add(-time.Second)})
if got, err := fs.metadataSubscriptionScope(admitted, method); status.Code(err) != codes.Unauthenticated {
t.Fatalf("%s with an expired admitted token over mTLS: scope=%+v err=%v, want Unauthenticated", method, got, err)
}
if got, err := fs.metadataSubscriptionScope(verifiedSubscriptionContext("not-a-subscription-token"), method); err != nil || got != nil {
t.Fatalf("%s over mTLS with another bearer: scope=%+v err=%v, want the mTLS full stream", method, got, err)
}
}
}
+17 -2
View File
@@ -16,6 +16,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/peer"
"google.golang.org/protobuf/proto"
)
@@ -31,8 +32,22 @@ func (s *filerGrpcScope) stream(srv any, ss grpc.ServerStream, info *grpc.Stream
// caller when no subscription key is set, whatever the bearer.
method := strings.TrimPrefix(info.FullMethod, scopeFilerMethodPrefix)
if s.cfg.subscriptionScope != nil && (method == "SubscribeMetadata" || method == "SubscribeLocalMetadata") {
if _, authErr := bearerFromMetadata(ss.Context()); authErr == nil {
if _, subErr := s.cfg.subscriptionScope(ss.Context(), method); subErr == nil {
requireToken := s.cfg.requireToken != nil && s.cfg.requireToken()
// Require-mode must not let a tokenless mTLS peer, an invalid bearer,
// or a permissive no-subscribe-key verifier bypass the gate. A dedicated
// subscription token returns a non-nil scope; general/admin tokens that
// this filer accepts already passed resolve above.
if raw, authErr := bearerFromMetadata(ss.Context()); authErr == nil && raw != "" {
verificationContext := ss.Context()
if requireToken {
// Verify the bearer independently of the subscription verifier's
// mTLS shortcut. Keep the handler's original transport authority.
verificationContext = peer.NewContext(verificationContext, &peer.Peer{})
}
if subScope, subErr := s.cfg.subscriptionScope(verificationContext, method); subErr == nil && (!requireToken || subScope != nil) {
if subScope != nil {
ss = &subscriptionStream{ServerStream: ss, ctx: context.WithValue(ss.Context(), scopeSubscriptionContextKey{}, subScope)}
}
return handler(srv, ss)
}
}
+12 -2
View File
@@ -1,15 +1,25 @@
package weed_server
import (
"context"
"strings"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/grpc"
)
// Only the scope interceptor produces this marker, after verifying a general
// filer token. Dedicated subscription tokens keep their existing verifier.
// Only the scope interceptor produces this marker: a *scope for a general
// filer token, or the *security.MetadataSubscriptionScope a dedicated
// subscription token was admitted with.
type scopeSubscriptionContextKey struct{}
type subscriptionStream struct {
grpc.ServerStream
ctx context.Context
}
func (s *subscriptionStream) Context() context.Context { return s.ctx }
// checkSubscribe bounds every requested selector. Event filtering also enforces
// path-segment boundaries because the subscription's prefix match is textual.
func (sc *scope) checkSubscribe(method string, req *filer_pb.SubscribeMetadataRequest) error {
+4 -5
View File
@@ -12,7 +12,6 @@ import (
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/cluster"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/operation"
@@ -224,7 +223,7 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr
glog.V(2).InfofCtx(ctx, "CreateEntry %s: forwarding to owner %s", fullpath, owner)
req.IsMoved = true
return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
forwarded, e := client.CreateEntry(ctx, req)
forwarded, e := client.CreateEntry(withCallerAuthContext(ctx), req)
if e != nil {
return e
}
@@ -394,7 +393,7 @@ func (fs *FilerServer) ObjectTransaction(ctx context.Context, req *filer_pb.Obje
glog.V(2).InfofCtx(ctx, "ObjectTransaction %s: forwarding to owner %s", req.LockKey, owner)
return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
var e error
resp, e = client.ObjectTransaction(ctx, forwarded)
resp, e = client.ObjectTransaction(withCallerAuthContext(ctx), forwarded)
return e
})
})
@@ -961,7 +960,7 @@ func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntr
glog.V(2).InfofCtx(ctx, "UpdateEntry %s: forwarding to owner %s", fullpath, owner)
req.IsMoved = true
return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
forwarded, e := client.UpdateEntry(ctx, req)
forwarded, e := client.UpdateEntry(withCallerAuthContext(ctx), req)
if e != nil {
return e
}
@@ -1263,7 +1262,7 @@ func (fs *FilerServer) AppendToEntry(ctx context.Context, req *filer_pb.AppendTo
glog.V(4).InfofCtx(ctx, "AppendToEntry %s/%s", req.GetDirectory(), req.GetEntryName())
fullpath := util.NewFullPath(req.Directory, req.EntryName)
lockClient := cluster.NewLockClient(fs.grpcDialOption, fs.option.Host)
lockClient := fs.newLockClient()
lock := lockClient.NewBlockingLongLivedLock(string(fullpath), string(fs.option.Host), 0)
if lock == nil {
return nil, fmt.Errorf("failed to acquire lock for %s", fullpath)
+4 -2
View File
@@ -107,14 +107,16 @@ func (fs *FilerServer) Ping(ctx context.Context, req *filer_pb.PingRequest) (res
resp = &filer_pb.PingResponse{
StartTimeNs: time.Now().UnixNano(),
}
// Empty target is a self-liveness probe and stays unauthenticated.
// Empty target is a self-liveness probe. In compatibility mode it remains
// available without a bearer; require-token enforcement runs before this
// handler and rejects tokenless calls.
if req.Target != "" && !fs.isKnownPingTarget(ctx, req.Target, req.TargetType) {
resp.StopTimeNs = time.Now().UnixNano()
return resp, status.Errorf(codes.InvalidArgument, "unknown ping target %s of type %s", req.Target, req.TargetType)
}
if req.TargetType == cluster.FilerType {
pingErr = pb.WithFilerClient(false, 0, pb.ServerAddress(req.Target), fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
pingResp, err := client.Ping(ctx, &filer_pb.PingRequest{})
pingResp, err := client.Ping(withCallerAuthContext(ctx), &filer_pb.PingRequest{})
if pingResp != nil {
resp.RemoteTimeNs = pingResp.StartTimeNs
}
+8 -6
View File
@@ -35,7 +35,8 @@ func (fs *FilerServer) DistributedLock(ctx context.Context, req *filer_pb.LockRe
} else if !req.IsMoved && movedTo != "" && movedTo != fs.option.Host {
glog.V(3).Infof("FILER LOCK: Forwarding to correct filer - from=%s to=%s", fs.option.Host, movedTo)
err = pb.WithFilerClient(false, 0, movedTo, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
secondResp, err := client.DistributedLock(ctx, &filer_pb.LockRequest{
forwardCtx := withCallerAuthContext(ctx)
secondResp, err := client.DistributedLock(forwardCtx, &filer_pb.LockRequest{
Name: req.Name,
SecondsToLock: req.SecondsToLock,
RenewToken: req.RenewToken,
@@ -89,7 +90,8 @@ func (fs *FilerServer) DistributedUnlock(ctx context.Context, req *filer_pb.Unlo
err = mErr
} else if !req.IsMoved && movedTo != "" {
err = pb.WithFilerClient(false, 0, movedTo, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
secondResp, err := client.DistributedUnlock(ctx, &filer_pb.UnlockRequest{
forwardCtx := withCallerAuthContext(ctx)
secondResp, err := client.DistributedUnlock(forwardCtx, &filer_pb.UnlockRequest{
Name: req.Name,
RenewToken: req.RenewToken,
IsMoved: true,
@@ -120,7 +122,7 @@ func (fs *FilerServer) FindLockOwner(ctx context.Context, req *filer_pb.FindLock
}
if !req.IsMoved && movedTo != "" {
err = pb.WithFilerClient(false, 0, movedTo, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
secondResp, err := client.FindLockOwner(ctx, &filer_pb.FindLockOwnerRequest{
secondResp, err := client.FindLockOwner(withCallerAuthContext(ctx), &filer_pb.FindLockOwnerRequest{
Name: req.Name,
IsMoved: true,
})
@@ -206,7 +208,7 @@ func (fs *FilerServer) OnDlmChangeSnapshot(snapshot []pb.ServerAddress) {
glog.V(0).Infof("DLM: transferring primary lock %s to new primary=%s", lock.Key, primary)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err := pb.WithFilerClient(false, 0, primary, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.TransferLocks(ctx, &filer_pb.TransferLocksRequest{
_, err := client.TransferLocks(fs.peerContext(ctx), &filer_pb.TransferLocksRequest{
Locks: []*filer_pb.Lock{
{
Name: lock.Key,
@@ -235,7 +237,7 @@ func (fs *FilerServer) OnDlmChangeSnapshot(snapshot []pb.ServerAddress) {
// We're neither primary nor backup → transfer to primary and remove locally
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err := pb.WithFilerClient(false, 0, primary, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.TransferLocks(ctx, &filer_pb.TransferLocksRequest{
_, err := client.TransferLocks(fs.peerContext(ctx), &filer_pb.TransferLocksRequest{
Locks: []*filer_pb.Lock{
{
Name: lock.Key,
@@ -267,7 +269,7 @@ func (fs *FilerServer) SetupDlmReplication() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err := pb.WithFilerClient(false, 0, server, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
_, err := client.ReplicateLock(ctx, &filer_pb.ReplicateLockRequest{
_, err := client.ReplicateLock(fs.peerContext(ctx), &filer_pb.ReplicateLockRequest{
Name: key,
RenewToken: token,
PrevRenewToken: prevToken,
@@ -12,6 +12,7 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
@@ -24,11 +25,18 @@ import (
// receivedUpdates counts the UpdateEntry requests a filer receives over gRPC,
// and how many of them another filer forwarded (is_moved).
type receivedUpdates struct {
mu sync.Mutex
updates, moved int
mu sync.Mutex
updates, moved int
pingAuthorizations [][]string
}
func (c *receivedUpdates) intercept(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
if _, ok := req.(*filer_pb.PingRequest); ok {
md, _ := metadata.FromIncomingContext(ctx)
c.mu.Lock()
c.pingAuthorizations = append(c.pingAuthorizations, slices.Clone(md.Get("authorization")))
c.mu.Unlock()
}
if r, ok := req.(*filer_pb.UpdateEntryRequest); ok {
c.mu.Lock()
c.updates++
@@ -56,7 +64,7 @@ type twoFilers struct {
callsA, callsB *receivedUpdates
}
func newTwoFilers(t *testing.T) *twoFilers {
func newTwoFilers(t *testing.T, configure ...func(*FilerServer)) *twoFilers {
t.Helper()
c := &twoFilers{
store: newRenameTestStore(),
@@ -79,7 +87,14 @@ func newTwoFilers(t *testing.T) *twoFilers {
grpcDialOption: c.dial,
entryLockTable: util.NewLockTable[util.FullPath](),
}
srv := grpc.NewServer(grpc.UnaryInterceptor(calls.intercept))
for _, config := range configure {
config(fs)
}
options := []grpc.ServerOption{grpc.UnaryInterceptor(calls.intercept)}
if fs.grpcScope != nil {
options = append(options, fs.grpcScope.ServerOptions()...)
}
srv := grpc.NewServer(options...)
filer_pb.RegisterSeaweedFilerServer(srv, fs)
go func() { _ = srv.Serve(lis) }()
t.Cleanup(func() {
+7 -2
View File
@@ -9,6 +9,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
@@ -65,6 +67,9 @@ func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockReq
if fs.filer.Dlm != nil {
if owner := fs.filer.Dlm.LockRing.GetPrimary(req.Key); owner != "" && owner != fs.option.Host {
if !req.IsMoved && scopeKeepOnly(ctx) {
return &filer_pb.PosixLockResponse{}, status.Error(codes.PermissionDenied, "scoped PosixLock cannot be forwarded")
}
if err := fs.checkMovedMarker(ctx, req.IsMoved, owner); err != nil {
return &filer_pb.PosixLockResponse{}, err
}
@@ -80,7 +85,7 @@ func (fs *FilerServer) PosixLock(ctx context.Context, req *filer_pb.PosixLockReq
var resp *filer_pb.PosixLockResponse
err := pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
var e error
resp, e = client.PosixLock(ctx, forwarded)
resp, e = client.PosixLock(withCallerAuthContext(ctx), forwarded)
return e
})
if err != nil {
@@ -207,7 +212,7 @@ func (fs *FilerServer) posixCoolingOrWarmup(ctx context.Context, key string, lk
var resp *filer_pb.PosixLockResponse
err := pb.WithFilerClient(false, 0, prior, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
var e error
resp, e = client.PosixLock(probeCtx, &filer_pb.PosixLockRequest{
resp, e = client.PosixLock(fs.peerContext(probeCtx), &filer_pb.PosixLockRequest{
Key: key,
IsMoved: true,
CoolingProbe: true,
+1 -1
View File
@@ -57,7 +57,7 @@ func (fs *FilerServer) forwardDeleteEntry(ctx context.Context, req *filer_pb.Del
glog.V(2).InfofCtx(ctx, "DeleteEntry %s: forwarding to owner %s", fullpath, owner)
req.IsMoved = true
return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
forwarded, e := client.DeleteEntry(ctx, req)
forwarded, e := client.DeleteEntry(withCallerAuthContext(ctx), req)
if e != nil {
return e
}
@@ -15,7 +15,8 @@ import (
)
func (fs *FilerServer) metadataSubscriptionScope(ctx context.Context, method string) (*security.MetadataSubscriptionScope, error) {
if sc, ok := ctx.Value(scopeSubscriptionContextKey{}).(*scope); ok {
switch sc := ctx.Value(scopeSubscriptionContextKey{}).(type) {
case *scope:
if sc.expired() {
return nil, scopeExpiredError(sc)
}
@@ -24,16 +25,26 @@ func (fs *FilerServer) metadataSubscriptionScope(ctx context.Context, method str
prefixes = append(prefixes, grant.path)
}
return &security.MetadataSubscriptionScope{Prefixes: prefixes, ExpiresAt: sc.exp}, nil
case *security.MetadataSubscriptionScope:
if !time.Now().Before(sc.ExpiresAt) {
return nil, errMetadataSubscriptionExpired
}
return sc, nil
}
var adminKey, previousAdminKey security.SigningKey
if fs.filerGuard != nil {
adminKey, previousAdminKey = fs.filerGuard.VerificationKeys(true)
}
return security.CheckGrpcMetadataSubscription(ctx,
security.SigningKey(util.GetViper().GetString("jwt.filer_signing.subscribe.key")),
adminKey,
previousAdminKey,
method)
subscribeKey := security.SigningKey(util.GetViper().GetString("jwt.filer_signing.subscribe.key"))
subscription, err := security.CheckGrpcMetadataSubscription(ctx, subscribeKey, adminKey, previousAdminKey, method)
if settings := fs.grpcScopeSettings.Load(); err != nil && settings != nil && len(settings.key) > 0 {
// An unscoped grpc_key token already has full filer gRPC access, and
// peers without the shared key sign their subscriptions with it.
if grpcSubscription, grpcErr := security.CheckGrpcMetadataSubscription(ctx, subscribeKey, settings.key, settings.previousKey, method); grpcErr == nil {
return grpcSubscription, nil
}
}
return subscription, err
}
// scopeMetadataResponse keeps only what a scoped subscriber may see: events
+7
View File
@@ -331,6 +331,8 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption)
glog.Warningf("filer: guard.white_list is configured but the IP whitelist feature is currently disabled. See https://github.com/seaweedfs/seaweedfs/issues/7094")
}
fs.filerGuard = security.NewGuard([]string{}, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec, v.GetString("jwt.filer_signing.previous_key"), v.GetString("jwt.filer_signing.read.previous_key"))
fs.filer.PeerContext = fs.peerContext
fs.filer.PeerSubscriptionContext = fs.peerSubscriptionContext
basicAuth, basicAuthFile := loadBasicAuth(nil, "")
fs.basicAuth.Store(basicAuth)
fs.basicAuthFile = basicAuthFile
@@ -338,8 +340,10 @@ func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, option *FilerOption)
fs.loadGrpcScopeConfig(v)
fs.grpcScope = newFilerGrpcScope(scopeConfig{
adminKeys: func() (security.SigningKey, security.SigningKey) { return fs.filerGuard.VerificationKeys(true) },
verificationKeys: fs.grpcScopeVerificationKeys,
subscriptionScope: fs.metadataSubscriptionScope,
requireToken: func() bool { return fs.grpcScopeSettings.Load().requireToken },
leeway: func() time.Duration { return fs.grpcScopeSettings.Load().leeway },
assignLifetime: func() time.Duration { return fs.grpcScopeSettings.Load().assignLifetime },
}, fs)
@@ -835,6 +839,7 @@ func (fs *FilerServer) Reload() {
type grpcScopeSettings struct {
key security.SigningKey
previousKey security.SigningKey
requireToken bool
leeway time.Duration
assignLifetime time.Duration
}
@@ -842,6 +847,7 @@ type grpcScopeSettings struct {
func (fs *FilerServer) loadGrpcScopeConfig(v *util.ViperProxy) {
v.SetDefault("jwt.filer_signing.assign_expires_after_seconds", int(security.DefaultAssignTokenLifetime/time.Second))
v.SetDefault("jwt.filer_signing.clock_leeway_seconds", 30)
v.SetDefault("jwt.filer_signing.grpc_require_token", false)
key := security.SigningKey(v.GetString("jwt.filer_signing.grpc_key"))
previousKey := security.SigningKey(v.GetString("jwt.filer_signing.grpc_previous_key"))
lifetime := time.Duration(v.GetInt("jwt.filer_signing.assign_expires_after_seconds")) * time.Second
@@ -859,6 +865,7 @@ func (fs *FilerServer) loadGrpcScopeConfig(v *util.ViperProxy) {
fs.grpcScopeSettings.Store(&grpcScopeSettings{
key: key,
previousKey: previousKey,
requireToken: v.GetBool("jwt.filer_signing.grpc_require_token"),
leeway: leeway,
assignLifetime: lifetime,
})
@@ -25,6 +25,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/storage/needle"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/constants"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
@@ -278,7 +280,7 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa
// when it is an append
if isAppend || isOffsetWrite {
if fs.filer.Dlm != nil && len(fs.filer.Dlm.LockRing.GetSnapshot()) > 1 {
lockClient := cluster.NewLockClient(fs.grpcDialOption, fs.option.Host)
lockClient := fs.newLockClient()
distributedLock = lockClient.NewBlockingLongLivedLock(path, string(fs.option.Host), 0)
if distributedLock == nil {
replyerr = fmt.Errorf("failed to acquire lock for %s; retry the request", path)
@@ -458,6 +460,7 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa
}
// maybe compact entry chunks
unmanifested := mergedChunks
mergedChunks, replyerr = filer.MaybeManifestize(fs.saveAsChunk(ctx, so), fs.filer.DeleteChunksNotRecursive, mergedChunks)
if replyerr != nil {
glog.V(0).InfofCtx(ctx, "manifestize %s: %v", r.RequestURI, replyerr)
@@ -530,7 +533,8 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa
routed, dbErr = fs.forwardToWriteOwner(ctx, entryRouteKey(util.FullPath(path)), func(owner pb.ServerAddress) error {
return pb.WithFilerClient(false, 0, owner, fs.grpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
dir, _ := entry.FullPath.DirAndName()
return filer_pb.CreateEntry(context.WithoutCancel(ctx), client, &filer_pb.CreateEntryRequest{
forwardCtx := fs.withHTTPForwardAuthContext(context.WithoutCancel(ctx), r)
return filer_pb.CreateEntry(forwardCtx, client, &filer_pb.CreateEntryRequest{
Directory: dir,
Entry: entry.ToProtoEntry(),
IsMoved: true,
@@ -554,6 +558,12 @@ func (fs *FilerServer) saveMetaData(ctx context.Context, r *http.Request, fileNa
switch {
case routed && errors.Is(dbErr, filer_pb.ErrPreconditionFailed):
replyerr = fmt.Errorf("entry %s changed during append; retry the request", path)
case routed && status.Code(dbErr) == codes.Unauthenticated:
// The owner refused the call before running it. A new manifest can
// list committed chunks, so only its own blob is deleted.
if !inlineAppendConverted {
fs.filer.DeleteChunksNotRecursive(filer.DoMinusChunks(mergedChunks, unmanifested))
}
case routed:
// The owner may have committed before the reply was lost, and a
// separate local store may not hold that commit yet.
@@ -0,0 +1,210 @@
package weed_server
import (
"context"
"crypto/rand"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/operation"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/security"
"github.com/seaweedfs/seaweedfs/weed/util"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// HTTP append and offset forwarding must keep compatibility-mode requests
// tokenless while require-mode carries the request's bearer to the owner.
func TestSaveMetaDataHTTPForwardAuthFollowsRequireMode(t *testing.T) {
for _, tc := range []struct {
name string
requireToken bool
write string
auth string
wantError codes.Code
}{
{name: "compatibility/append expired bearer", write: "append", auth: "expired", wantError: codes.OK},
{name: "compatibility/append unrelated bearer", write: "append", auth: "unrelated", wantError: codes.OK},
{name: "compatibility/append AT cookie", write: "append", auth: "cookie", wantError: codes.OK},
{name: "compatibility/offset expired bearer", write: "offset", auth: "expired", wantError: codes.OK},
{name: "require/append valid bearer", requireToken: true, write: "append", auth: "valid", wantError: codes.OK},
{name: "require/append expired bearer", requireToken: true, write: "append", auth: "expired", wantError: codes.Unauthenticated},
{name: "require/append unrelated bearer", requireToken: true, write: "append", auth: "unrelated", wantError: codes.Unauthenticated},
{name: "require/append valid AT cookie", requireToken: true, write: "append", auth: "cookie", wantError: codes.OK},
{name: "require/offset valid bearer", requireToken: true, write: "offset", auth: "valid", wantError: codes.OK},
{name: "require/offset expired bearer", requireToken: true, write: "offset", auth: "expired", wantError: codes.Unauthenticated},
} {
t.Run(tc.name, func(t *testing.T) {
c, key := newHTTPForwardAuthFilers(t, tc.requireToken)
path := c.keyOwnedBy(t, c.addrB, c.addrB)
seedHTTPForwardEntry(t, c, path, tc.write)
requestURL := string(path)
if tc.write == "append" {
requestURL += "?op=append"
}
r := httptest.NewRequest(http.MethodPut, requestURL, nil)
setHTTPForwardAuth(t, r, key, tc.auth)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var saveErr error
var uncommitted []*filer_pb.FileChunk
if tc.write == "append" {
_, saveErr, uncommitted = c.fsA.saveMetaData(ctx, r, path.Name(), "", &operation.StorageOption{}, 4, nil, nil, 3, []byte("new"))
} else {
_, saveErr, uncommitted = c.fsA.saveMetaData(ctx, r, path.Name(), "", &operation.StorageOption{}, 4, nil, []*filer_pb.FileChunk{{FileId: "3,new", Offset: 3, Size: 3}}, 6, nil)
}
if got := status.Code(saveErr); got != tc.wantError {
t.Fatalf("saveMetaData error code = %v, want %v (error=%v)", got, tc.wantError, saveErr)
}
if tc.write == "offset" && tc.wantError != codes.OK {
if len(uncommitted) != 1 || uncommitted[0].GetFileIdString() != "3,new" {
t.Fatalf("refused offset write uncommitted chunks = %v, want only the new chunk", uncommitted)
}
} else if len(uncommitted) != 0 {
t.Fatalf("uncommitted chunks = %v, want none", uncommitted)
}
stored, err := c.store.FindEntry(ctx, path)
if err != nil {
t.Fatalf("find entry: %v", err)
}
if tc.write == "append" {
wantContent := ""
if tc.wantError == codes.OK {
wantContent = "new"
}
if got := string(stored.Content); got != wantContent {
t.Fatalf("stored content = %q, want %q", got, wantContent)
}
} else {
wantChunks := 1
wantSize := uint64(3)
if tc.wantError == codes.OK {
wantChunks = 2
wantSize = 6
}
if got := len(stored.GetChunks()); got != wantChunks {
t.Fatalf("stored chunk count = %d, want %d", got, wantChunks)
}
if got := stored.FileSize; got != wantSize {
t.Fatalf("stored file size = %d, want %d", got, wantSize)
}
}
})
}
}
// A refused append deletes the manifest this filer generated, but not the
// committed chunks the manifest lists.
func TestRefusedHTTPAppendCleansGeneratedManifest(t *testing.T) {
c, key := newHTTPForwardAuthFilers(t, true)
_, uploaded := newInlineAppendUploadServer(t, c.fsA.filer, 0, 0)
path := c.keyOwnedBy(t, c.addrB, c.addrB)
entry := newFileEntry(string(path), 7)
for i := 0; i < filer.SmallChunkManifestBatch-1; i++ {
entry.Chunks = append(entry.Chunks, &filer_pb.FileChunk{FileId: fmt.Sprintf("3,old%d", i), Offset: int64(i) * 3, Size: 3})
}
entry.FileSize = uint64(len(entry.Chunks)) * 3
if err := c.store.InsertEntry(context.Background(), entry); err != nil {
t.Fatalf("seed entry: %v", err)
}
r := httptest.NewRequest(http.MethodPut, string(path)+"?op=append", nil)
setHTTPForwardAuth(t, r, key, "expired")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, saveErr, uncommitted := c.fsA.saveMetaData(ctx, r, path.Name(), "", &operation.StorageOption{}, 4, nil, []*filer_pb.FileChunk{{FileId: "3,new", Size: 3}}, 3, nil)
if got := status.Code(saveErr); got != codes.Unauthenticated {
t.Fatalf("saveMetaData error code = %v, want Unauthenticated (error=%v)", got, saveErr)
}
if len(uncommitted) != 1 || uncommitted[0].GetFileIdString() != "3,new" {
t.Fatalf("uncommitted chunks = %v, want only the new chunk", uncommitted)
}
uploaded.mu.Lock()
var manifests []string
for fileId := range uploaded.data {
manifests = append(manifests, fileId)
}
uploaded.mu.Unlock()
if len(manifests) != 1 {
t.Fatalf("uploaded blobs = %v, want one generated manifest", manifests)
}
var queued []string
c.fsA.filer.FileIdDeletionQueue.Consume(func(fileIds []string) { queued = append(queued, fileIds...) })
if len(queued) != 1 || queued[0] != manifests[0] {
t.Fatalf("queued deletions = %v, want only the generated manifest %s", queued, manifests[0])
}
stored, err := c.store.FindEntry(ctx, path)
if err != nil {
t.Fatalf("find entry: %v", err)
}
if got := len(stored.GetChunks()); got != filer.SmallChunkManifestBatch-1 {
t.Fatalf("stored chunk count = %d, want %d", got, filer.SmallChunkManifestBatch-1)
}
}
func newHTTPForwardAuthFilers(t *testing.T, requireToken bool) (*twoFilers, security.SigningKey) {
t.Helper()
keyBytes := make([]byte, 32)
if _, err := rand.Read(keyBytes); err != nil {
t.Fatalf("generate filer signing key: %v", err)
}
key := security.SigningKey(keyBytes)
c := newTwoFilers(t, func(fs *FilerServer) {
fs.option.SaveToFilerLimit = 64
fs.filerGuard = security.NewGuard(nil, string(key), 10, "", 0, "", "")
fs.filer.PeerContext = fs.peerContext
fs.grpcScopeSettings.Store(&grpcScopeSettings{requireToken: requireToken})
fs.grpcScope = newFilerGrpcScope(scopeConfig{
signingKey: fs.filerGuard.SigningKey,
verificationKeys: func() (security.SigningKey, security.SigningKey) { return fs.filerGuard.VerificationKeys(true) },
requireToken: func() bool { return requireToken },
}, fs)
})
sharedWriteRing(c)
return c, key
}
func seedHTTPForwardEntry(t *testing.T, c *twoFilers, path util.FullPath, write string) {
t.Helper()
if write == "append" {
c.seed(t, path)
return
}
entry := newFileEntry(string(path), 7)
entry.FileSize = 3
entry.Chunks = []*filer_pb.FileChunk{{FileId: "3,old", Offset: 0, Size: 3}}
if err := c.store.InsertEntry(context.Background(), entry); err != nil {
t.Fatalf("seed offset entry: %v", err)
}
}
func setHTTPForwardAuth(t *testing.T, r *http.Request, key security.SigningKey, kind string) {
t.Helper()
switch kind {
case "valid":
r.Header.Set("Authorization", "Bearer "+peerAdminToken(key))
case "expired":
claims := jwt.RegisteredClaims{ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute))}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(key))
if err != nil {
t.Fatalf("sign expired test token: %v", err)
}
r.Header.Set("Authorization", "Bearer "+token)
case "unrelated":
r.Header.Set("Authorization", "Bearer "+peerAdminToken(security.SigningKey("unrelated-key")))
case "cookie":
r.AddCookie(&http.Cookie{Name: "AT", Value: peerAdminToken(key)})
default:
t.Fatalf("unknown HTTP auth kind %q", kind)
}
}