diff --git a/weed/command/fuse_std.go b/weed/command/fuse_std.go index 2756c0bb7d..d601a47fec 100644 --- a/weed/command/fuse_std.go +++ b/weed/command/fuse_std.go @@ -125,6 +125,8 @@ func runFuse(cmd *Command, args []string) bool { mountOptions.filer = ¶meter.value case "filer.path": mountOptions.filerMountRootPath = ¶meter.value + case "filer.tokenFile": + mountOptions.filerTokenFile = ¶meter.value case "volumeName": mountOptions.volumeName = ¶meter.value case "dirAutoCreate": diff --git a/weed/command/fuse_std_test.go b/weed/command/fuse_std_test.go index 4026a943ad..6bde26d1c8 100644 --- a/weed/command/fuse_std_test.go +++ b/weed/command/fuse_std_test.go @@ -65,3 +65,28 @@ func TestRunFuseSetsVolumeName(t *testing.T) { "volumeName=MyDisk,concurrentReaders=bad", }) } + +func TestRunFuseSetsFilerTokenFile(t *testing.T) { + oldTokenFile := mountOptions.filerTokenFile + oldConcurrentReaders := mountOptions.concurrentReaders + oldDir := mountOptions.dir + defer func() { + got := mountOptions.filerTokenFile + mountOptions.filerTokenFile = oldTokenFile + mountOptions.concurrentReaders = oldConcurrentReaders + mountOptions.dir = oldDir + + if recover() == nil { + t.Fatal("expected invalid concurrentReaders option to be parsed") + } + if got == nil || *got != "/run/seaweedfs/token" { + t.Fatalf("-o filer.tokenFile did not set mountOptions.filerTokenFile, got %v", got) + } + }() + + runFuse(cmdMount, []string{ + "/mnt", + "-o", + "filer.tokenFile=/run/seaweedfs/token,concurrentReaders=bad", + }) +} diff --git a/weed/command/mount.go b/weed/command/mount.go index 3f45f10fe5..36eb719fcd 100644 --- a/weed/command/mount.go +++ b/weed/command/mount.go @@ -8,6 +8,7 @@ import ( type MountOptions struct { filer *string filerMountRootPath *string + filerTokenFile *string dir *string volumeName *string dirAutoCreate *bool @@ -104,6 +105,7 @@ func init() { cmdMount.Run = runMount // break init cycle mountOptions.filer = cmdMount.Flag.String("filer", "localhost:8888", "comma-separated weed filer location") mountOptions.filerMountRootPath = cmdMount.Flag.String("filer.path", "/", "mount this remote path from filer server") + mountOptions.filerTokenFile = cmdMount.Flag.String("filer.tokenFile", "", "file holding a pre-issued filer gRPC token, re-read for every filer call so a replaced file takes effect without a restart; a missing or empty file fails the call. Cannot be combined with -peer.enable or -dlm. copy_file_range's server-side copy signs its filer HTTP request with jwt.filer_signing.key, not this token, and is unsupported with it") mountOptions.dir = cmdMount.Flag.String("dir", ".", "mount weed filer to this directory") mountOptions.volumeName = cmdMount.Flag.String("volumeName", "", "name the mount shown by the platform (Finder/Explorer, or \"mount\"/\"df\" on Linux and FreeBSD), overriding the name taken from -filer.path or -dir") mountOptions.dirAutoCreate = cmdMount.Flag.Bool("dirAutoCreate", false, "auto create the directory to mount to") diff --git a/weed/command/mount_common.go b/weed/command/mount_common.go index bc1a2c0c7f..99a68f3c60 100644 --- a/weed/command/mount_common.go +++ b/weed/command/mount_common.go @@ -149,7 +149,7 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr var err error var digest string for i := 0; i < 10; i++ { - err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, nil, func(client filer_pb.SeaweedFilerClient) error { + err = pb.WithOneOfGrpcFilerClients(false, filerAddresses, grpcDialOption, mountFilerTokenSource(option), func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(context.Background(), &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return fmt.Errorf("get filer grpc address %v configuration: %w", filerAddresses, err) @@ -180,6 +180,31 @@ func connectToFiler(option *MountOptions) (filerAddresses []pb.ServerAddress, gr return filerAddresses, grpcDialOption, cipher, bucketRootPath, true } +// mountFilerTokenSource reads -filer.tokenFile for each filer call, or is nil +// without it so the mount keeps its existing credentials. +func mountFilerTokenSource(option *MountOptions) security.FilerTokenSource { + if option.filerTokenFile == nil || *option.filerTokenFile == "" { + return nil + } + return security.FilerTokenFile(util.ResolvePath(*option.filerTokenFile)) +} + +// checkFilerTokenFile refuses options a filer token cannot serve. A filer +// refuses MountRegister, MountList and distributed locks to a scoped token, +// so peer chunk sharing and -dlm would fail at run time instead of at start. +func checkFilerTokenFile(option *MountOptions) error { + if option.filerTokenFile == nil || *option.filerTokenFile == "" { + return nil + } + if option.peerEnabled != nil && *option.peerEnabled { + return fmt.Errorf("-filer.tokenFile cannot be used with -peer.enable: the filer refuses MountRegister and MountList to scoped tokens") + } + if option.distributedLock != nil && *option.distributedLock { + return fmt.Errorf("-filer.tokenFile cannot be used with -dlm: the filer refuses distributed locks to scoped tokens") + } + return nil +} + // fileSystemParams are the pieces of a mount that each platform works out for // itself: where it is attached, and whose identity the entries carry. type fileSystemParams struct { @@ -219,6 +244,7 @@ func buildSeaweedFileSystem(option *MountOptions, p fileSystemParams) *mount.WFS GrpcDialOption: p.grpcDialOption, FilerSigningKey: security.SigningKey(util.GetViper().GetString("jwt.filer_signing.key")), FilerSigningExpiresAfterSec: util.GetViper().GetInt("jwt.filer_signing.expires_after_seconds"), + FilerTokenSource: mountFilerTokenSource(option), FilerMountRootPath: p.mountRoot, VolumeReadAuth: option.volumeReadAuth != nil && *option.volumeReadAuth, Collection: *option.collection, diff --git a/weed/command/mount_std.go b/weed/command/mount_std.go index 5db141b288..adc6f4293d 100644 --- a/weed/command/mount_std.go +++ b/weed/command/mount_std.go @@ -46,6 +46,10 @@ func RunMount(option *MountOptions, umask os.FileMode) bool { fmt.Println(err) return false } + if err := checkFilerTokenFile(option); err != nil { + fmt.Println(err) + return false + } filerAddresses, grpcDialOption, cipher, bucketRootPath, ok := connectToFiler(option) if !ok { @@ -74,7 +78,7 @@ func RunMount(option *MountOptions, umask os.FileMode) bool { } } var err error - sseReader, err = mount.NewSSES3Reader(context.Background(), bucketPath, filerAddresses, grpcDialOption) + sseReader, err = mount.NewSSES3Reader(context.Background(), bucketPath, filerAddresses, grpcDialOption, mountFilerTokenSource(option)) if err != nil { glog.Errorf("configure SSE-S3 reads: %v", err) return false diff --git a/weed/command/mount_token_file_test.go b/weed/command/mount_token_file_test.go new file mode 100644 index 0000000000..1fadb10061 --- /dev/null +++ b/weed/command/mount_token_file_test.go @@ -0,0 +1,118 @@ +//go:build linux || darwin || freebsd || windows + +package command + +import ( + "context" + "net" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" +) + +func TestCheckFilerTokenFileRefusesUnsupportedOptions(t *testing.T) { + on, off := true, false + tokenFile, none := "/run/filer-token", "" + tests := []struct { + name string + tokenFile *string + peer, dlm *bool + want string + }{ + {name: "no token file", tokenFile: &none, peer: &on, dlm: &on}, + {name: "unset token file", peer: &on, dlm: &on}, + {name: "token file alone", tokenFile: &tokenFile, peer: &off, dlm: &off}, + {name: "token file, options unset", tokenFile: &tokenFile}, + {name: "peer sharing", tokenFile: &tokenFile, peer: &on, dlm: &off, want: "-peer.enable"}, + {name: "distributed lock", tokenFile: &tokenFile, peer: &off, dlm: &on, want: "-dlm"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := checkFilerTokenFile(&MountOptions{filerTokenFile: tt.tokenFile, peerEnabled: tt.peer, distributedLock: tt.dlm}) + if tt.want == "" { + if err != nil { + t.Fatalf("checkFilerTokenFile = %v, want nil", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.want) || !strings.Contains(err.Error(), "-filer.tokenFile") { + t.Fatalf("checkFilerTokenFile = %v, want a refusal naming -filer.tokenFile and %s", err, tt.want) + } + }) + } +} + +func TestMountFilerTokenSourceIsNilWithoutFlag(t *testing.T) { + empty := "" + for _, option := range []*MountOptions{{}, {filerTokenFile: &empty}} { + if mountFilerTokenSource(option) != nil { + t.Fatal("a mount without -filer.tokenFile has a token source") + } + } +} + +type configurationFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + mu sync.Mutex + tokens [][]string +} + +func (f *configurationFiler) GetFilerConfiguration(ctx context.Context, _ *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + f.mu.Lock() + f.tokens = append(f.tokens, md.Get("authorization")) + f.mu.Unlock() + return &filer_pb.GetFilerConfigurationResponse{DirBuckets: "/buckets"}, nil +} + +// The startup handshake runs before the file system exists and must already +// present the token file, or a filer that requires tokens refuses the mount. +func TestConnectToFilerPresentsTokenFile(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + fake := &configurationFiler{} + server := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(server, fake) + go server.Serve(listener) + t.Cleanup(server.Stop) + address := string(pb.NewServerAddressWithGrpcPort("127.0.0.1:1", listener.Addr().(*net.TCPAddr).Port)) + + tokenPath := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(tokenPath, []byte("bootstrap-token\n"), 0o600); err != nil { + t.Fatal(err) + } + for _, tt := range []struct { + name string + tokenFile string + want []string + }{ + {name: "without token file", want: nil}, + {name: "with token file", tokenFile: tokenPath, want: []string{"Bearer bootstrap-token"}}, + } { + t.Run(tt.name, func(t *testing.T) { + fake.mu.Lock() + fake.tokens = nil + fake.mu.Unlock() + filer, tokenFile := address, tt.tokenFile + _, _, _, bucketRoot, ok := connectToFiler(&MountOptions{filer: &filer, filerTokenFile: &tokenFile}) + if !ok || bucketRoot != "/buckets" { + t.Fatalf("connectToFiler ok=%v bucketRoot=%q", ok, bucketRoot) + } + fake.mu.Lock() + defer fake.mu.Unlock() + if len(fake.tokens) != 1 || strings.Join(fake.tokens[0], ",") != strings.Join(tt.want, ",") { + t.Fatalf("authorization = %q, want %q", fake.tokens, tt.want) + } + }) + } +} diff --git a/weed/command/mount_windows.go b/weed/command/mount_windows.go index eba12c13d4..fc6c409557 100644 --- a/weed/command/mount_windows.go +++ b/weed/command/mount_windows.go @@ -49,6 +49,10 @@ func RunMount(option *MountOptions, umask os.FileMode) bool { fmt.Println("-idmap is only supported on Linux") return false } + if err := checkFilerTokenFile(option); err != nil { + fmt.Println(err) + return false + } dir := *option.dir if dir == "" { diff --git a/weed/mount/inode_to_path.go b/weed/mount/inode_to_path.go index 1c4da1a7c6..d042450c8f 100644 --- a/weed/mount/inode_to_path.go +++ b/weed/mount/inode_to_path.go @@ -539,6 +539,17 @@ func (i *InodeToPath) HasInode(inode uint64) bool { return found } +// DirectoryInodes returns the inodes of the directories the kernel holds. +func (i *InodeToPath) DirectoryInodes() []uint64 { + i.RLock() + defer i.RUnlock() + inodes := make([]uint64, 0, len(i.dirStates)) + for inode := range i.dirStates { + inodes = append(inodes, inode) + } + return inodes +} + func (i *InodeToPath) InvalidateAllChildrenCache() { i.Lock() defer i.Unlock() diff --git a/weed/mount/meta_cache/meta_cache.go b/weed/mount/meta_cache/meta_cache.go index c889488c00..e93c9a6290 100644 --- a/weed/mount/meta_cache/meta_cache.go +++ b/weed/mount/meta_cache/meta_cache.go @@ -96,6 +96,9 @@ type directoryBuildState struct { // removals the rebuild wipe declined as being of another file than the // one cached; the replay checks them again against what it finds declinedRemovals map[*filer_pb.SubscribeMetadataResponse]struct{} + // discarded is set when the listing can no longer be trusted, for example + // after the mount's filer grant narrowed: the build must not publish it + discarded bool } const recentEventDedupWindow = 4096 @@ -108,6 +111,7 @@ const ( metadataCompleteBuild metadataAbortBuild metadataPurgeDir + metadataDiscardBuilds metadataSectionRefresh metadataShutdown ) @@ -373,6 +377,26 @@ func (mc *MetaCache) PurgeDirectoryChildren(dirPath util.FullPath, resetFn func( }) } +// ErrDirectoryBuildDiscarded ends a directory build that DiscardDirectoryBuilds +// marked: the build publishes nothing, and its caller wipes what it inserted and +// lists the directory again. +var ErrDirectoryBuildDiscarded = errors.New("directory build discarded") + +// DiscardDirectoryBuilds asynchronously makes every directory build in flight +// end without publishing, then runs resetFn, so a listing read before a +// distrust is never cached after it: a build that completed earlier is reset +// by resetFn, and one still running is discarded. Both happen in the apply +// loop, serialized with completeDirectoryBuildNow's markCachedFn. A build that +// begins later is unaffected. +func (mc *MetaCache) DiscardDirectoryBuilds(resetFn func()) { + _ = mc.enqueueApplyRequest(metadataApplyRequest{ + ctx: context.Background(), + kind: metadataDiscardBuilds, + resetFn: resetFn, + done: make(chan error, 1), + }) +} + // UpdateEntry stores a local write against the entry. versionTsNs is the // filer log position the write restates — a section refresh listed before it // must not roll the content back — or zero when no position describes it, @@ -1022,6 +1046,14 @@ func (mc *MetaCache) handleApplyRequest(req metadataApplyRequest) error { return mc.abortDirectoryBuildNow(req.buildPath) case metadataPurgeDir: return mc.purgeDirectoryChildrenNow(req.ctx, req.buildPath, req.resetFn) + case metadataDiscardBuilds: + for _, state := range mc.buildingDirs { + state.discarded = true + } + if req.resetFn != nil { + req.resetFn() + } + return nil case metadataSectionRefresh: return mc.applySectionRefreshNow(req.ctx, req.buildPath, req.refresh) case metadataShutdown: @@ -1371,6 +1403,9 @@ func (mc *MetaCache) completeDirectoryBuildNow(ctx context.Context, dirPath util if state == nil { return nil } + if state.discarded { + return ErrDirectoryBuildDiscarded + } // The listing covered every child at its snapshot, so one directory floor // versions them all — a child only needs its own record once a later event diff --git a/weed/mount/meta_cache/meta_cache_discard_test.go b/weed/mount/meta_cache/meta_cache_discard_test.go new file mode 100644 index 0000000000..21738f5c1c --- /dev/null +++ b/weed/mount/meta_cache/meta_cache_discard_test.go @@ -0,0 +1,132 @@ +package meta_cache + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc" +) + +func TestDiscardDirectoryBuildsKeepsAnInFlightBuildUnpublished(t *testing.T) { + mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true}) + defer mc.Shutdown() + + dir := util.FullPath("/dir") + if err := mc.BeginDirectoryBuild(context.Background(), dir); err != nil { + t.Fatalf("begin build: %v", err) + } + insertCacheEntry(t, mc, "/dir/old.txt") + + var resets int32 + mc.DiscardDirectoryBuilds(func() { atomic.AddInt32(&resets, 1) }) + err := mc.CompleteDirectoryBuild(context.Background(), dir, 0, nil) + if !errors.Is(err, ErrDirectoryBuildDiscarded) { + t.Fatalf("complete build = %v, want ErrDirectoryBuildDiscarded", err) + } + if mc.IsDirectoryCached(dir) { + t.Fatal("a discarded build must not mark its directory cached") + } + if got := atomic.LoadInt32(&resets); got != 1 { + t.Fatalf("resetFn ran %d times, want once in the apply loop", got) + } + + // A build that begins after the discard publishes as usual. + if err := mc.BeginDirectoryBuild(context.Background(), dir); err != nil { + t.Fatalf("begin second build: %v", err) + } + if err := mc.CompleteDirectoryBuild(context.Background(), dir, 0, nil); err != nil { + t.Fatalf("complete second build: %v", err) + } + if !mc.IsDirectoryCached(dir) { + t.Fatal("a build begun after the discard should be cached") + } +} + +// discardListClient serves a first listing that blocks until released, as one +// read under a grant that is then distrusted, and later listings at once. +type discardListClient struct { + filer_pb.SeaweedFilerClient + first, later []*filer_pb.ListEntriesResponse + entered chan struct{} + release chan struct{} + + mu sync.Mutex + calls int +} + +func (c *discardListClient) ListEntries(ctx context.Context, _ *filer_pb.ListEntriesRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[filer_pb.ListEntriesResponse], error) { + c.mu.Lock() + c.calls++ + call := c.calls + c.mu.Unlock() + if call == 1 { + return &ctxAwareListStream{ctx: ctx, responses: c.first, entered: c.entered, release: c.release}, nil + } + open := make(chan struct{}) + close(open) + return &ctxAwareListStream{ctx: ctx, responses: c.later, entered: make(chan struct{}), release: open}, nil +} + +func listedFile(name string) *filer_pb.ListEntriesResponse { + return &filer_pb.ListEntriesResponse{ + Entry: &filer_pb.Entry{ + Name: name, + Attributes: &filer_pb.FuseAttributes{Crtime: 1, Mtime: 1, FileMode: 0100644, FileSize: 3}, + }, + SnapshotTsNs: 100, + } +} + +func TestEnsureVisitedListsAgainAfterItsBuildIsDiscarded(t *testing.T) { + mc, _, _, _ := newTestMetaCache(t, map[util.FullPath]bool{"/": true}) + defer mc.Shutdown() + + client := &discardListClient{ + first: []*filer_pb.ListEntriesResponse{listedFile("old.txt")}, + later: []*filer_pb.ListEntriesResponse{listedFile("new.txt")}, + entered: make(chan struct{}), + release: make(chan struct{}), + } + visited := make(chan error, 1) + go func() { + visited <- EnsureVisited(context.Background(), mc, &buildFilerAccessor{client: client}, util.FullPath("/dir"), 0) + }() + select { + case <-client.entered: + case <-time.After(10 * time.Second): + t.Fatal("the build never reached the filer listing") + } + + // The grant narrows while the first listing is in flight. + mc.DiscardDirectoryBuilds(nil) + close(client.release) + + select { + case err := <-visited: + if err != nil { + t.Fatalf("EnsureVisited: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("EnsureVisited did not finish") + } + if !mc.IsDirectoryCached("/dir") { + t.Fatal("/dir should be cached from the second listing") + } + if _, _, err := mc.FindEntry(context.Background(), "/dir/old.txt"); err == nil { + t.Fatal("an entry from the discarded listing survived") + } + if _, _, err := mc.FindEntry(context.Background(), "/dir/new.txt"); err != nil { + t.Fatalf("an entry from the second listing is missing: %v", err) + } + client.mu.Lock() + defer client.mu.Unlock() + if client.calls != 2 { + t.Fatalf("listed %d times, want 2", client.calls) + } +} diff --git a/weed/mount/meta_cache/meta_cache_init.go b/weed/mount/meta_cache/meta_cache_init.go index 946086cff0..6abdedbf36 100644 --- a/weed/mount/meta_cache/meta_cache_init.go +++ b/weed/mount/meta_cache/meta_cache_init.go @@ -66,6 +66,10 @@ func EnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClie path := p // capture for closure g.Go(func() error { err := doEnsureVisited(ctx, mc, client, path, maxCacheableEntries) + // A build discarded by a distrust lists the directory again. + for attempt := 1; errors.Is(err, ErrDirectoryBuildDiscarded) && attempt < maxDiscardedBuildRetries; attempt++ { + err = doEnsureVisited(ctx, mc, client, path, maxCacheableEntries) + } var tooLarge *DirectoryTooLargeError if errors.As(err, &tooLarge) && path != dirPath { // An ancestor found oversized just reads through; failing the @@ -85,6 +89,10 @@ func EnsureVisited(ctx context.Context, mc *MetaCache, client filer_pb.FilerClie // (fewer disk syncs). Larger values reduce I/O overhead but increase memory and latency. const batchInsertSize = 100 +// maxDiscardedBuildRetries bounds how often one visit lists a directory whose +// build a distrust discarded. +const maxDiscardedBuildRetries = 3 + const ( emptyRebuildConfirmations = 2 emptyRebuildConfirmDelay = 50 * time.Millisecond diff --git a/weed/mount/meta_cache/meta_cache_subscribe.go b/weed/mount/meta_cache/meta_cache_subscribe.go index fa3bca7236..389f76d9a5 100644 --- a/weed/mount/meta_cache/meta_cache_subscribe.go +++ b/weed/mount/meta_cache/meta_cache_subscribe.go @@ -13,6 +13,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "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" "github.com/seaweedfs/seaweedfs/weed/wdclient" ) @@ -49,6 +50,12 @@ func mergeProcessors(mainProcessor func(resp *filer_pb.SubscribeMetadataResponse } } +// SubscriptionCredentials resolves the bearer of one subscription attempt. It +// is called before each attempt with a context that ends with the attempt, and +// returns the attempt's token source and a channel that, once closed, ends the +// attempt so the next one resubscribes from the checkpoint with a newer token. +type SubscriptionCredentials func(ctx context.Context) (security.FilerTokenSource, <-chan struct{}, error) + // applySubscribedEvent applies one event of the filer's metadata log to the // cache. It fails only to end the subscription, when the cache is closed. func applySubscribedEvent(mc *MetaCache, resp *filer_pb.SubscribeMetadataResponse) error { @@ -91,8 +98,11 @@ var ( // SubscribeMetaEvents keeps the meta cache current by following the filer's // metadata log until ctx is cancelled, the cache is closed, the stream ends // cleanly, or the process exits. Cancelling ctx is how a mount quiesces the -// follow before closing the cache it writes into. -func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32, client filer_pb.FilerClient, lookupFn wdclient.LookupFileIdFunctionType, dir string, lastTsNs int64, skipSelfEvents bool, onRetry func(lastTsNs int64, err error), followers ...*MetadataFollower) error { +// follow before closing the cache it writes into. credentials, when set, +// authorizes each attempt; a resubscribe it asks for resumes at once from the +// checkpoint and is not a gap, so onRetry is not called for it. Nil keeps the +// client's own credentials. +func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32, client filer_pb.FilerClient, lookupFn wdclient.LookupFileIdFunctionType, dir string, lastTsNs int64, skipSelfEvents bool, credentials SubscriptionCredentials, onRetry func(lastTsNs int64, err error), followers ...*MetadataFollower) error { if ctx == nil { ctx = context.Background() } @@ -142,12 +152,31 @@ func SubscribeMetaEvents(ctx context.Context, mc *MetaCache, selfSignature int32 return filer.NewChunkStreamReaderFromLookup(context.Background(), lookupFn, chunks), nil } } - util.RetryUntil("followMetaUpdates", func() error { - if err := ctx.Err(); err != nil { - return fmt.Errorf("%w: %w", pb.ErrStopFollowing, err) + follow := func() error { + attemptCtx, cancel := context.WithCancel(ctx) + defer cancel() + if credentials != nil { + source, refresh, err := credentials(attemptCtx) + if err != nil { + return fmt.Errorf("subscription credentials: %w", err) + } + metadataFollowOption.FilerTokenSource = source + metadataFollowOption.Resubscribe = refresh } - metadataFollowOption.ClientEpoch++ return pb.WithFilerClientFollowMetadata(client, metadataFollowOption, mergeProcessors(processEventFn, followers...)) + } + util.RetryUntil("followMetaUpdates", func() error { + for { + if err := ctx.Err(); err != nil { + return fmt.Errorf("%w: %w", pb.ErrStopFollowing, err) + } + metadataFollowOption.ClientEpoch++ + err := follow() + if credentials == nil || !errors.Is(err, pb.ErrResubscribe) { + return err + } + glog.V(1).Infof("follow metadata updates: resubscribing with a replaced filer token from %v", time.Unix(0, metadataFollowOption.StartTsNs)) + } }, func(err error) bool { // A cancelled context is the common case here, and it does not arrive // wrapped: the stream's own gRPC Canceled status surfaces bare. Without diff --git a/weed/mount/sse_s3_reader.go b/weed/mount/sse_s3_reader.go index c707886fa9..bbea47c99c 100644 --- a/weed/mount/sse_s3_reader.go +++ b/weed/mount/sse_s3_reader.go @@ -26,6 +26,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/pb/master_pb" "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/security" ) var ( @@ -48,7 +49,7 @@ type SSES3Reader struct { // NewSSES3Reader reads through the S3 gateways the filer's masters list for // its filer group. -func NewSSES3Reader(ctx context.Context, bucketPath string, filers []pb.ServerAddress, grpcDialOption grpc.DialOption) (*SSES3Reader, error) { +func NewSSES3Reader(ctx context.Context, bucketPath string, filers []pb.ServerAddress, grpcDialOption grpc.DialOption, filerTokenSource security.FilerTokenSource) (*SSES3Reader, error) { cfg, err := config.LoadDefaultConfig(ctx, config.WithDefaultRegion("us-east-1")) if err != nil { return nil, err @@ -56,17 +57,19 @@ func NewSSES3Reader(ctx context.Context, bucketPath string, filers []pb.ServerAd return &SSES3Reader{ cfg: cfg, endpoints: func(ctx context.Context) ([]string, error) { - return listS3Endpoints(ctx, filers, grpcDialOption) + return listS3Endpoints(ctx, filers, grpcDialOption, filerTokenSource) }, root: bucketPath + "/", bucket: path.Base(bucketPath), }, nil } -func listS3Endpoints(ctx context.Context, filers []pb.ServerAddress, grpcDialOption grpc.DialOption) ([]string, error) { +// listS3Endpoints asks a filer for its masters with the mount's filer token, +// then the masters for the gateways; the master calls carry no filer token. +func listS3Endpoints(ctx context.Context, filers []pb.ServerAddress, grpcDialOption grpc.DialOption, filerTokenSource security.FilerTokenSource) ([]string, error) { var masters []string var filerGroup string - if err := pb.WithOneOfGrpcFilerClients(false, filers, grpcDialOption, nil, func(client filer_pb.SeaweedFilerClient) error { + if err := pb.WithOneOfGrpcFilerClients(false, filers, grpcDialOption, filerTokenSource, func(client filer_pb.SeaweedFilerClient) error { resp, err := client.GetFilerConfiguration(ctx, &filer_pb.GetFilerConfigurationRequest{}) if err != nil { return err diff --git a/weed/mount/sse_s3_reader_test.go b/weed/mount/sse_s3_reader_test.go index 8618f92e59..49ab8594a1 100644 --- a/weed/mount/sse_s3_reader_test.go +++ b/weed/mount/sse_s3_reader_test.go @@ -14,7 +14,7 @@ import ( func gatewayReader(t *testing.T, bucketPath string, endpoints ...string) *SSES3Reader { t.Helper() - reader, err := NewSSES3Reader(context.Background(), bucketPath, nil, nil) + reader, err := NewSSES3Reader(context.Background(), bucketPath, nil, nil, nil) if err != nil { t.Fatal(err) } diff --git a/weed/mount/weedfs.go b/weed/mount/weedfs.go index d82a70e318..28328f3da9 100644 --- a/weed/mount/weedfs.go +++ b/weed/mount/weedfs.go @@ -44,7 +44,11 @@ type Option struct { GrpcDialOption grpc.DialOption FilerSigningKey security.SigningKey FilerSigningExpiresAfterSec int - FilerMountRootPath string + // FilerTokenSource, when set, authorizes every filer gRPC call, stream + // opening and subscription of this mount; nil keeps the connection's own + // credentials. It is never sent to master, volume or peer mount services. + FilerTokenSource security.FilerTokenSource + FilerMountRootPath string // VolumeReadAuth reads chunks with the exact-fid read tokens the filer // returns from LookupDirectoryEntries instead of signing them locally. VolumeReadAuth bool @@ -274,11 +278,9 @@ func NewSeaweedFileSystem(option *Option) *WFS { // Create FilerClient for efficient volume location caching // Pass all filer addresses for high availability with automatic failover // Configure URL preference based on VolumeServerAccess option - var opts *wdclient.FilerClientOption + opts := &wdclient.FilerClientOption{FilerTokenSource: option.FilerTokenSource} if option.VolumeServerAccess == "publicUrl" { - opts = &wdclient.FilerClientOption{ - UrlPreference: wdclient.PreferPublicUrl, - } + opts.UrlPreference = wdclient.PreferPublicUrl } filerClient = wdclient.NewFilerClient( @@ -336,6 +338,7 @@ func NewSeaweedFileSystem(option *Option) *WFS { if option.EnableDistributedLock && !option.WritebackCache && len(option.FilerAddresses) > 0 { wfs.lockClient = cluster.NewLockClient(option.GrpcDialOption, option.FilerAddresses[0]) + wfs.lockClient.TokenSource = option.FilerTokenSource glog.V(0).Infof("distributed lock manager enabled for mount") } else if option.EnableDistributedLock && option.WritebackCache { glog.V(0).Infof("distributed lock manager disabled: writeback cache implies single-writer mode") @@ -442,7 +445,7 @@ func NewSeaweedFileSystem(option *Option) *WFS { option.PeerEnabled = false } else { dial := func(ctx context.Context, addr pb.ServerAddress, fn func(client filer_pb.SeaweedFilerClient) error) error { - return pb.WithGrpcFilerClient(false, 0, addr, option.GrpcDialOption, nil, fn) + return pb.WithGrpcFilerClient(false, 0, addr, option.GrpcDialOption, option.FilerTokenSource, fn) } wfs.peerRegistrar = NewPeerRegistrar(option.FilerAddresses, dial, selfAddr, option.PeerDataCenter, option.PeerRack) if err := wfs.peerRegistrar.Start(context.Background()); err != nil { @@ -566,18 +569,28 @@ func (wfs *WFS) followMetadataUpdates(startTime time.Time, follower *meta_cache. go func() { defer wfs.metaFollowWg.Done() - meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, func(lastTsNs int64, err error) { + meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, startTime.UnixNano(), wfs.option.WritebackCache, wfs.subscriptionCredentials(), func(lastTsNs int64, err error) { glog.Warningf("meta events follow retry from %v: %v", time.Unix(0, lastTsNs), err) - // A subscription gap may have dropped events, so distrust every cached - // listing. Reset the flags first (safe — it never deletes entries), then - // wipe the root's stale children through the apply loop so the delete - // cannot strand a concurrent rebuild cached-but-empty. - wfs.inodeToPath.InvalidateAllChildrenCache() - wfs.purgeDirectoryCache(util.FullPath(wfs.option.FilerMountRootPath)) + // A subscription gap may have dropped events. + wfs.distrustCachedListings() }, follower) }() } +// distrustCachedListings makes every cached listing be read again from the +// filer. It resets the flags first (safe — it never deletes entries). Through +// the apply loop it then discards the directory builds in flight and resets the +// flags again, so no listing read before the distrust is published after it, +// and wipes the root's stale children so the delete cannot strand a concurrent +// rebuild cached-but-empty. Last, the kernel drops its copies too: the events +// that would have dropped them one directory at a time may be missing. +func (wfs *WFS) distrustCachedListings() { + wfs.inodeToPath.InvalidateAllChildrenCache() + wfs.metaCache.DiscardDirectoryBuilds(wfs.inodeToPath.InvalidateAllChildrenCache) + wfs.purgeDirectoryCache(util.FullPath(wfs.option.FilerMountRootPath)) + wfs.invalidateKernelListings() +} + // metadataFollowStopWait bounds the unmount wait for the metadata follow to // unwind. A subscriber stuck in a read against an unreachable filer must not // hold up an unmount; the closed-cache path covers the event it misses. @@ -1146,11 +1159,34 @@ func (wfs *WFS) invalidateKernelDirListing(path util.FullPath) { } // ENOENT is the kernel not holding the inode, ENOSYS a kernel without the // notify; neither is worth a line. - if status := server.InodeNotify(dirInode, 0, -1); status != fuse.OK && status != fuse.ENOENT && status != fuse.ENOSYS { + if status := kernelInodeNotify(server, dirInode); status != fuse.OK && status != fuse.ENOENT && status != fuse.ENOSYS { glog.V(4).Infof("invalidate kernel listing of %s: %v", dir, status) } } +// kernelInodeNotify drops the kernel's cached data and attributes of an +// inode. Tests replace it. +var kernelInodeNotify = func(server *fuse.Server, inode uint64) fuse.Status { + return server.InodeNotify(inode, 0, -1) +} + +// invalidateKernelListings drops the listing the kernel keeps for every +// directory it holds: OpenDir lets it keep listings in the page cache across +// opens, so without a notify it serves them again without asking the mount. +// Must not run on a thread serving a kernel request, for the reasons +// invalidateKernelDirListing gives. +func (wfs *WFS) invalidateKernelListings() { + server := wfs.fuseServer + if server == nil { + return + } + for _, inode := range wfs.inodeToPath.DirectoryInodes() { + if status := kernelInodeNotify(server, inode); status != fuse.OK && status != fuse.ENOENT && status != fuse.ENOSYS { + glog.V(4).Infof("invalidate kernel listing of inode %d: %v", inode, status) + } + } +} + // MountRoot is the filer path this mount is rooted at. Event paths are absolute // on the filer; a front end that addresses files relative to the mount needs it // to translate them. diff --git a/weed/mount/weedfs_file_copy_range.go b/weed/mount/weedfs_file_copy_range.go index ad469a3fc9..f64c500792 100644 --- a/weed/mount/weedfs_file_copy_range.go +++ b/weed/mount/weedfs_file_copy_range.go @@ -225,6 +225,10 @@ func (wfs *WFS) CopyFileRange(cancel <-chan struct{}, in *fuse.CopyFileRangeIn) } func (wfs *WFS) tryServerSideWholeFileCopy(cancel <-chan struct{}, in *fuse.CopyFileRangeIn, fhIn, fhOut *FileHandle) (written uint32, handled bool, code fuse.Status) { + if !wfs.canSignFilerCopy() { + glog.V(4).Infof("server-side copy: skipped (filer token file without a filer signing key)") + return 0, false, fuse.OK + } if err := wfs.checkContentPublication(fhOut, nil); err != nil { glog.V(4).Infof("server-side copy: skipped (%v)", err) return 0, false, fuse.OK @@ -527,6 +531,18 @@ func entryMatchesServerSideWholeFileCopy(copyRequest wholeFileServerCopyRequest, return true } +// canSignFilerCopy reports whether a server-side copy may be tried. A mount +// with a filer token file but no filer signing key would send the filer HTTP +// request unsigned: its token is a gRPC credential. That request is skipped, so +// the copy streams through the chunk path instead of failing as ambiguous. A +// mount without a token file keeps its behaviour, signed or not. +func (wfs *WFS) canSignFilerCopy() bool { + return wfs.option == nil || wfs.option.FilerTokenSource == nil || len(wfs.option.FilerSigningKey) > 0 +} + +// filerCopyJWT signs the filer HTTP request of a server-side copy with the +// filer HTTP key. A mount with only a filer token file holds no such key, so +// it never tries a server-side copy; see canSignFilerCopy. func (wfs *WFS) filerCopyJWT() security.EncodedJwt { if wfs.option == nil || len(wfs.option.FilerSigningKey) == 0 { return "" diff --git a/weed/mount/weedfs_file_copy_range_test.go b/weed/mount/weedfs_file_copy_range_test.go index ac7cfd6bfc..83fcb382ad 100644 --- a/weed/mount/weedfs_file_copy_range_test.go +++ b/weed/mount/weedfs_file_copy_range_test.go @@ -12,6 +12,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/mount/meta_cache" "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" ) @@ -484,3 +485,57 @@ func TestServerSideCopySkipsFencedDestination(t *testing.T) { t.Fatal("fenced destination should fall back to the streaming copy") } } + +func TestServerSideCopyNeedsASigningKeyWithAFilerTokenFile(t *testing.T) { + tokenSource := security.FilerTokenSource(func(context.Context) (security.EncodedJwt, error) { return "t", nil }) + cases := []struct { + name string + tokenSource security.FilerTokenSource + signingKey security.SigningKey + wantTried bool + }{ + {name: "token file without signing key", tokenSource: tokenSource, wantTried: false}, + {name: "token file with signing key", tokenSource: tokenSource, signingKey: security.SigningKey("k"), wantTried: true}, + {name: "no token file, no signing key", wantTried: true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + wfs := newCopyRangeTestWFS() + wfs.option.FilerTokenSource = tc.tokenSource + wfs.option.FilerSigningKey = tc.signingKey + srcInode := wfs.inodeToPath.Lookup(util.FullPath("/src.txt"), 1, false, false, 0, true) + dstInode := wfs.inodeToPath.Lookup(util.FullPath("/dst.txt"), 1, false, false, 0, true) + srcHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, srcInode, &filer_pb.Entry{ + Name: "src.txt", + Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: 5, Inode: srcInode}, + Content: []byte("hello"), + }, 0, 0) + dstHandle, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, dstInode, &filer_pb.Entry{ + Name: "dst.txt", + Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: dstInode}, + }, 0, 0) + srcHandle.RememberPath("/src.txt") + dstHandle.RememberPath("/dst.txt") + + tried := false + originalCopy := performServerSideWholeFileCopy + t.Cleanup(func() { performServerSideWholeFileCopy = originalCopy }) + performServerSideWholeFileCopy = func(<-chan struct{}, *WFS, wholeFileServerCopyRequest) (*filer_pb.Entry, entryVersion, serverSideWholeFileCopyOutcome, error) { + tried = true + return nil, entryVersion{}, serverSideWholeFileCopyNotCommitted, errors.New("stub") + } + + _, handled, status := wfs.tryServerSideWholeFileCopy(make(chan struct{}), &fuse.CopyFileRangeIn{ + FhIn: uint64(srcHandle.fh), + FhOut: uint64(dstHandle.fh), + Len: 8, + }, srcHandle, dstHandle) + if tried != tc.wantTried { + t.Fatalf("server-side copy tried=%v, want %v", tried, tc.wantTried) + } + if handled || status != fuse.OK { + t.Fatalf("handled=%v status=%v, want a fallback to the streaming copy", handled, status) + } + }) + } +} diff --git a/weed/mount/weedfs_filer_token.go b/weed/mount/weedfs_filer_token.go new file mode 100644 index 0000000000..3c144e9f94 --- /dev/null +++ b/weed/mount/weedfs_filer_token.go @@ -0,0 +1,78 @@ +package mount + +import ( + "context" + "time" + + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/mount/meta_cache" + "github.com/seaweedfs/seaweedfs/weed/security" +) + +// filerTokenPollInterval is how often an open metadata subscription checks +// its token source for a replacement. Tests shorten it. +var filerTokenPollInterval = time.Second + +// subscriptionCredentials opens each metadata subscription attempt with the +// token current at that moment, and ends the attempt once the source holds a +// different one, so the follow resubscribes from its checkpoint instead of +// running on with the old token until the filer ends the stream at expiry. A +// replacement must therefore reach the file before the old token expires; +// without one, the filer's end of the stream takes the gap path as before. +// +// Cached listings survive a replacement whose grant covers the old one. When +// the new token may show less, or either cannot be decoded, they are +// distrusted as after a gap, the kernel's copies included, so no listing the +// old grant showed outlives it. +// A readdir already under way on an open handle finishes from what it read. +// Nil without a token source. +func (wfs *WFS) subscriptionCredentials() meta_cache.SubscriptionCredentials { + source := wfs.option.FilerTokenSource + if source == nil { + return nil + } + // Attempts run one at a time, on the subscription goroutine. + var previous security.EncodedJwt + return func(ctx context.Context) (security.FilerTokenSource, <-chan struct{}, error) { + token, err := source(ctx) + if err != nil { + return nil, nil, err + } + if previous != "" && !security.FilerTokenGrantCovers(previous, token) { + glog.V(0).Infof("filer token grant may have narrowed: reading cached listings again") + wfs.distrustCachedListings() + } + previous = token + refresh := make(chan struct{}) + go watchFilerToken(ctx, source, token, refresh) + return func(context.Context) (security.EncodedJwt, error) { return token, nil }, refresh, nil + } +} + +// watchFilerToken closes refresh once source holds a token other than token. +// A failed read leaves the open stream alone: its authority was fixed when it +// opened, and the next attempt fails closed if the file is still unreadable. +func watchFilerToken(ctx context.Context, source security.FilerTokenSource, token security.EncodedJwt, refresh chan<- struct{}) { + ticker := time.NewTicker(filerTokenPollInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if current, err := source(ctx); err == nil && current != token { + close(refresh) + return + } + } + } +} + +// filerTokenExpiry is when token expires by its own claims, zero when it does +// not say or cannot be decoded. +func filerTokenExpiry(token security.EncodedJwt) time.Time { + if claims, ok := security.FilerTokenClaims(token); ok && claims.ExpiresAt != nil { + return claims.ExpiresAt.Time + } + return time.Time{} +} diff --git a/weed/mount/weedfs_filer_token_test.go b/weed/mount/weedfs_filer_token_test.go new file mode 100644 index 0000000000..fa28c8aff5 --- /dev/null +++ b/weed/mount/weedfs_filer_token_test.go @@ -0,0 +1,229 @@ +package mount + +import ( + "context" + "crypto/rand" + "encoding/hex" + "path/filepath" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/seaweedfs/go-fuse/v2/fuse" + "google.golang.org/grpc/metadata" + + "github.com/seaweedfs/seaweedfs/weed/mount/meta_cache" + "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" +) + +type subscription struct { + token string + sinceNs int64 +} + +// tokenSubscriberFiler reports every subscription it receives. The first one +// is sent event, then every subscription stays open until the mount ends it. +type tokenSubscriberFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + event atomic.Pointer[filer_pb.SubscribeMetadataResponse] + subscribed chan subscription +} + +func (s *tokenSubscriberFiler) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error { + md, _ := metadata.FromIncomingContext(stream.Context()) + s.subscribed <- subscription{token: joinAuthorization(md), sinceNs: req.SinceNs} + if event := s.event.Swap(nil); event != nil { + if err := stream.Send(event); err != nil { + return err + } + } + <-stream.Context().Done() + return stream.Context().Err() +} + +func randomFilerKey(t *testing.T) security.SigningKey { + t.Helper() + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + t.Fatal(err) + } + return security.SigningKey(hex.EncodeToString(b)) +} + +func nextSubscription(t *testing.T, subscribed <-chan subscription) subscription { + t.Helper() + select { + case s := <-subscribed: + return s + case <-time.After(10 * time.Second): + t.Fatal("no subscription arrived") + return subscription{} + } +} + +// kernelNotifies records the inodes passed to kernelInodeNotify. +type kernelNotifies struct { + mu sync.Mutex + inodes []uint64 +} + +func recordKernelNotifies(t *testing.T) *kernelNotifies { + t.Helper() + n := &kernelNotifies{} + old := kernelInodeNotify + kernelInodeNotify = func(_ *fuse.Server, inode uint64) fuse.Status { + n.mu.Lock() + n.inodes = append(n.inodes, inode) + n.mu.Unlock() + return fuse.OK + } + t.Cleanup(func() { kernelInodeNotify = old }) + return n +} + +func (n *kernelNotifies) since(mark int) []uint64 { + n.mu.Lock() + defer n.mu.Unlock() + return append([]uint64(nil), n.inodes[mark:]...) +} + +func (n *kernelNotifies) count() int { + n.mu.Lock() + defer n.mu.Unlock() + return len(n.inodes) +} + +// A replaced token ends the subscription and the follow resubscribes with it +// from the last applied event. Cached listings stay while the new grant covers +// the old one, and are read again when it may not, both the mount's own and +// those the kernel keeps for the directories it holds. +func TestMetadataSubscriptionResubscribesWithReplacedToken(t *testing.T) { + oldInterval := filerTokenPollInterval + filerTokenPollInterval = 10 * time.Millisecond + t.Cleanup(func() { filerTokenPollInterval = oldInterval }) + + key := randomFilerKey(t) + scoped := func(id string, prefixes ...string) security.EncodedJwt { + return security.GenJwtForFilerScope(key, time.Hour, id, prefixes, nil) + } + tests := []struct { + name string + next security.EncodedJwt + wantKeep bool + }{ + {name: "renewed, same grant", next: scoped("renewed", "/"), wantKeep: true}, + {name: "broader grant", next: security.GenJwtForFilerAdmin(key, 3600), wantKeep: true}, + {name: "narrowed grant", next: scoped("narrowed", "/dir/sub"), wantKeep: false}, + {name: "undecodable", next: "opaque-token", wantKeep: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + wfs, _ := newMetaSubscriberMount(t) + notifies := recordKernelNotifies(t) + wfs.fuseServer = &fuse.Server{} + event := createdEvent("a") + fake := &tokenSubscriberFiler{subscribed: make(chan subscription, 4)} + fake.event.Store(event) + wfs.option.FilerAddresses = []pb.ServerAddress{listenFiler(t, fake)} + path := filepath.Join(t.TempDir(), "token") + first := scoped("first", "/") + writeMountTokenFile(t, path, string(first)) + wfs.option.FilerTokenSource = security.FilerTokenFile(path) + + root, dir := util.FullPath("/"), util.FullPath("/dir") + wfs.inodeToPath.MarkChildrenCached(root) + dirInode := wfs.inodeToPath.Lookup(dir, time.Now().Unix(), true, false, 0, false) + wfs.inodeToPath.MarkChildrenCached(dir) + rootInode, _ := wfs.inodeToPath.GetInode(root) + + follower := &meta_cache.MetadataFollower{ + PathPrefixToWatch: "/etc/seaweedfs/", + ProcessEventFn: func(*filer_pb.SubscribeMetadataResponse) error { return nil }, + } + wfs.followMetadataUpdates(time.Unix(0, 1), follower) + t.Cleanup(func() { + wfs.stopMetadataFollow() + wfs.metaCache.Shutdown() + }) + + if got := nextSubscription(t, fake.subscribed); got.token != "Bearer "+string(first) || got.sinceNs != 1 { + t.Fatalf("first subscription = %+v", got) + } + deadline := time.Now().Add(10 * time.Second) + for { + if entry, _, _ := wfs.metaCache.FindEntry(context.Background(), dir.Child("a")); entry != nil { + break + } + if time.Now().After(deadline) { + t.Fatal("the event was never applied") + } + time.Sleep(10 * time.Millisecond) + } + + mark := notifies.count() + writeMountTokenFile(t, path, string(tt.next)) + got := nextSubscription(t, fake.subscribed) + if got.token != "Bearer "+string(tt.next) { + t.Fatal("resubscription did not present the replaced token") + } + if got.sinceNs != event.TsNs { + t.Fatalf("resubscribed from %d, want the applied event's %d", got.sinceNs, event.TsNs) + } + if kept := wfs.inodeToPath.IsChildrenCached(dir); kept != tt.wantKeep { + t.Fatalf("cached listing kept = %v, want %v", kept, tt.wantKeep) + } + notified := notifies.since(mark) + if tt.wantKeep { + if len(notified) != 0 { + t.Fatalf("kernel listings dropped for inodes %v, want none", notified) + } + } else if !slices.Contains(notified, rootInode) || !slices.Contains(notified, dirInode) { + t.Fatalf("kernel listings dropped for inodes %v, want root %d and dir %d", notified, rootInode, dirInode) + } + select { + case extra := <-fake.subscribed: + t.Fatalf("unexpected further subscription %+v", extra) + case <-time.After(100 * time.Millisecond): + } + }) + } +} + +// An unchanged token file never ends an open subscription. +func TestMetadataSubscriptionKeepsStreamWhileTokenUnchanged(t *testing.T) { + oldInterval := filerTokenPollInterval + filerTokenPollInterval = 10 * time.Millisecond + t.Cleanup(func() { filerTokenPollInterval = oldInterval }) + + wfs, _ := newMetaSubscriberMount(t) + fake := &tokenSubscriberFiler{subscribed: make(chan subscription, 4)} + wfs.option.FilerAddresses = []pb.ServerAddress{listenFiler(t, fake)} + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "steady-token") + wfs.option.FilerTokenSource = security.FilerTokenFile(path) + follower := &meta_cache.MetadataFollower{ + PathPrefixToWatch: "/etc/seaweedfs/", + ProcessEventFn: func(*filer_pb.SubscribeMetadataResponse) error { return nil }, + } + wfs.followMetadataUpdates(time.Now(), follower) + t.Cleanup(func() { + wfs.stopMetadataFollow() + wfs.metaCache.Shutdown() + }) + + if got := nextSubscription(t, fake.subscribed); got.token != "Bearer steady-token" { + t.Fatalf("subscription token = %q", got.token) + } + // Rewriting the same token is not a replacement. + writeMountTokenFile(t, path, "steady-token") + select { + case extra := <-fake.subscribed: + t.Fatalf("subscription reopened without a token change: %+v", extra) + case <-time.After(300 * time.Millisecond): + } +} diff --git a/weed/mount/weedfs_meta_subscribe_shutdown_test.go b/weed/mount/weedfs_meta_subscribe_shutdown_test.go index e5a6a3ee04..afcee29b5e 100644 --- a/weed/mount/weedfs_meta_subscribe_shutdown_test.go +++ b/weed/mount/weedfs_meta_subscribe_shutdown_test.go @@ -180,7 +180,7 @@ func runMetaSubscriberAfterClose(t *testing.T) { defer close(stopped) // nil lookupFn: the filer streams decoded events, so the apply path is // reached without any volume server. - meta_cache.SubscribeMetaEvents(context.Background(), wfs.metaCache, wfs.signature, wfs, nil, "/", 0, false, nil) + meta_cache.SubscribeMetaEvents(context.Background(), wfs.metaCache, wfs.signature, wfs, nil, "/", 0, false, nil, nil) }() select { @@ -290,7 +290,7 @@ func TestMountMetaFollowCancelIsAStop(t *testing.T) { var retries atomic.Int32 go func() { defer close(joined) - stopped <- meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, nil, "/", 0, false, + stopped <- meta_cache.SubscribeMetaEvents(ctx, wfs.metaCache, wfs.signature, wfs, nil, "/", 0, false, nil, func(int64, error) { retries.Add(1) }) }() t.Cleanup(func() { diff --git a/weed/mount/weedfs_meta_subscribe_test.go b/weed/mount/weedfs_meta_subscribe_test.go index fca8d84a3a..ecbe43cce3 100644 --- a/weed/mount/weedfs_meta_subscribe_test.go +++ b/weed/mount/weedfs_meta_subscribe_test.go @@ -9,12 +9,16 @@ import ( "net/http/httptest" "net/url" "path/filepath" + "slices" "sync/atomic" "testing" "time" + "github.com/seaweedfs/go-fuse/v2/fuse" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweedfs/weed/mount/meta_cache" @@ -189,7 +193,7 @@ func testMountMetadataReplayAuthorization(t *testing.T, access string, readAuth followed := make(chan struct{}) go func() { defer close(followed) - meta_cache.SubscribeMetaEvents(context.Background(), wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, 0, false, nil) + meta_cache.SubscribeMetaEvents(context.Background(), wfs.metaCache, wfs.signature, wfs, wfs.metadataLogLookupFn(), wfs.option.FilerMountRootPath, 0, false, nil, nil) }() select { @@ -220,3 +224,61 @@ func testMountMetadataReplayAuthorization(t *testing.T, access string, readAuth t.Errorf("replayed file size %d, want 7", entry.Attr.FileSize) } } + +// gapFilerServer breaks the first subscription, losing whatever it would have +// sent, and holds every later one open. +type gapFilerServer struct { + filer_pb.UnimplementedSeaweedFilerServer + attempts atomic.Int32 + resumed chan struct{} +} + +func (s *gapFilerServer) SubscribeMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeMetadataServer) error { + if s.attempts.Add(1) == 1 { + return status.Error(codes.Internal, "stream broken") + } + select { + case s.resumed <- struct{}{}: + default: + } + <-stream.Context().Done() + return stream.Context().Err() +} + +// After a subscription gap the kernel's cached listings go along with the +// mount's: the events that would have dropped them may be among those missed. +func TestSubscriptionGapDropsKernelListings(t *testing.T) { + wfs, _ := newMetaSubscriberMount(t) + notifies := recordKernelNotifies(t) + wfs.fuseServer = &fuse.Server{} + fake := &gapFilerServer{resumed: make(chan struct{}, 1)} + wfs.option.FilerAddresses = []pb.ServerAddress{listenFiler(t, fake)} + + root, dir := util.FullPath("/"), util.FullPath("/dir") + dirInode := wfs.inodeToPath.Lookup(dir, time.Now().Unix(), true, false, 0, false) + wfs.inodeToPath.MarkChildrenCached(dir) + rootInode, _ := wfs.inodeToPath.GetInode(root) + + follower := &meta_cache.MetadataFollower{ + PathPrefixToWatch: "/etc/seaweedfs/", + ProcessEventFn: func(*filer_pb.SubscribeMetadataResponse) error { return nil }, + } + wfs.followMetadataUpdates(time.Unix(0, 1), follower) + t.Cleanup(func() { + wfs.stopMetadataFollow() + wfs.metaCache.Shutdown() + }) + + select { + case <-fake.resumed: + case <-time.After(10 * time.Second): + t.Fatal("the follow never resubscribed after the gap") + } + if wfs.inodeToPath.IsChildrenCached(dir) { + t.Fatal("cached listing survived the gap") + } + notified := notifies.since(0) + if !slices.Contains(notified, rootInode) || !slices.Contains(notified, dirInode) { + t.Fatalf("kernel listings dropped for inodes %v, want root %d and dir %d", notified, rootInode, dirInode) + } +} diff --git a/weed/mount/weedfs_stream_mutate.go b/weed/mount/weedfs_stream_mutate.go index b3bba4aed2..a5fe00c605 100644 --- a/weed/mount/weedfs_stream_mutate.go +++ b/weed/mount/weedfs_stream_mutate.go @@ -13,6 +13,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/glog" "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" grpcMetadata "google.golang.org/grpc/metadata" @@ -50,7 +51,7 @@ var ErrStreamTransport = errors.New("stream transport error") type streamMutateMux struct { wfs *WFS - mu sync.Mutex // protects stream, cancel, grpcConn, closed, stopSend, generation + mu sync.Mutex // protects the fields below, up to draining stream filer_pb.SeaweedFiler_StreamMutateEntryClient cancel context.CancelFunc grpcConn *grpc.ClientConn // dedicated connection, closed on stream teardown @@ -58,8 +59,24 @@ type streamMutateMux struct { closed bool disabled bool // permanently disabled if filer doesn't support the RPC stopSend chan struct{} // closed to signal the current sendLoop to exit + sendDone chan struct{} // closed when the current sendLoop has exited generation uint64 // incremented each time a new stream is created + // A stream keeps the filer token it opened with. token and expiresAt + // (zero when unknown) describe it; a replaced or expiring token retires + // the stream before a successor opens (see retireLocked). active counts + // requests admitted to the current generation and not yet released; + // idle is closed when it reaches zero during a retirement, and draining + // is non-nil while one runs. retireCancel cancels the retiring stream, + // for Close and for a waiter that gives up on it. + token security.EncodedJwt + expiresAt time.Time + active int + idle chan struct{} + draining chan struct{} + retireCancel context.CancelFunc + received atomic.Uint64 // responses received, on any generation + nextID atomic.Uint64 // pending maps request_id → response channel. The recvLoop dispatches @@ -165,10 +182,14 @@ func (m *streamMutateMux) DeleteEntry(ctx context.Context, req *filer_pb.DeleteE // response events until is_last=true. The callback is invoked for each // intermediate rename event (same as the current StreamRenameEntry recv loop). func (m *streamMutateMux) Rename(ctx context.Context, req *filer_pb.StreamRenameEntryRequest, onEvent func(*filer_pb.StreamRenameEntryResponse) error) error { - gen, err := m.ensureStream() + gen, expiresAt, err := m.ensureStream(ctx) if err != nil { + if ctx.Err() != nil && errors.Is(err, ctx.Err()) { + return err + } return fmt.Errorf("%w: %v", ErrStreamTransport, err) } + defer m.release(gen) id := m.nextID.Add(1) ch := make(chan *filer_pb.StreamMutateEntryResponse, 64) @@ -211,7 +232,7 @@ func (m *streamMutateMux) Rename(ctx context.Context, req *filer_pb.StreamRename select { case resp, ok := <-ch: if !ok { - return fmt.Errorf("rename recv: %w: stream closed", ErrStreamTransport) + return m.lostReply(expiresAt, fmt.Errorf("rename recv: %w: stream closed", ErrStreamTransport)) } // Applying an event can legitimately outlast the silence bound — // a directory rename migrates an open child's DLM lock under @@ -242,7 +263,7 @@ func (m *streamMutateMux) Rename(ctx context.Context, req *filer_pb.StreamRename respTimer.Reset(m.wfs.filerRPCWait()) case <-respTimer.C: m.teardownStream(gen) - return fmt.Errorf("rename recv: %w: timed out", ErrStreamTransport) + return m.lostReply(expiresAt, fmt.Errorf("rename recv: %w: timed out", ErrStreamTransport)) case <-ctx.Done(): return ctx.Err() } @@ -251,10 +272,14 @@ func (m *streamMutateMux) Rename(ctx context.Context, req *filer_pb.StreamRename // doUnary sends a single-response request and waits for the reply. func (m *streamMutateMux) doUnary(ctx context.Context, req *filer_pb.StreamMutateEntryRequest) (*filer_pb.StreamMutateEntryResponse, error) { - gen, err := m.ensureStream() + gen, expiresAt, err := m.ensureStream(ctx) if err != nil { + if ctx.Err() != nil && errors.Is(err, ctx.Err()) { + return nil, err + } return nil, fmt.Errorf("%w: %v", ErrStreamTransport, err) } + defer m.release(gen) id := m.nextID.Add(1) req.RequestId = id @@ -296,7 +321,7 @@ func (m *streamMutateMux) doUnary(ctx context.Context, req *filer_pb.StreamMutat case resp, ok := <-ch: respTimer.Stop() if !ok { - return nil, fmt.Errorf("%w: stream closed", ErrStreamTransport) + return nil, m.lostReply(expiresAt, fmt.Errorf("%w: stream closed", ErrStreamTransport)) } // A failed create still carries a structured error code in its nested // CreateEntryResponse, so hand that back for CreateEntry to unwrap and @@ -311,71 +336,276 @@ func (m *streamMutateMux) doUnary(ctx context.Context, req *filer_pb.StreamMutat return resp, nil case <-respTimer.C: m.teardownStream(gen) - return nil, fmt.Errorf("%w: response timed out", ErrStreamTransport) + return nil, m.lostReply(expiresAt, fmt.Errorf("%w: response timed out", ErrStreamTransport)) case <-ctx.Done(): respTimer.Stop() return nil, ctx.Err() } } -// ensureStream opens the bidi stream if not already open. It returns the -// stream generation so callers can tag outgoing requests. -func (m *streamMutateMux) ensureStream() (uint64, error) { +// ensureStream opens the bidi stream if not already open and admits one +// request to it. It returns the stream generation so callers can tag outgoing +// requests, and when the stream's token expires (zero when unknown); the +// caller releases its admission with release(gen) once it stops waiting for +// that request's replies. A caller whose ctx ends while a retiring stream +// drains returns ctx's error unadmitted; the retirement carries on. +func (m *streamMutateMux) ensureStream(ctx context.Context) (uint64, time.Time, error) { m.mu.Lock() defer m.mu.Unlock() - if m.closed { - return 0, fmt.Errorf("stream mux is closed") - } - if m.disabled { - return 0, fmt.Errorf("StreamMutateEntry not supported by filer") - } - if m.stream != nil { - return m.generation, nil - } - - // Wait for prior generation's recvLoop to fully tear down before opening - // a new stream. This guarantees all pending waiters from the old stream - // have been failed before we create a new generation. - if m.recvDone != nil { - done := m.recvDone - m.mu.Unlock() - <-done - m.mu.Lock() - // Re-check after reacquiring the lock. + for { if m.closed { - return 0, fmt.Errorf("stream mux is closed") + return 0, time.Time{}, fmt.Errorf("stream mux is closed") } if m.disabled { - return 0, fmt.Errorf("StreamMutateEntry not supported by filer") + return 0, time.Time{}, fmt.Errorf("StreamMutateEntry not supported by filer") + } + // A retiring stream admits nothing; its successor opens after it. + if draining := m.draining; draining != nil { + m.mu.Unlock() + select { + case <-draining: + case <-ctx.Done(): + m.mu.Lock() + return 0, time.Time{}, ctx.Err() + } + m.mu.Lock() + continue } if m.stream != nil { - return m.generation, nil + retire, err := m.mustRetireLocked() + if err != nil { + return 0, time.Time{}, err + } + if !retire { + m.active++ + return m.generation, m.expiresAt, nil + } + m.retireLocked() + continue + } + // Wait for prior generation's recvLoop to fully tear down before + // opening a new stream. This guarantees all pending waiters from the + // old stream have been failed before we create a new generation. + if done := m.recvDone; done != nil { + select { + case <-done: + default: + m.mu.Unlock() + <-done + m.mu.Lock() + continue + } + } + // A new stream is admitted through the checks above like an open one: + // the token file may have been replaced, or the token neared expiry, + // while it opened. + if err := m.openLocked(); err != nil { + return 0, time.Time{}, err } } +} +// openLocked opens a stream with the current filer token and starts its loops, +// with no request admitted yet. Called with mu held. +func (m *streamMutateMux) openLocked() error { + token, expiresAt, err := m.streamToken() + if err != nil { + return err + } var stream filer_pb.SeaweedFiler_StreamMutateEntryClient - err := m.openStream(&stream) + err = m.openStream(&stream, token) if err != nil { if s, ok := status.FromError(err); ok && s.Code() == codes.Unimplemented { m.disabled = true glog.V(0).Infof("filer does not support StreamMutateEntry, falling back to unary RPCs") } - return 0, err + return err } - - m.generation++ - m.stream = stream - m.stopSend = make(chan struct{}) - recvDone := make(chan struct{}) - m.recvDone = recvDone - gen := m.generation - go m.sendLoop(stream, m.stopSend, gen) - go m.recvLoop(stream, gen, recvDone) - return gen, nil + m.startLocked(stream, token, expiresAt) + return nil } -func (m *streamMutateMux) openStream(out *filer_pb.SeaweedFiler_StreamMutateEntryClient) error { +// startLocked makes stream, opened with token, the current generation and +// starts its loops. Called with mu held. +func (m *streamMutateMux) startLocked(stream filer_pb.SeaweedFiler_StreamMutateEntryClient, token security.EncodedJwt, expiresAt time.Time) { + m.generation++ + m.stream = stream + m.token, m.expiresAt = token, expiresAt + m.active = 0 + m.stopSend = make(chan struct{}) + m.sendDone = make(chan struct{}) + recvDone := make(chan struct{}) + m.recvDone = recvDone + go m.sendLoop(stream, m.stopSend, m.sendDone, m.generation, expiresAt) + go m.recvLoop(stream, m.generation, recvDone) +} + +// release ends one request's admission to generation gen. +func (m *streamMutateMux) release(gen uint64) { + m.mu.Lock() + defer m.mu.Unlock() + if gen != m.generation || m.active == 0 { + return + } + m.active-- + if m.active == 0 && m.idle != nil { + close(m.idle) + m.idle = nil + } +} + +// streamToken resolves the filer token a new stream opens with. The stream +// keeps it for its whole life, so a token that would expire before a request +// sent now could be answered is refused: the caller's unary fallback, which +// the filer checks when each call starts, is safe where the stream is not. +func (m *streamMutateMux) streamToken() (security.EncodedJwt, time.Time, error) { + source := m.wfs.option.FilerTokenSource + if source == nil { + return "", time.Time{}, nil + } + token, err := source(context.Background()) + if err != nil { + return "", time.Time{}, err + } + expiresAt := filerTokenExpiry(token) + if m.tokenExpiring(expiresAt) { + return "", time.Time{}, fmt.Errorf("filer token expires within %v", m.wfs.filerRPCWait()) + } + return token, expiresAt, nil +} + +// tokenExpiring reports whether a stream token expiring at expiresAt (zero +// when unknown) has filerRPCWait or less left, so that a reply to a request +// sent now might come after the filer stops answering on that stream. +func (m *streamMutateMux) tokenExpiring(expiresAt time.Time) bool { + return !expiresAt.IsZero() && !time.Now().Add(m.wfs.filerRPCWait()).Before(expiresAt) +} + +// lostReply returns err, the transport error for a sent request whose reply +// never came, unless the stream's token is about to expire or has expired. +// The filer may then have applied the request and refused to send its reply, +// so the outcome is unknown: the request is reported as failed with EIO, +// which callers do not resend over the unary path. +func (m *streamMutateMux) lostReply(expiresAt time.Time, err error) error { + if !m.tokenExpiring(expiresAt) { + return err + } + return &streamMutateError{ + msg: fmt.Sprintf("%v near filer token expiry; the filer may have applied it", err), + errno: syscall.EIO, + } +} + +// mustRetireLocked reports whether the open stream must stop admitting +// requests: the token source now holds another token, or the stream's own +// token would expire before a request sent now could be answered. The filer +// refuses to send on a scoped stream once its token has expired, so a request +// it applied at that moment would lose its reply. A source that cannot be +// read fails the request. +func (m *streamMutateMux) mustRetireLocked() (bool, error) { + source := m.wfs.option.FilerTokenSource + if source == nil { + return false, nil + } + token, err := source(context.Background()) + if err != nil { + return false, err + } + if token != m.token { + return true, nil + } + return m.tokenExpiring(m.expiresAt), nil +} + +// retireLocked ends the current stream so a successor can open with a new +// token. It stops admitting requests and, in the background, waits for the +// admitted ones to be answered, half-closes the stream so the filer finishes +// it, and waits for the receive loop to end; m.draining closes when that is +// done. Running it in the background lets a request that triggered or waits +// for the retirement give up on its own context without cutting the admitted +// requests short. A wait gives up only after filerRPCWait without a response, +// as a waiter's own timer does, so a long rename that keeps answering is not +// cut short; the stream is then cancelled instead of closed. Nothing is resent +// here: a request still unanswered when the wait gives up fails as on a lost +// stream. Close cancels the stream through m.retireCancel instead of waiting. +// Called with mu held; returns with mu held and no stream open. +func (m *streamMutateMux) retireLocked() { + draining := make(chan struct{}) + m.draining = draining + stream, cancel, conn := m.stream, m.cancel, m.grpcConn + stopSend, sendDone, recvDone := m.stopSend, m.sendDone, m.recvDone + // The generation is this retirement's to end: teardownStream sees no + // stream and only cancels it, and the filer index stays where it is. + m.stream, m.cancel, m.grpcConn, m.stopSend = nil, nil, nil, nil + m.retireCancel = cancel + var idle chan struct{} + if m.active > 0 { + idle = make(chan struct{}) + m.idle = idle + } + + go func() { + wait := m.wfs.filerRPCWait() + quiet := idle == nil || m.waitWhileAnswering(idle) + close(stopSend) + if quiet { + // CloseSend must not race the send loop's Send. + select { + case <-sendDone: + case <-time.After(wait): + quiet = false + } + } + if !quiet { + cancel() + } + <-sendDone + if quiet { + stream.CloseSend() + m.waitWhileAnswering(recvDone) + } + cancel() + <-recvDone + if conn != nil { + conn.Close() + } + + m.mu.Lock() + defer m.mu.Unlock() + m.idle = nil + m.draining = nil + m.retireCancel = nil + close(draining) + }() +} + +// waitWhileAnswering waits for done until filerRPCWait passes without a +// response arriving, and reports whether done closed. +func (m *streamMutateMux) waitWhileAnswering(done <-chan struct{}) bool { + wait := m.wfs.filerRPCWait() + timer := time.NewTimer(wait) + defer timer.Stop() + last := m.received.Load() + for { + select { + case <-done: + return true + case <-timer.C: + current := m.received.Load() + if current == last { + return false + } + last = current + timer.Reset(wait) + } + } +} + +// openStream dials the first filer that accepts the stream, opening it with +// token (none when empty). +func (m *streamMutateMux) openStream(out *filer_pb.SeaweedFiler_StreamMutateEntryClient, token security.EncodedJwt) error { + streamToken := func(context.Context) (security.EncodedJwt, error) { return token, nil } i := atomic.LoadInt32(&m.wfs.option.filerIndex) n := int32(len(m.wfs.option.FilerAddresses)) var lastErr error @@ -394,7 +624,7 @@ func (m *streamMutateMux) openStream(out *filer_pb.SeaweedFiler_StreamMutateEntr continue } - client := filer_pb.NewSeaweedFilerClient(grpcConn) + client := filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(grpcConn, streamToken)) streamCtx, cancel := context.WithCancel(ctx) stream, err := client.StreamMutateEntry(streamCtx) if err != nil { @@ -418,7 +648,10 @@ func (m *streamMutateMux) openStream(out *filer_pb.SeaweedFiler_StreamMutateEntr return lastErr } -func (m *streamMutateMux) sendLoop(stream filer_pb.SeaweedFiler_StreamMutateEntryClient, stop <-chan struct{}, gen uint64) { +// sendLoop sends the requests queued for generation gen, whose token expires +// at expiresAt (zero when unknown). +func (m *streamMutateMux) sendLoop(stream filer_pb.SeaweedFiler_StreamMutateEntryClient, stop <-chan struct{}, done chan<- struct{}, gen uint64, expiresAt time.Time) { + defer close(done) defer m.drainSendCh() for { select { @@ -430,6 +663,14 @@ func (m *streamMutateMux) sendLoop(stream filer_pb.SeaweedFiler_StreamMutateEntr req.errCh <- fmt.Errorf("%w: stream generation mismatch", ErrStreamTransport) continue } + // A request admitted with the token's margin may have waited here + // until the margin was gone; its reply could then be refused. Not + // sending it lets it go out over unary, which is safe because the + // filer never saw it. + if m.tokenExpiring(expiresAt) { + req.errCh <- fmt.Errorf("%w: filer token expires within %v, not sent", ErrStreamTransport, m.wfs.filerRPCWait()) + continue + } err := stream.Send(req.req) req.errCh <- err if err != nil { @@ -456,6 +697,7 @@ func (m *streamMutateMux) recvLoop(stream filer_pb.SeaweedFiler_StreamMutateEntr m.teardownStream(gen) return } + m.received.Add(1) if ch, ok := m.pending.Load(resp.RequestId); ok { ch.(chan *filer_pb.StreamMutateEntryResponse) <- resp @@ -471,6 +713,12 @@ func (m *streamMutateMux) recvLoop(stream filer_pb.SeaweedFiler_StreamMutateEntr func (m *streamMutateMux) teardownStream(gen uint64) { m.mu.Lock() if m.generation != gen || m.stream == nil { + // A retiring stream is ended by its retirement, but one a waiter gave + // up on must stop at once, as a torn-down stream does: a request still + // queued on it must not go out after its waiter fell back to unary. + if m.generation == gen && m.retireCancel != nil { + m.retireCancel() + } m.mu.Unlock() return } @@ -554,6 +802,11 @@ func (m *streamMutateMux) Close() { m.stream = nil // prevent teardownStream from acting after Close cancel := m.cancel m.cancel = nil + // A retirement would wait for its admitted requests to be answered; + // unmount cuts it short instead. + if cancel == nil { + cancel = m.retireCancel + } grpcConn := m.grpcConn m.grpcConn = nil recvDone := m.recvDone diff --git a/weed/mount/weedfs_stream_mutate_token_test.go b/weed/mount/weedfs_stream_mutate_token_test.go new file mode 100644 index 0000000000..b897a53c00 --- /dev/null +++ b/weed/mount/weedfs_stream_mutate_token_test.go @@ -0,0 +1,661 @@ +package mount + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" +) + +type mutateRecord struct { + stream int // 1-based stream number, 0 for a unary CreateEntry + token string + name string +} + +// tokenMutateFiler answers creates on StreamMutateEntry and CreateEntry, +// recording which stream and token carried each one. A create for a name in +// held is answered only once that name is released. +type tokenMutateFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + + mu sync.Mutex + records []mutateRecord + held map[string]chan struct{} + arrived chan string + streams int + finished []int // streams the client half-closed cleanly +} + +func newTokenMutateFiler() *tokenMutateFiler { + return &tokenMutateFiler{held: map[string]chan struct{}{}, arrived: make(chan string, 16)} +} + +func (f *tokenMutateFiler) hold(name string) { + f.mu.Lock() + f.held[name] = make(chan struct{}) + f.mu.Unlock() +} + +func (f *tokenMutateFiler) release(name string) { + f.mu.Lock() + close(f.held[name]) + f.mu.Unlock() +} + +func (f *tokenMutateFiler) record(r mutateRecord) chan struct{} { + f.mu.Lock() + defer f.mu.Unlock() + f.records = append(f.records, r) + return f.held[r.name] +} + +func (f *tokenMutateFiler) snapshot() (records []mutateRecord, streams int, finished []int) { + f.mu.Lock() + defer f.mu.Unlock() + return append([]mutateRecord(nil), f.records...), f.streams, append([]int(nil), f.finished...) +} + +func (f *tokenMutateFiler) StreamMutateEntry(stream filer_pb.SeaweedFiler_StreamMutateEntryServer) error { + md, _ := metadata.FromIncomingContext(stream.Context()) + f.mu.Lock() + f.streams++ + n := f.streams + f.mu.Unlock() + for { + req, err := stream.Recv() + if err == io.EOF { + f.mu.Lock() + f.finished = append(f.finished, n) + f.mu.Unlock() + return nil + } + if err != nil { + return err + } + create := req.GetCreateRequest() + gate := f.record(mutateRecord{stream: n, token: joinAuthorization(md), name: create.GetEntry().GetName()}) + f.arrived <- create.GetEntry().GetName() + if gate != nil { + select { + case <-gate: + case <-stream.Context().Done(): + return stream.Context().Err() + } + } + if err := stream.Send(&filer_pb.StreamMutateEntryResponse{ + RequestId: req.RequestId, + IsLast: true, + Response: &filer_pb.StreamMutateEntryResponse_CreateResponse{CreateResponse: &filer_pb.CreateEntryResponse{}}, + }); err != nil { + return err + } + } +} + +func (f *tokenMutateFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + f.record(mutateRecord{token: joinAuthorization(md), name: req.GetEntry().GetName()}) + f.arrived <- req.GetEntry().GetName() + return &filer_pb.CreateEntryResponse{}, nil +} + +func newTokenMutateMount(t *testing.T, source security.FilerTokenSource) (*WFS, *tokenMutateFiler) { + t.Helper() + fake := newTokenMutateFiler() + wfs := newInvalidateTestWFS(t) + wfs.filerCallTimeout = 5 * time.Second + wfs.option.FilerAddresses = []pb.ServerAddress{listenFiler(t, fake)} + atomic.StoreInt32(&wfs.option.filerIndex, 0) + wfs.option.FilerTokenSource = source + wfs.streamMutate = newStreamMutateMux(wfs) + t.Cleanup(wfs.streamMutate.Close) + return wfs, fake +} + +func createThroughMount(wfs *WFS, name string) error { + _, err := wfs.streamCreateEntry(context.Background(), &filer_pb.CreateEntryRequest{ + Directory: "/dir", + Entry: &filer_pb.Entry{Name: name}, + }) + return err +} + +func awaitArrival(t *testing.T, fake *tokenMutateFiler, want string) { + t.Helper() + select { + case got := <-fake.arrived: + if got != want { + t.Fatalf("filer received %q, want %q", got, want) + } + case <-time.After(10 * time.Second): + t.Fatalf("filer never received %q", want) + } +} + +func wantRecords(t *testing.T, got []mutateRecord, want ...mutateRecord) { + t.Helper() + if len(got) != len(want) { + t.Fatalf("filer received %+v, want %+v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("filer received %+v, want %+v", got, want) + } + } +} + +// Without a token source the mux runs one stream with no bearer, as before. +func TestStreamMutateWithoutTokenSourceKeepsOneStream(t *testing.T) { + wfs, fake := newTokenMutateMount(t, nil) + for _, name := range []string{"a", "b"} { + if err := createThroughMount(wfs, name); err != nil { + t.Fatalf("create %s: %v", name, err) + } + awaitArrival(t, fake, name) + } + records, streams, _ := fake.snapshot() + wantRecords(t, records, mutateRecord{stream: 1, name: "a"}, mutateRecord{stream: 1, name: "b"}) + if streams != 1 { + t.Fatalf("streams = %d, want 1", streams) + } +} + +// A replaced token retires the stream only after its admitted request is +// answered: the next request waits, then goes out once, on a new stream that +// carries the new token. Nothing falls back to unary, so nothing is replayed. +func TestStreamMutateDrainsBeforeReopeningWithReplacedToken(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-a") + wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path)) + + fake.hold("first") + first := make(chan error, 1) + go func() { first <- createThroughMount(wfs, "first") }() + awaitArrival(t, fake, "first") + + writeMountTokenFile(t, path, "token-b") + second := make(chan error, 1) + go func() { second <- createThroughMount(wfs, "second") }() + + select { + case name := <-fake.arrived: + t.Fatalf("filer received %q while the old stream still had a request unanswered", name) + case <-time.After(200 * time.Millisecond): + } + + fake.release("first") + if err := <-first; err != nil { + t.Fatalf("first create: %v", err) + } + awaitArrival(t, fake, "second") + if err := <-second; err != nil { + t.Fatalf("second create: %v", err) + } + + records, streams, finished := fake.snapshot() + wantRecords(t, records, + mutateRecord{stream: 1, token: "Bearer token-a", name: "first"}, + mutateRecord{stream: 2, token: "Bearer token-b", name: "second"}) + if streams != 2 || len(finished) != 1 || finished[0] != 1 { + t.Fatalf("streams = %d, cleanly finished %v; want the first half-closed before the second", streams, finished) + } +} + +// A request cancelled while the retiring stream drains returns at once and is +// never sent; the retirement and the next stream carry on. +func TestStreamMutateCancelledWhileDrainingIsNotSent(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-a") + wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path)) + + fake.hold("first") + first := make(chan error, 1) + go func() { first <- createThroughMount(wfs, "first") }() + awaitArrival(t, fake, "first") + + writeMountTokenFile(t, path, "token-b") + ctx, cancel := context.WithCancel(context.Background()) + cancelled := make(chan error, 1) + go func() { + _, err := wfs.streamMutate.CreateEntry(ctx, &filer_pb.CreateEntryRequest{ + Directory: "/dir", Entry: &filer_pb.Entry{Name: "cancelled"}, + }) + cancelled <- err + }() + select { + case err := <-cancelled: + t.Fatalf("request returned %v before the old stream drained", err) + case <-time.After(200 * time.Millisecond): + } + cancel() + select { + case err := <-cancelled: + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled request returned %v, want context.Canceled", err) + } + case <-time.After(5 * time.Second): + t.Fatal("a cancelled request kept waiting for the old stream to drain") + } + + fake.release("first") + if err := <-first; err != nil { + t.Fatalf("first create: %v", err) + } + if err := createThroughMount(wfs, "after"); err != nil { + t.Fatalf("create after: %v", err) + } + awaitArrival(t, fake, "after") + records, _, _ := fake.snapshot() + wantRecords(t, records, + mutateRecord{stream: 1, token: "Bearer token-a", name: "first"}, + mutateRecord{stream: 2, token: "Bearer token-b", name: "after"}) +} + +// Each replacement retires the stream in turn; requests in between share it. +func TestStreamMutateConsecutiveTokenReplacements(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-1") + wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path)) + + steps := []struct{ token, name string }{ + {"token-1", "a"}, {"token-1", "b"}, {"token-2", "c"}, {"token-3", "d"}, {"token-3", "e"}, + } + for _, step := range steps { + writeMountTokenFile(t, path, step.token) + if err := createThroughMount(wfs, step.name); err != nil { + t.Fatalf("create %s: %v", step.name, err) + } + awaitArrival(t, fake, step.name) + } + + records, streams, finished := fake.snapshot() + wantRecords(t, records, + mutateRecord{stream: 1, token: "Bearer token-1", name: "a"}, + mutateRecord{stream: 1, token: "Bearer token-1", name: "b"}, + mutateRecord{stream: 2, token: "Bearer token-2", name: "c"}, + mutateRecord{stream: 3, token: "Bearer token-3", name: "d"}, + mutateRecord{stream: 3, token: "Bearer token-3", name: "e"}) + if streams != 3 || len(finished) != 2 { + t.Fatalf("streams = %d, cleanly finished %v; want 3 streams, the first two half-closed", streams, finished) + } +} + +// A stream stops admitting requests once its token would expire before a +// reply could come back. With no replacement in the file, the request is not +// sent on any stream and goes out once as a unary call, which the filer +// checks when it starts. +func TestStreamMutateRetiresStreamBeforeTokenExpiry(t *testing.T) { + key := randomFilerKey(t) + token := security.GenJwtForFilerScope(key, 2*time.Second, "short", []string{"/dir"}, nil) + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, string(token)) + wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path)) + wfs.filerCallTimeout = 500 * time.Millisecond + expiresAt := filerTokenExpiry(token) + if time.Until(expiresAt) <= wfs.filerCallTimeout { + t.Skip("token already too close to expiry to open a stream") + } + + if err := createThroughMount(wfs, "early"); err != nil { + t.Fatalf("early create: %v", err) + } + awaitArrival(t, fake, "early") + + time.Sleep(time.Until(expiresAt.Add(-wfs.filerCallTimeout)) + 50*time.Millisecond) + _, err := wfs.streamMutate.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{ + Directory: "/dir", Entry: &filer_pb.Entry{Name: "refused"}, + }) + if !errors.Is(err, ErrStreamTransport) { + t.Fatalf("stream create near expiry = %v, want a transport error before sending", err) + } + if err := createThroughMount(wfs, "late"); err != nil { + t.Fatalf("late create: %v", err) + } + awaitArrival(t, fake, "late") + + records, streams, finished := fake.snapshot() + wantRecords(t, records, + mutateRecord{stream: 1, token: "Bearer " + string(token), name: "early"}, + mutateRecord{stream: 0, token: "Bearer " + string(token), name: "late"}) + if streams != 1 || len(finished) != 1 { + t.Fatalf("streams = %d, cleanly finished %v; want the expiring stream half-closed and none reopened", streams, finished) + } +} + +// A token file that cannot be read fails the mutation on both paths without +// reaching the filer. +func TestStreamMutateFailsClosedWithoutTokenFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-a") + wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path)) + if err := createThroughMount(wfs, "before"); err != nil { + t.Fatalf("create: %v", err) + } + awaitArrival(t, fake, "before") + + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + if err := createThroughMount(wfs, "after"); err == nil { + t.Fatal("create succeeded without a readable token file") + } + records, _, _ := fake.snapshot() + wantRecords(t, records, mutateRecord{stream: 1, token: "Bearer token-a", name: "before"}) +} + +// A request whose reply does not come back while the stream's token is about +// to expire may have been applied by the filer, which refuses to answer on an +// expired stream. It fails as unknown instead of going out again over unary, +// so the filer sees it exactly once. +func TestStreamMutateReplyLostNearExpiryIsNotReplayed(t *testing.T) { + key := randomFilerKey(t) + token := security.GenJwtForFilerScope(key, 6*time.Second, "short", []string{"/dir"}, nil) + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, string(token)) + wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path)) + wfs.filerCallTimeout = time.Second + expiresAt := filerTokenExpiry(token) + // Half a wait before the margin ends: the request is still admitted and + // sent, and its reply wait ends within the margin. + sendAt := expiresAt.Add(-wfs.filerCallTimeout * 3 / 2) + if time.Until(sendAt) <= 0 { + t.Skip("token already too close to expiry") + } + + if err := createThroughMount(wfs, "early"); err != nil { + t.Fatalf("early create: %v", err) + } + awaitArrival(t, fake, "early") + + // Admitted and sent with the margin intact; the filer applies it and does + // not answer before the reply wait ends, inside the margin. + fake.hold("held") + defer fake.release("held") + time.Sleep(time.Until(sendAt)) + err := createThroughMount(wfs, "held") + records, _, _ := fake.snapshot() + if len(records) != 2 { + t.Fatalf("filer received %+v, want early and held once each", records) + } + if records[1].stream == 0 { + // The expiry is wall-clock time; a clock step during the sleep can + // leave too little margin to send, and the request then correctly + // went out once over unary instead. + t.Skipf("wall clock passed the margin before the send (%v left); held went out over unary once", time.Until(expiresAt)) + } + if err == nil || errors.Is(err, ErrStreamTransport) { + t.Fatalf("create whose reply was lost near expiry = %v, want a failure that is not resent", err) + } + wantRecords(t, records, + mutateRecord{stream: 1, token: "Bearer " + string(token), name: "early"}, + mutateRecord{stream: 1, token: "Bearer " + string(token), name: "held"}) +} + +// The send loop checks the token's margin again right before sending: a +// request admitted with the margin that waited behind a slow send until the +// margin was gone is not sent, and fails with a transport error so it goes out +// once over unary. +func TestStreamMutateSendLoopHoldsBackRequestOnceMarginIsGone(t *testing.T) { + wfs := newInvalidateTestWFS(t) + wfs.filerCallTimeout = 300 * time.Millisecond + m := newStreamMutateMux(wfs) + stream := newFakeMutateClientStream("slow") + expiresAt := time.Now().Add(wfs.filerCallTimeout + 200*time.Millisecond) + stop, done := make(chan struct{}), make(chan struct{}) + go m.sendLoop(stream, stop, done, 1, expiresAt) + defer func() { + close(stop) + stream.cancel() + <-done + }() + + slow, late := queueFakeCreate(m, "slow"), queueFakeCreate(m, "late") + stream.awaitSend(t, "slow") + time.Sleep(time.Until(expiresAt.Add(-wfs.filerCallTimeout)) + 50*time.Millisecond) + close(stream.unblock) + + if err := <-slow; err != nil { + t.Fatalf("slow send: %v", err) + } + if err := <-late; !errors.Is(err, ErrStreamTransport) { + t.Fatalf("send after the margin was gone = %v, want a transport error", err) + } + if sent := stream.sentNames(); len(sent) != 1 || sent[0] != "slow" { + t.Fatalf("stream sent %v, want only slow", sent) + } +} + +// A token file replaced while the stream opens is caught when the first +// request is admitted: that stream is retired unused and the request goes out +// on a successor carrying the new token. +func TestStreamMutateTokenReplacedWhileOpeningIsNotUsed(t *testing.T) { + var reads atomic.Int32 + source := func(context.Context) (security.EncodedJwt, error) { + if reads.Add(1) == 1 { + return "token-a", nil + } + return "token-b", nil + } + wfs, fake := newTokenMutateMount(t, source) + if err := createThroughMount(wfs, "first"); err != nil { + t.Fatalf("create: %v", err) + } + awaitArrival(t, fake, "first") + records, streams, finished := fake.snapshot() + wantRecords(t, records, mutateRecord{stream: 2, token: "Bearer token-b", name: "first"}) + if streams != 2 || len(finished) != 1 || finished[0] != 1 { + t.Fatalf("streams = %d, cleanly finished %v; want the first retired unused", streams, finished) + } +} + +// Unmount during a retirement does not wait for the admitted requests to be +// answered: the retiring stream is cancelled, and its waiters return. +func TestStreamMutateCloseCutsRetirementShort(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-a") + wfs, fake := newTokenMutateMount(t, security.FilerTokenFile(path)) + m := wfs.streamMutate + + fake.hold("first") + defer fake.release("first") + first := goFakeCreate(m, "first") + awaitArrival(t, fake, "first") + writeMountTokenFile(t, path, "token-b") + second := goFakeCreate(m, "second") + awaitRetiring(t, m) + + start := time.Now() + m.Close() + limit := wfs.filerCallTimeout / 5 + if elapsed := time.Since(start); elapsed > limit { + t.Fatalf("Close took %v during a retirement, want under %v", elapsed, limit) + } + for _, ch := range []chan error{first, second} { + select { + case err := <-ch: + if err == nil { + t.Fatal("a request succeeded after Close") + } + case <-time.After(limit): + t.Fatal("a request kept waiting after Close") + } + } + records, _, _ := fake.snapshot() + wantRecords(t, records, mutateRecord{stream: 1, token: "Bearer token-a", name: "first"}) +} + +// A waiter that gives up on a retiring stream stops it at once, as on an open +// stream: its request, possibly still queued behind a stuck send, falls back to +// unary and must never go out on the old stream afterwards. +func TestStreamMutateSendTimeoutStopsRetiringStream(t *testing.T) { + wfs := newInvalidateTestWFS(t) + wfs.filerCallTimeout = 500 * time.Millisecond + var current atomic.Value + current.Store(security.EncodedJwt("token-a")) + wfs.option.FilerTokenSource = func(context.Context) (security.EncodedJwt, error) { + return current.Load().(security.EncodedJwt), nil + } + // The successor opens on a real filer. + wfs.option.FilerAddresses = []pb.ServerAddress{listenFiler(t, newTokenMutateFiler())} + atomic.StoreInt32(&wfs.option.filerIndex, 0) + m := newStreamMutateMux(wfs) + t.Cleanup(m.Close) + stream := newFakeMutateClientStream("stuck") + m.mu.Lock() + m.startLocked(stream, "token-a", time.Time{}) + m.cancel = stream.cancel + m.mu.Unlock() + + stuck := goFakeCreate(m, "stuck") + stream.awaitSend(t, "stuck") + queued := goFakeCreate(m, "queued") + awaitActive(t, m, 2) + current.Store(security.EncodedJwt("token-b")) + next := goFakeCreate(m, "next") + awaitRetiring(t, m) + + for _, ch := range []chan error{stuck, queued} { + if err := <-ch; !errors.Is(err, ErrStreamTransport) { + t.Fatalf("timed-out send = %v, want a transport error", err) + } + } + if stream.ctx.Err() == nil { + t.Fatal("the retiring stream kept running after its waiters fell back to unary") + } + if err := <-next; err != nil { + t.Fatalf("create on the successor: %v", err) + } + if sent := stream.sentNames(); len(sent) != 0 { + t.Fatalf("the retiring stream sent %v after its waiters gave up", sent) + } +} + +// fakeMutateClientStream is the client end of a mutation stream whose Send of +// the named message blocks until unblock closes or the stream is cancelled. +type fakeMutateClientStream struct { + grpc.ClientStream + ctx context.Context + cancel context.CancelFunc + block string + unblock chan struct{} + entered chan string + mu sync.Mutex + sent []string +} + +func newFakeMutateClientStream(block string) *fakeMutateClientStream { + ctx, cancel := context.WithCancel(context.Background()) + return &fakeMutateClientStream{ctx: ctx, cancel: cancel, block: block, unblock: make(chan struct{}), entered: make(chan string, 16)} +} + +func (s *fakeMutateClientStream) Send(req *filer_pb.StreamMutateEntryRequest) error { + name := req.GetCreateRequest().GetEntry().GetName() + s.entered <- name + if name == s.block { + select { + case <-s.unblock: + case <-s.ctx.Done(): + return s.ctx.Err() + } + } + if s.ctx.Err() != nil { + return s.ctx.Err() + } + s.mu.Lock() + s.sent = append(s.sent, name) + s.mu.Unlock() + return nil +} + +func (s *fakeMutateClientStream) Recv() (*filer_pb.StreamMutateEntryResponse, error) { + <-s.ctx.Done() + return nil, s.ctx.Err() +} + +func (s *fakeMutateClientStream) CloseSend() error { return nil } + +func (s *fakeMutateClientStream) sentNames() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.sent...) +} + +func (s *fakeMutateClientStream) awaitSend(t *testing.T, want string) { + t.Helper() + select { + case got := <-s.entered: + if got != want { + t.Fatalf("stream sending %q, want %q", got, want) + } + case <-time.After(5 * time.Second): + t.Fatalf("stream never started sending %q", want) + } +} + +// queueFakeCreate queues a create for generation 1 straight onto the send +// loop and returns its send result. +func queueFakeCreate(m *streamMutateMux, name string) chan error { + errCh := make(chan error, 1) + m.sendCh <- &streamMutateReq{ + req: &filer_pb.StreamMutateEntryRequest{ + Request: &filer_pb.StreamMutateEntryRequest_CreateRequest{CreateRequest: &filer_pb.CreateEntryRequest{ + Directory: "/dir", Entry: &filer_pb.Entry{Name: name}, + }}, + }, + errCh: errCh, + gen: 1, + } + return errCh +} + +// goFakeCreate runs a create through the mux, without the unary fallback. +func goFakeCreate(m *streamMutateMux, name string) chan error { + done := make(chan error, 1) + go func() { + _, err := m.CreateEntry(context.Background(), &filer_pb.CreateEntryRequest{ + Directory: "/dir", Entry: &filer_pb.Entry{Name: name}, + }) + done <- err + }() + return done +} + +func awaitRetiring(t *testing.T, m *streamMutateMux) { + t.Helper() + awaitMux(t, m, "a retirement", func() bool { return m.draining != nil }) +} + +func awaitActive(t *testing.T, m *streamMutateMux, n int) { + t.Helper() + awaitMux(t, m, "admissions", func() bool { return m.active == n }) +} + +func awaitMux(t *testing.T, m *streamMutateMux, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + m.mu.Lock() + ok := cond() + m.mu.Unlock() + if ok { + return + } + if time.Now().After(deadline) { + t.Fatalf("mux never reached %s", what) + } + time.Sleep(5 * time.Millisecond) + } +} diff --git a/weed/mount/wfs_filer_client.go b/weed/mount/wfs_filer_client.go index be69d703ff..ec615eb1d6 100644 --- a/weed/mount/wfs_filer_client.go +++ b/weed/mount/wfs_filer_client.go @@ -13,6 +13,7 @@ import ( "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" ) @@ -29,7 +30,13 @@ func (wfs *WFS) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFile // stopped following are final whatever their message says, and the path or // cause they name can contain "transport". func isRetryableFilerCall(err error) bool { - return !filer_pb.IsFilerVerdict(err) && !errors.Is(err, pb.ErrStopFollowing) && util.IsTransientError(err) + return !filer_pb.IsFilerVerdict(err) && !endsFollowAttempt(err) && util.IsTransientError(err) +} + +// endsFollowAttempt reports a metadata follow its consumer ended, for good or +// to resubscribe: no other filer should run the same attempt. +func endsFollowAttempt(err error) bool { + return errors.Is(err, pb.ErrStopFollowing) || errors.Is(err, pb.ErrResubscribe) } // withFilerClient walks the filer addresses until one answers fn. callWait @@ -56,8 +63,9 @@ func (wfs *WFS) withFilerClient(ctx context.Context, streamingMode bool, callWai // A verdict is the filer's answer, and another filer would give // the same one. Stop here, so that a later filer's transport // error cannot replace it and turn it into a retry. A consumer - // that stopped following is done with every filer. - if filer_pb.IsFilerVerdict(err) || errors.Is(err, pb.ErrStopFollowing) { + // that stopped following, or asked to resubscribe, is done with + // this attempt on every filer. + if filer_pb.IsFilerVerdict(err) || endsFollowAttempt(err) { atomic.StoreInt32(&wfs.option.filerIndex, i) return err } @@ -99,7 +107,7 @@ func (wfs *WFS) filerRPCWait() time.Duration { func (wfs *WFS) callFiler(ctx context.Context, streamingMode bool, callWait time.Duration, filerGrpcAddress string, fn func(ctx context.Context, client filer_pb.SeaweedFilerClient) error) error { if streamingMode { return pb.WithGrpcClient(ctx, streamingMode, wfs.signature, func(grpcConnection *grpc.ClientConn) error { - return fn(ctx, filer_pb.NewSeaweedFilerClient(grpcConnection)) + return fn(ctx, wfs.newFilerClient(grpcConnection)) }, filerGrpcAddress, false, wfs.option.GrpcDialOption) } @@ -112,7 +120,7 @@ func (wfs *WFS) callFiler(ctx context.Context, streamingMode bool, callWait time done := make(chan error, 1) go func() { done <- pb.WithGrpcClient(attemptCtx, streamingMode, wfs.signature, func(grpcConnection *grpc.ClientConn) error { - return fn(attemptCtx, filer_pb.NewSeaweedFilerClient(grpcConnection)) + return fn(attemptCtx, wfs.newFilerClient(grpcConnection)) }, filerGrpcAddress, false, wfs.option.GrpcDialOption) }() @@ -145,6 +153,13 @@ func (wfs *WFS) callFiler(ctx context.Context, streamingMode bool, callWait time } } +// newFilerClient authorizes each call through the client with the mount's +// filer token source, resolved per attempt so a retry carries a replaced +// token. The cached channel itself carries no identity. +func (wfs *WFS) newFilerClient(conn *grpc.ClientConn) filer_pb.SeaweedFilerClient { + return filer_pb.NewSeaweedFilerClient(security.WithFilerClientAuth(conn, wfs.option.FilerTokenSource)) +} + func (wfs *WFS) AdjustedUrl(location *filer_pb.Location) string { if wfs.option.VolumeServerAccess == "publicUrl" { return location.PublicUrl diff --git a/weed/mount/wfs_filer_token_test.go b/weed/mount/wfs_filer_token_test.go new file mode 100644 index 0000000000..6698e96315 --- /dev/null +++ b/weed/mount/wfs_filer_token_test.go @@ -0,0 +1,274 @@ +package mount + +import ( + "context" + "net" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + + "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" + + "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" +) + +// tokenRecordingFiler records the authorization each lookup arrived with. +// onLookup, when set, decides the reply for each call by its 1-based number. +type tokenRecordingFiler struct { + filer_pb.UnimplementedSeaweedFilerServer + mu sync.Mutex + tokens []string + calls atomic.Int32 + onLookup func(call int32) error +} + +func (s *tokenRecordingFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { + call := s.calls.Add(1) + md, _ := metadata.FromIncomingContext(ctx) + s.mu.Lock() + s.tokens = append(s.tokens, joinAuthorization(md)) + s.mu.Unlock() + if s.onLookup != nil { + if err := s.onLookup(call); err != nil { + return nil, err + } + } + return &filer_pb.LookupDirectoryEntryResponse{Entry: &filer_pb.Entry{Name: req.Name}}, nil +} + +func (s *tokenRecordingFiler) seen() []string { + s.mu.Lock() + defer s.mu.Unlock() + return append([]string(nil), s.tokens...) +} + +func joinAuthorization(md metadata.MD) string { + values := md.Get("authorization") + switch len(values) { + case 0: + return "" + case 1: + return values[0] + } + return "multiple" +} + +func writeMountTokenFile(t *testing.T, path, token string) { + t.Helper() + tmp := path + ".tmp" + if err := os.WriteFile(tmp, []byte(token+"\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Rename(tmp, path); err != nil { + t.Fatal(err) + } +} + +func lookupThroughMount(wfs *WFS) error { + return wfs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error { + _, err := client.LookupDirectoryEntry(context.Background(), &filer_pb.LookupDirectoryEntryRequest{Directory: "/", Name: "x"}) + return err + }) +} + +func newTokenTestWFS(t *testing.T, filer pb.ServerAddress, source security.FilerTokenSource) *WFS { + t.Helper() + wfs := newInvalidateTestWFS(t) + wfs.option.FilerAddresses = []pb.ServerAddress{filer} + wfs.option.FilerTokenSource = source + atomic.StoreInt32(&wfs.option.filerIndex, 0) + return wfs +} + +// Without -filer.tokenFile the mount's calls carry no bearer, as before. +func TestMountFilerCallsWithoutTokenFileCarryNoAuthorization(t *testing.T) { + fake := &tokenRecordingFiler{} + wfs := newTokenTestWFS(t, listenFiler(t, fake), nil) + if err := lookupThroughMount(wfs); err != nil { + t.Fatalf("lookup: %v", err) + } + if got := fake.seen(); len(got) != 1 || got[0] != "" { + t.Fatalf("authorization = %q, want none", got) + } +} + +// Each call reads the file, so a replacement reaches the next call over the +// same cached channel. +func TestMountFilerCallsCarryCurrentTokenFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-one") + fake := &tokenRecordingFiler{} + wfs := newTokenTestWFS(t, listenFiler(t, fake), security.FilerTokenFile(path)) + + if err := lookupThroughMount(wfs); err != nil { + t.Fatalf("first lookup: %v", err) + } + writeMountTokenFile(t, path, "token-two") + if err := lookupThroughMount(wfs); err != nil { + t.Fatalf("second lookup: %v", err) + } + got := fake.seen() + if len(got) != 2 || got[0] != "Bearer token-one" || got[1] != "Bearer token-two" { + t.Fatalf("authorization = %q, want the token current at each call", got) + } +} + +// A retried attempt resolves the token again: the replacement written while +// the first attempt failed is what the retry presents. +func TestMountFilerRetryUsesReplacedToken(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-old") + fake := &tokenRecordingFiler{} + fake.onLookup = func(call int32) error { + if call == 1 { + writeMountTokenFile(t, path, "token-new") + return status.Error(codes.Unavailable, "filer restarting") + } + return nil + } + wfs := newTokenTestWFS(t, listenFiler(t, fake), security.FilerTokenFile(path)) + + if err := lookupThroughMount(wfs); err != nil { + t.Fatalf("lookup: %v", err) + } + got := fake.seen() + if len(got) != 2 || got[0] != "Bearer token-old" || got[1] != "Bearer token-new" { + t.Fatalf("authorization = %q, want the retry to carry the replaced token", got) + } +} + +// Two mounts of one filer share its cached channel but keep their own +// identities, in either order. +func TestTwoMountsKeepTheirOwnTokensOnASharedChannel(t *testing.T) { + dir := t.TempDir() + pathA, pathB := filepath.Join(dir, "a"), filepath.Join(dir, "b") + writeMountTokenFile(t, pathA, "token-a") + writeMountTokenFile(t, pathB, "token-b") + fake := &tokenRecordingFiler{} + filer := listenFiler(t, fake) + mountA := newTokenTestWFS(t, filer, security.FilerTokenFile(pathA)) + mountB := newTokenTestWFS(t, filer, security.FilerTokenFile(pathB)) + anonymous := newTokenTestWFS(t, filer, nil) + + for _, wfs := range []*WFS{anonymous, mountA, mountB, anonymous, mountB, mountA} { + if err := lookupThroughMount(wfs); err != nil { + t.Fatalf("lookup: %v", err) + } + } + want := []string{"", "Bearer token-a", "Bearer token-b", "", "Bearer token-b", "Bearer token-a"} + got := fake.seen() + if len(got) != len(want) { + t.Fatalf("authorization = %q, want %q", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("authorization = %q, want %q", got, want) + } + } + + var wg sync.WaitGroup + for i := 0; i < 20; i++ { + for _, wfs := range []*WFS{mountA, mountB} { + wg.Add(1) + go func(wfs *WFS) { + defer wg.Done() + if err := lookupThroughMount(wfs); err != nil { + t.Errorf("concurrent lookup: %v", err) + } + }(wfs) + } + } + wg.Wait() + counts := map[string]int{} + for _, token := range fake.seen()[len(want):] { + counts[token]++ + } + if counts["Bearer token-a"] != 20 || counts["Bearer token-b"] != 20 || len(counts) != 2 { + t.Fatalf("concurrent authorization counts = %v, want 20 of each mount's token", counts) + } +} + +// A configured file that cannot be read fails the call before it reaches the +// filer: never anonymously, never with another identity. +func TestMountFilerCallFailsLocallyWithoutTokenFile(t *testing.T) { + fake := &tokenRecordingFiler{} + missing := filepath.Join(t.TempDir(), "missing") + wfs := newTokenTestWFS(t, listenFiler(t, fake), security.FilerTokenFile(missing)) + + if err := lookupThroughMount(wfs); err == nil { + t.Fatal("lookup succeeded without a readable token file") + } + if got := fake.calls.Load(); got != 0 { + t.Fatalf("filer saw %d calls, want none", got) + } +} + +// sseConfigFiler answers the SSE-S3 reader's configuration call. +type sseConfigFiler struct { + tokenRecordingFiler + master string +} + +func (s *sseConfigFiler) GetFilerConfiguration(ctx context.Context, req *filer_pb.GetFilerConfigurationRequest) (*filer_pb.GetFilerConfigurationResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + s.mu.Lock() + s.tokens = append(s.tokens, joinAuthorization(md)) + s.mu.Unlock() + return &filer_pb.GetFilerConfigurationResponse{Masters: []string{s.master}}, nil +} + +type recordingMaster struct { + master_pb.UnimplementedSeaweedServer + mu sync.Mutex + tokens []string +} + +func (m *recordingMaster) ListClusterNodes(ctx context.Context, req *master_pb.ListClusterNodesRequest) (*master_pb.ListClusterNodesResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + m.mu.Lock() + m.tokens = append(m.tokens, joinAuthorization(md)) + m.mu.Unlock() + return &master_pb.ListClusterNodesResponse{ClusterNodes: []*master_pb.ListClusterNodesResponse_ClusterNode{{S3Endpoint: "http://127.0.0.1:1"}}}, nil +} + +// The SSE-S3 reader presents the token to the filer only; the master it then +// asks for gateways gets no filer credential. +func TestListS3EndpointsSendsTokenToFilerOnly(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeMountTokenFile(t, path, "token-sse") + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + master := &recordingMaster{} + server := grpc.NewServer() + master_pb.RegisterSeaweedServer(server, master) + go server.Serve(listener) + t.Cleanup(server.Stop) + masterAddr := pb.NewServerAddressWithGrpcPort("127.0.0.1:1", listener.Addr().(*net.TCPAddr).Port) + + filer := &sseConfigFiler{master: string(masterAddr)} + endpoints, err := listS3Endpoints(context.Background(), []pb.ServerAddress{listenFiler(t, filer)}, + grpc.WithTransportCredentials(insecure.NewCredentials()), security.FilerTokenFile(path)) + if err != nil || len(endpoints) != 1 { + t.Fatalf("listS3Endpoints = %v, %v", endpoints, err) + } + if got := filer.seen(); len(got) != 1 || got[0] != "Bearer token-sse" { + t.Fatalf("filer authorization = %q, want the mount token", got) + } + master.mu.Lock() + defer master.mu.Unlock() + if len(master.tokens) != 1 || master.tokens[0] != "" { + t.Fatalf("master authorization = %q, want none", master.tokens) + } +} diff --git a/weed/security/filer_token_file.go b/weed/security/filer_token_file.go new file mode 100644 index 0000000000..282e5436cd --- /dev/null +++ b/weed/security/filer_token_file.go @@ -0,0 +1,121 @@ +package security + +import ( + "context" + "fmt" + "io" + "path" + "slices" + "strings" + "unicode" + + jwt "github.com/golang-jwt/jwt/v5" +) + +// maxFilerTokenFileSize bounds what a token file read may load into memory. +const maxFilerTokenFileSize = 64 << 10 + +// FilerTokenFile is the token source of a client that holds a pre-issued +// filer token instead of a signing key. It reads path on every call, so a +// replaced file, including an atomic rename that keeps size and mtime, is +// used from the next RPC attempt or stream opening on. Surrounding whitespace +// is trimmed. A missing, unreadable, empty or malformed file is an error, and +// the call fails without falling back to anonymous or admin authority. +// Errors name the path but never carry the file's contents. +func FilerTokenFile(path string) FilerTokenSource { + return func(context.Context) (EncodedJwt, error) { + f, err := openFilerTokenFile(path) + if err != nil { + return "", fmt.Errorf("filer token file: %w", err) + } + defer f.Close() + data, err := io.ReadAll(io.LimitReader(f, maxFilerTokenFileSize+1)) + if err != nil { + return "", fmt.Errorf("filer token file: %w", err) + } + if len(data) > maxFilerTokenFileSize { + return "", fmt.Errorf("filer token file %s is larger than %d bytes", path, maxFilerTokenFileSize) + } + token := strings.TrimSpace(string(data)) + if token == "" { + return "", fmt.Errorf("filer token file %s is empty", path) + } + if strings.IndexFunc(token, func(r rune) bool { return unicode.IsSpace(r) || !unicode.IsPrint(r) }) >= 0 { + return "", fmt.Errorf("filer token file %s does not hold a single token", path) + } + return EncodedJwt(token), nil + } +} + +// FilerTokenClaims decodes a filer token's claims without verifying it. A +// client that holds only the token uses them to plan reconnects before the +// token expires; they never decide access, which stays with the filer. +func FilerTokenClaims(token EncodedJwt) (*SeaweedFilerClaims, bool) { + claims := &SeaweedFilerClaims{} + if _, _, err := jwt.NewParser().ParseUnverified(string(token), claims); err != nil { + return nil, false + } + return claims, true +} + +// FilerTokenGrantCovers reports, from the tokens' unverified claims, whether +// next lets its holder see everything prev did: every path prev could read +// and every method prev could call. A client that cached what prev showed it +// can keep that cache when next covers prev. A token that cannot be decoded, +// or names a prefix the filer would refuse, covers nothing but itself. +func FilerTokenGrantCovers(prev, next EncodedJwt) bool { + if prev == next { + return true + } + p, ok := FilerTokenClaims(prev) + if !ok { + return false + } + n, ok := FilerTokenClaims(next) + if !ok { + return false + } + if len(n.AllowedMethods) > 0 { + if len(p.AllowedMethods) == 0 { + return false + } + for _, m := range p.AllowedMethods { + if !slices.Contains(n.AllowedMethods, m) { + return false + } + } + } + nextPrefixes, ok := filerTokenPrefixes(n) + if !ok { + return false + } + prevPrefixes, ok := filerTokenPrefixes(p) + if !ok { + return false + } + if len(nextPrefixes) == 0 { + return true + } + if len(prevPrefixes) == 0 { + return false + } + for _, prefix := range prevPrefixes { + if !MetadataPathInScope(prefix, nextPrefixes) { + return false + } + } + return true +} + +// filerTokenPrefixes lists the paths a token may read, empty when it is not +// scoped. ok is false when a prefix is not a clean absolute path, which the +// filer refuses. +func filerTokenPrefixes(c *SeaweedFilerClaims) (prefixes []string, ok bool) { + prefixes = append(append(prefixes, c.AllowedPrefixes...), c.ReadPrefixes...) + for _, p := range prefixes { + if !strings.HasPrefix(p, "/") || path.Clean(p) != p { + return nil, false + } + } + return prefixes, true +} diff --git a/weed/security/filer_token_file_other.go b/weed/security/filer_token_file_other.go new file mode 100644 index 0000000000..83e7560cab --- /dev/null +++ b/weed/security/filer_token_file_other.go @@ -0,0 +1,11 @@ +//go:build !windows + +package security + +import "os" + +// openFilerTokenFile opens path for reading. A rename that replaces the file +// does not wait for open handles here. +func openFilerTokenFile(path string) (*os.File, error) { + return os.Open(path) +} diff --git a/weed/security/filer_token_file_test.go b/weed/security/filer_token_file_test.go new file mode 100644 index 0000000000..e2ade90e31 --- /dev/null +++ b/weed/security/filer_token_file_test.go @@ -0,0 +1,226 @@ +package security + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" +) + +// writeTokenFile replaces path atomically, the way a token renewer should. +func writeTokenFile(t *testing.T, path, content string) { + t.Helper() + tmp := path + ".tmp" + if err := os.WriteFile(tmp, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Rename(tmp, path); err != nil { + t.Fatal(err) + } +} + +func TestFilerTokenFileTrimsSurroundingWhitespace(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeTokenFile(t, path, "\n header.payload.signature \r\n\t") + + token, err := FilerTokenFile(path)(context.Background()) + if err != nil { + t.Fatalf("read token: %v", err) + } + if token != "header.payload.signature" { + t.Fatalf("token = %q, want the trimmed contents", token) + } +} + +func TestFilerTokenFileFailsClosedWithoutLeakingContents(t *testing.T) { + dir := t.TempDir() + const secret = "s3cr3t-part" + tests := []struct { + name string + setup func(path string) + want string + is error // checked instead of want for errors the platform words + }{ + {name: "missing", setup: func(string) {}, is: os.ErrNotExist}, + {name: "empty", setup: func(p string) { writeTokenFile(t, p, "") }, want: "empty"}, + {name: "whitespace only", setup: func(p string) { writeTokenFile(t, p, " \n\t ") }, want: "empty"}, + {name: "unreadable", setup: func(p string) { + if err := os.Mkdir(p, 0o700); err != nil { + t.Fatal(err) + } + }, want: "filer token file"}, + {name: "two tokens", setup: func(p string) { writeTokenFile(t, p, secret+"-a\n"+secret+"-b") }, want: "single token"}, + {name: "control character", setup: func(p string) { writeTokenFile(t, p, secret+"\x00") }, want: "single token"}, + {name: "too large", setup: func(p string) { writeTokenFile(t, p, strings.Repeat(secret, maxFilerTokenFileSize)) }, want: "larger than"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(dir, strings.ReplaceAll(tt.name, " ", "-")) + tt.setup(path) + token, err := FilerTokenFile(path)(context.Background()) + if err == nil { + t.Fatal("read succeeded, want a local failure") + } + if token != "" { + t.Fatal("a failed read returned a token") + } + if tt.is != nil { + if !errors.Is(err, tt.is) { + t.Fatalf("error %q is not %v", err, tt.is) + } + } else if !strings.Contains(err.Error(), tt.want) { + t.Fatalf("error %q does not explain the failure (%q)", err, tt.want) + } + if strings.Contains(err.Error(), secret) { + t.Fatal("error carries the token file's contents") + } + }) + } +} + +func TestFilerTokenFileSeesSameSizeSameMtimeReplacement(t *testing.T) { + path := filepath.Join(t.TempDir(), "token") + writeTokenFile(t, path, "token-aaaa") + source := FilerTokenFile(path) + if token, err := source(context.Background()); err != nil || token != "token-aaaa" { + t.Fatalf("first read = %q, %v", token, err) + } + before, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + + writeTokenFile(t, path, "token-bbbb") + if err := os.Chtimes(path, before.ModTime(), before.ModTime()); err != nil { + t.Fatal(err) + } + after, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if after.Size() != before.Size() || !after.ModTime().Equal(before.ModTime()) { + t.Fatal("replacement did not keep size and mtime") + } + + if token, err := source(context.Background()); err != nil || token != "token-bbbb" { + t.Fatalf("read after replacement = %q, %v; want the new token", token, err) + } +} + +// Concurrent calls during repeated atomic replacement see one whole token or +// the other, never an error or a partial read; two sources stay independent. +func TestFilerTokenFileConcurrentUseAndIndependentFiles(t *testing.T) { + dir := t.TempDir() + pathA, pathB := filepath.Join(dir, "a"), filepath.Join(dir, "b") + writeTokenFile(t, pathA, "mount-a-1") + writeTokenFile(t, pathB, "mount-b-1") + sourceA, sourceB := FilerTokenFile(pathA), FilerTokenFile(pathB) + + stop := make(chan struct{}) + writerDone := make(chan struct{}) + go func() { + defer close(writerDone) + for i := 0; ; i++ { + select { + case <-stop: + return + default: + } + content := "mount-a-1" + if i%2 == 0 { + content = "mount-a-2" + } + tmp := filepath.Join(dir, "a.tmp") + if err := os.WriteFile(tmp, []byte(content), 0o600); err != nil { + t.Error(err) + return + } + if err := os.Rename(tmp, pathA); err != nil { + t.Error(err) + return + } + } + }() + + var wg sync.WaitGroup + for g := 0; g < 8; g++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 200; i++ { + a, err := sourceA(context.Background()) + if err != nil || (a != "mount-a-1" && a != "mount-a-2") { + t.Errorf("mount a read %q, %v", a, err) + return + } + b, err := sourceB(context.Background()) + if err != nil || b != "mount-b-1" { + t.Errorf("mount b read %q, %v", b, err) + return + } + } + }() + } + wg.Wait() + close(stop) + <-writerDone +} + +func TestFilerTokenClaimsDecodesWithoutKey(t *testing.T) { + key := testSigningKey(t) + token := GenJwtForFilerScope(key, time.Hour, "mount-1", []string{"/buckets/a"}, []string{"/shared"}) + claims, ok := FilerTokenClaims(token) + if !ok { + t.Fatal("scoped token did not decode") + } + if claims.ExpiresAt == nil || time.Until(claims.ExpiresAt.Time) <= 50*time.Minute { + t.Fatalf("expiry = %v, want about an hour from now", claims.ExpiresAt) + } + if len(claims.AllowedPrefixes) != 1 || claims.AllowedPrefixes[0] != "/buckets/a" || len(claims.ReadPrefixes) != 1 { + t.Fatalf("claims = %+v", claims) + } + if _, ok := FilerTokenClaims("not-a-token"); ok { + t.Fatal("garbage decoded as a token") + } +} + +func TestFilerTokenGrantCovers(t *testing.T) { + key := testSigningKey(t) + scoped := func(allowed, read []string) EncodedJwt { + return GenJwtForFilerScope(key, time.Hour, "id", allowed, read) + } + admin := GenJwtForFilerAdmin(key, 60) + subscribeOnly := GenJwtForMetadataSubscription(key, 60, []string{"/buckets"}) + base := scoped([]string{"/buckets/a"}, nil) + + tests := []struct { + name string + prev, next EncodedJwt + want bool + }{ + {name: "same token", prev: base, next: base, want: true}, + {name: "same grant, new token", prev: base, next: scoped([]string{"/buckets/a"}, nil), want: true}, + {name: "broader prefix", prev: base, next: scoped([]string{"/buckets"}, nil), want: true}, + {name: "extra prefix", prev: base, next: scoped([]string{"/buckets/a", "/buckets/b"}, nil), want: true}, + {name: "write turned read-only", prev: base, next: scoped(nil, []string{"/buckets/a"}), want: true}, + {name: "to unscoped", prev: base, next: admin, want: true}, + {name: "narrower prefix", prev: base, next: scoped([]string{"/buckets/a/x"}, nil), want: false}, + {name: "sibling prefix", prev: base, next: scoped([]string{"/buckets/ab"}, nil), want: false}, + {name: "dropped read prefix", prev: scoped([]string{"/buckets/a"}, []string{"/shared"}), next: base, want: false}, + {name: "unscoped to scoped", prev: admin, next: base, want: false}, + {name: "method restricted", prev: base, next: subscribeOnly, want: false}, + {name: "undecodable next", prev: base, next: "opaque-token", want: false}, + {name: "undecodable prev", prev: "opaque-token", next: base, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := FilerTokenGrantCovers(tt.prev, tt.next); got != tt.want { + t.Fatalf("FilerTokenGrantCovers = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/weed/security/filer_token_file_windows.go b/weed/security/filer_token_file_windows.go new file mode 100644 index 0000000000..c5045cacbe --- /dev/null +++ b/weed/security/filer_token_file_windows.go @@ -0,0 +1,25 @@ +//go:build windows + +package security + +import ( + "os" + "syscall" +) + +// openFilerTokenFile opens path for reading with delete sharing, so a renewer +// can replace the file by rename while a read still holds it open. os.Open +// leaves delete sharing out, and the rename would fail until the read closed. +func openFilerTokenFile(path string) (*os.File, error) { + name, err := syscall.UTF16PtrFromString(path) + if err != nil { + return nil, &os.PathError{Op: "open", Path: path, Err: err} + } + h, err := syscall.CreateFile(name, syscall.GENERIC_READ, + syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, + nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0) + if err != nil { + return nil, &os.PathError{Op: "open", Path: path, Err: err} + } + return os.NewFile(uintptr(h), path), nil +}