From 39675b2faf589c32a9f7da3eaad52f52d942fae2 Mon Sep 17 00:00:00 2001 From: Carlos Leyva <66577002+carlos-leyva-guerrero@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:31:02 +0100 Subject: [PATCH] filer: hide remote rename source paths from scoped responses (#13010) * filer: redact remote rename source from scoped responses * Preserve scoped remote rename markers * Consolidate scoped marker replacement coverage * Refuse scoped whole-entry guards during remote rename * Keep coded create refusals for guarded scoped writes * Make scoped subscription batch coverage deterministic * filer: refuse scoped conditions that compare the remote rename source IF_EXTENDED_NOT_EQUAL clauses and ExpectedExtended on Create, Update and DeleteEntry could still compare a guess against the hidden marker, so a scoped client could confirm the source path it redacts. Co-Authored-By: Claude Opus 5.5 * filer: refuse scoped condition gates on the remote rename source An IF_EXTENDED_TIME_ELAPSED gate applies its time check only when the gate value matches, so a gate on the marker also confirms a guess. Co-Authored-By: Claude Opus 5.5 * filer: keep a pending rename source out of remote copy errors A failed copy of a pending remote-only rename named the marker's source location, which the backend error repeats, and rename RPCs return that error to scoped callers. Log the full error and return one naming only the paths the caller supplied. Co-Authored-By: Claude Opus 5.5 * filer: let a scoped local overwrite end a pending remote rename Scoped replacements kept the hidden rename source marker even though a scoped entry can never stay remote-only, so the marker was stale on the local copy and every later scoped IF_ENTRY_EQUAL write was refused. Drop the preservation and let the overwrite clear the marker as other local writes do. Co-Authored-By: Claude Opus 5.5 * codespell: ignore poligon only inside URLs Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Chris Lu Co-authored-by: Claude Opus 5.5 --- weed/filer/filer_lazy_remote.go | 8 +- weed/server/filer_grpc_scope.go | 77 +++- .../filer_grpc_scope_entry_equal_test.go | 383 ++++++++++++++++++ weed/server/filer_grpc_scope_harness_test.go | 8 +- .../filer_grpc_scope_hidden_reads_test.go | 256 ++++++++++++ .../filer_grpc_scope_mutation_flags_test.go | 47 +++ weed/server/filer_grpc_scope_redact.go | 205 ++++++++++ weed/server/filer_grpc_scope_stream.go | 1 + weed/server/filer_grpc_scope_stream_test.go | 96 ++++- .../filer_grpc_scope_subscription_test.go | 214 +++++++++- weed/server/filer_grpc_server.go | 13 + .../filer_grpc_server_rename_remote_test.go | 18 + .../filer_grpc_server_sub_meta_scope.go | 1 + .../server/scoped_update_stored_state_test.go | 24 ++ 14 files changed, 1341 insertions(+), 10 deletions(-) create mode 100644 weed/server/filer_grpc_scope_entry_equal_test.go create mode 100644 weed/server/filer_grpc_scope_redact.go diff --git a/weed/filer/filer_lazy_remote.go b/weed/filer/filer_lazy_remote.go index 81d4e3996a..a1e3ccc1fd 100644 --- a/weed/filer/filer_lazy_remote.go +++ b/weed/filer/filer_lazy_remote.go @@ -392,7 +392,13 @@ func (f *Filer) CopyRemoteOnlyEntry(ctx context.Context, entry *Entry, oldPath, } remoteEntry, err := copier.CopyFile(src, dst) if err != nil { - return nil, fmt.Errorf("copy remote %s to %s: %w", remote_storage.FormatLocation(src), remote_storage.FormatLocation(dst), err) + copyErr := fmt.Errorf("copy remote %s to %s: %w", remote_storage.FormatLocation(src), remote_storage.FormatLocation(dst), err) + if f.RemoteSourcePath(entry, oldPath) != oldPath { + // the pending source is filer-owned, and backend errors name it too + glog.WarningfCtx(ctx, "rename %s to %s: %v", oldPath, newPath, copyErr) + return nil, fmt.Errorf("copy remote object of %s to %s failed", oldPath, newPath) + } + return nil, copyErr } glog.V(3).InfofCtx(ctx, "CopyRemoteOnlyEntry: copied %s to %s", remote_storage.FormatLocation(src), remote_storage.FormatLocation(dst)) return remoteEntry, nil diff --git a/weed/server/filer_grpc_scope.go b/weed/server/filer_grpc_scope.go index 645afe84d1..9c517a48e8 100644 --- a/weed/server/filer_grpc_scope.go +++ b/weed/server/filer_grpc_scope.go @@ -304,14 +304,57 @@ func (sc *scope) checkProtectedPath(method, p string, descendants bool) error { return nil } +// scopeEntryEqualRefusal keeps a scoped client from guessing the hidden +// filer-owned state of a pending remote rename. The caller supplies the +// stored extended attributes so admission and the locked handler check can +// share the same rule without changing the global comparator. +func scopeEntryEqualRefusal(ctx context.Context, condition *filer_pb.WriteCondition, extended map[string][]byte) error { + if !scopeKeepOnly(ctx) { + return nil + } + if _, marked := extended[filer.ExtRemoteRenameSourceKey]; !marked { + return nil + } + if scopeHasEntryEqual(condition) { + return status.Error(codes.FailedPrecondition, "filer: scoped IF_ENTRY_EQUAL cannot be used while a remote rename is pending") + } + return nil +} + +// scopeNamesRemoteRenameSource reports a condition or expected attribute that +// compares against the hidden remote rename source. +func scopeNamesRemoteRenameSource(condition *filer_pb.WriteCondition, expectedExtended map[string][]byte) bool { + if _, ok := expectedExtended[filer.ExtRemoteRenameSourceKey]; ok { + return true + } + for _, clause := range condition.GetClauses() { + if clause.GetExtKey() == filer.ExtRemoteRenameSourceKey || clause.GetGateKey() == filer.ExtRemoteRenameSourceKey { + return true + } + } + return false +} + +func scopeHasEntryEqual(condition *filer_pb.WriteCondition) bool { + for _, clause := range condition.GetClauses() { + if clause != nil && clause.GetKind() == filer_pb.WriteCondition_IF_ENTRY_EQUAL { + return true + } + } + return false +} + // checkClientEntry admits retained chunks or chunks with valid assignment proofs. // A hard-link id may be retained there, or a fresh id may be introduced by an // update of an existing unlinked entry. Attaching another path's id is refused. // Client signatures stay allowed so mounts can filter their own events. -func (s *filerGrpcScope) checkClientEntry(ctx context.Context, sc *scope, method, p string, e *filer_pb.Entry, chunkAuth map[string]string, allowNewHardLink bool) error { +func (s *filerGrpcScope) checkClientEntry(ctx context.Context, sc *scope, method, p string, e *filer_pb.Entry, condition *filer_pb.WriteCondition, chunkAuth map[string]string, allowNewHardLink bool) error { if err := scopeCheckEntryShape(e); err != nil { return sc.deny(method, err.Error()) } + if _, ok := e.GetExtended()[filer.ExtRemoteRenameSourceKey]; ok { + return sc.deny(method, "remote rename source is filer-owned") + } if err := sc.checkProtectedPath(method, p, false); err != nil { return err } @@ -330,6 +373,9 @@ func (s *filerGrpcScope) checkClientEntry(ctx context.Context, sc *scope, method if err := scopeWritesSharedHardLink(stored, e); err != nil { return sc.deny(method, err.Error()) } + if err := scopeEntryEqualRefusal(ctx, condition, stored.GetExtended()); err != nil { + return err + } return nil } // Keep ordinary mount creates lookup-free at admission. The handlers @@ -351,6 +397,11 @@ func (s *filerGrpcScope) checkClientEntry(ctx context.Context, sc *scope, method } } } + if scopeHasEntryEqual(condition) { + if err := load(); err != nil { + return err + } + } if len(e.HardLinkId) == 0 { return nil @@ -381,6 +432,9 @@ func (s *filerGrpcScope) checkCreate(ctx context.Context, sc *scope, m string, r if req.GetIsFromOtherCluster() || req.GetIsMoved() { return sc.deny(m, "is_from_other_cluster and is_moved are not allowed") } + if scopeNamesRemoteRenameSource(req.GetCondition(), nil) { + return sc.deny(m, "remote rename source is filer-owned") + } p, err := sc.checkPath(m, req.GetDirectory(), req.GetEntry().GetName(), true) if err != nil { return err @@ -390,7 +444,10 @@ func (s *filerGrpcScope) checkCreate(ctx context.Context, sc *scope, m string, r return err } } - return s.checkClientEntry(ctx, sc, m, p, req.GetEntry(), req.GetChunkAuth(), false) + // CreateEntry reports precondition refusals in its coded response, also on + // StreamMutateEntry. Leave this check to the locked handler so mount clients + // recognize the verdict and fence writeback publication. + return s.checkClientEntry(ctx, sc, m, p, req.GetEntry(), nil, req.GetChunkAuth(), false) } func (s *filerGrpcScope) checkUpdate(ctx context.Context, sc *scope, m string, req *filer_pb.UpdateEntryRequest) error { @@ -400,11 +457,14 @@ func (s *filerGrpcScope) checkUpdate(ctx context.Context, sc *scope, m string, r if req.GetIsFromOtherCluster() || req.GetIsMoved() { return sc.deny(m, "is_from_other_cluster and is_moved are not allowed") } + if scopeNamesRemoteRenameSource(req.GetCondition(), req.GetExpectedExtended()) { + return sc.deny(m, "remote rename source is filer-owned") + } p, err := sc.checkPath(m, req.GetDirectory(), req.GetEntry().GetName(), true) if err != nil { return err } - return s.checkClientEntry(ctx, sc, m, p, req.GetEntry(), req.GetChunkAuth(), true) + return s.checkClientEntry(ctx, sc, m, p, req.GetEntry(), req.GetCondition(), req.GetChunkAuth(), true) } func (s *filerGrpcScope) checkAppend(ctx context.Context, sc *scope, m string, req *filer_pb.AppendToEntryRequest) error { @@ -415,7 +475,7 @@ func (s *filerGrpcScope) checkAppend(ctx context.Context, sc *scope, m string, r if err := s.checkAncestors(ctx, sc, m, p); err != nil { return err } - return s.checkClientEntry(ctx, sc, m, p, &filer_pb.Entry{Name: req.GetEntryName(), Chunks: req.GetChunks()}, req.GetChunkAuth(), false) + return s.checkClientEntry(ctx, sc, m, p, &filer_pb.Entry{Name: req.GetEntryName(), Chunks: req.GetChunks()}, nil, req.GetChunkAuth(), false) } // checkAncestors refuses a write at p that would make an ancestor outside the @@ -444,6 +504,9 @@ func (sc *scope) checkDelete(m string, req *filer_pb.DeleteEntryRequest) error { if req.GetIsFromOtherCluster() || req.GetIsMoved() { return sc.deny(m, "is_from_other_cluster and is_moved are not allowed") } + if scopeNamesRemoteRenameSource(nil, req.GetExpectedExtended()) { + return sc.deny(m, "remote rename source is filer-owned") + } p, err := sc.checkPath(m, req.GetDirectory(), req.GetName(), true) if err != nil { return err @@ -542,7 +605,11 @@ func (s *filerGrpcScope) unary(ctx context.Context, req any, info *grpc.UnarySer if !ok || reflect.TypeOf(req) != expected { return nil, sc.deny(info.FullMethod, "not available to a scoped token") } - return s.unaryScoped(s.withWriteAuthority(ctx, sc), sc, req, handler) + resp, err := s.unaryScoped(s.withWriteAuthority(ctx, sc), sc, req, handler) + if err != nil { + return resp, err + } + return scopeRedactResponse(resp), nil } // isScopeFilerConf reports whether (dir, name) is the filer's per-path config diff --git a/weed/server/filer_grpc_scope_entry_equal_test.go b/weed/server/filer_grpc_scope_entry_equal_test.go new file mode 100644 index 0000000000..014c237fed --- /dev/null +++ b/weed/server/filer_grpc_scope_entry_equal_test.go @@ -0,0 +1,383 @@ +package weed_server + +import ( + "context" + "errors" + "fmt" + "net" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/security" + "github.com/seaweedfs/seaweedfs/weed/util" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +func scopedEntryEqualCondition(expected *filer_pb.Entry, equalFirst bool) *filer_pb.WriteCondition { + equal := &filer_pb.WriteCondition_Clause{ + Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, + ExpectedEntry: proto.Clone(expected).(*filer_pb.Entry), + } + exists := &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_EXISTS} + clauses := []*filer_pb.WriteCondition_Clause{exists, equal} + if equalFirst { + clauses[0], clauses[1] = clauses[1], clauses[0] + } + return &filer_pb.WriteCondition{Clauses: clauses} +} + +func runScopedEntryEqualCondition(t *testing.T, method string, ctx context.Context, initial *filer.Entry, request *filer_pb.Entry, condition *filer_pb.WriteCondition, beforeHandler ...func(*filer.Entry)) (error, bool, *filer.Entry, int) { + t.Helper() + store := newRenameTestStore() + path := string(initial.FullPath) + store.entries[path] = initial + queue := &captureQueue{} + swapNotificationQueue(t, queue) + fs, scope := newScopeRetentionServer(t, store) + + var req any + switch method { + case "CreateEntry": + req = &filer_pb.CreateEntryRequest{ + Directory: aliceWS, + Entry: request, + Condition: condition, + SkipCheckParentDirectory: true, + } + case "UpdateEntry": + req = &filer_pb.UpdateEntryRequest{ + Directory: aliceWS, + Entry: request, + Condition: condition, + } + default: + t.Fatalf("unexpected method %q", method) + } + + called := false + response, err := scope.unary(ctx, req, &grpc.UnaryServerInfo{FullMethod: scopeFilerMethodPrefix + method}, func(handlerCtx context.Context, handlerReq any) (any, error) { + called = true + for _, update := range beforeHandler { + update(store.entries[path]) + } + switch method { + case "CreateEntry": + return fs.CreateEntry(handlerCtx, handlerReq.(*filer_pb.CreateEntryRequest)) + case "UpdateEntry": + return fs.UpdateEntry(handlerCtx, handlerReq.(*filer_pb.UpdateEntryRequest)) + default: + t.Fatalf("unexpected method %q", method) + return nil, nil + } + }) + + if err == nil && method == "CreateEntry" { + cr := response.(*filer_pb.CreateEntryResponse) + if cr.GetErrorCode() != filer_pb.FilerError_OK { + if cr.GetErrorCode() != filer_pb.FilerError_PRECONDITION_FAILED { + t.Fatalf("unexpected create refusal: %v", cr) + } + err = fmt.Errorf("%s: %w", cr.GetError(), filer_pb.ErrPreconditionFailed) + } + } + + got, findErr := store.FindEntry(context.Background(), util.FullPath(path)) + if findErr != nil { + t.Fatalf("find entry after %s: %v", method, findErr) + } + fs.filer.FileIdDeletionQueue.Consume(func(ids []string) { + if len(ids) != 0 { + t.Errorf("%s queued unexpected chunk deletions: %v", method, ids) + } + }) + return err, called, got, len(queue.snapshot()) +} + +func pendingRemoteRenameEntry(name string) *filer.Entry { + entry := newFileEntry(scopeJoin(aliceWS, name), 1) + entry.Remote = &filer_pb.RemoteEntry{ + StorageName: "s3", + LastLocalSyncTsNs: 123, + RemoteETag: "etag", + RemoteMtime: 456, + RemoteSize: 789, + } + entry.Extended = map[string][]byte{ + "visible-tag": []byte("kept"), + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + } + return entry +} + +func TestScopedEntryEqualRefusesHiddenRemoteRenameMarker(t *testing.T) { + for _, method := range []string{"CreateEntry", "UpdateEntry"} { + for _, equalFirst := range []bool{true, false} { + label := "second" + if equalFirst { + label = "first" + } + t.Run(method+"/equal-"+label, func(t *testing.T) { + initial := pendingRemoteRenameEntry("conditional-" + method) + before := proto.Clone(initial.ToProtoEntry()).(*filer_pb.Entry) + request := proto.Clone(before).(*filer_pb.Entry) + delete(request.Extended, filer.ExtRemoteRenameSourceKey) + request.RemoteEntry = nil + err, called, got, events := runScopedEntryEqualCondition(t, method, scopedRetentionContext(), initial, request, scopedEntryEqualCondition(request, equalFirst)) + if (method == "CreateEntry" && !errors.Is(err, filer_pb.ErrPreconditionFailed)) || (method == "UpdateEntry" && status.Code(err) != codes.FailedPrecondition) { + t.Fatalf("%s error = %v, want FailedPrecondition", method, err) + } + if !strings.Contains(err.Error(), "scoped IF_ENTRY_EQUAL") { + t.Fatalf("%s error = %v, want a clear scoped IF_ENTRY_EQUAL refusal", method, err) + } + if strings.Contains(err.Error(), "/buckets/t1/source") { + t.Fatalf("%s error exposed the hidden source path: %v", method, err) + } + if called != (method == "CreateEntry") { + t.Fatalf("%s handler called=%v, want Create refusal under lock and Update admission refusal", method, called) + } + if !proto.Equal(got.ToProtoEntry(), before) { + t.Fatalf("%s changed the stored entry: got=%v want=%v", method, got.ToProtoEntry(), before) + } + if events != 0 { + t.Fatalf("%s emitted %d metadata events on refusal", method, events) + } + }) + } + } +} + +func TestScopedEntryEqualWithoutHiddenMarkerIsAllowed(t *testing.T) { + for _, method := range []string{"CreateEntry", "UpdateEntry"} { + t.Run(method, func(t *testing.T) { + initial := newFileEntry(scopeJoin(aliceWS, "conditional-"+method), 1) + request := proto.Clone(initial.ToProtoEntry()).(*filer_pb.Entry) + err, called, _, _ := runScopedEntryEqualCondition(t, method, scopedRetentionContext(), initial, request, scopedEntryEqualCondition(request, true)) + if err != nil || !called { + t.Fatalf("%s error=%v called=%v, want allowed scoped conditional write", method, err, called) + } + }) + } +} + +func TestUnscopedEntryEqualWithHiddenMarkerIsUnchanged(t *testing.T) { + contexts := []struct { + name string + ctx context.Context + }{ + {name: "tokenless", ctx: context.Background()}, + {name: "unscoped filer token", ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs( + "authorization", "Bearer "+unscopedToken(), + ))}, + } + for _, method := range []string{"CreateEntry", "UpdateEntry"} { + for _, tc := range contexts { + t.Run(method+"/"+tc.name, func(t *testing.T) { + initial := pendingRemoteRenameEntry(tc.name + "-" + method) + expected := initial.ToProtoEntry() + err, called, _, _ := runScopedEntryEqualCondition(t, method, tc.ctx, initial, expected, scopedEntryEqualCondition(expected, true)) + if err != nil || !called { + t.Fatalf("%s error=%v called=%v, want unscoped conditional write unchanged", method, err, called) + } + }) + } + } +} + +func TestScopedEntryEqualRechecksPendingRenameUnderLock(t *testing.T) { + for _, method := range []string{"CreateEntry", "UpdateEntry"} { + t.Run(method, func(t *testing.T) { + initial := pendingRemoteRenameEntry("late-" + method) + expected := proto.Clone(initial.ToProtoEntry()).(*filer_pb.Entry) + delete(initial.Extended, filer.ExtRemoteRenameSourceKey) + request := proto.Clone(initial.ToProtoEntry()).(*filer_pb.Entry) + request.RemoteEntry = nil + request.Content = []byte("replacement") + err, called, got, events := runScopedEntryEqualCondition(t, method, scopedRetentionContext(), initial, request, scopedEntryEqualCondition(expected, true), func(current *filer.Entry) { + current.Extended[filer.ExtRemoteRenameSourceKey] = []byte("/buckets/t1/source") + }) + if !called || (method == "CreateEntry" && !errors.Is(err, filer_pb.ErrPreconditionFailed)) || (method == "UpdateEntry" && status.Code(err) != codes.FailedPrecondition) || !strings.Contains(err.Error(), "scoped IF_ENTRY_EQUAL") { + t.Fatalf("%s error=%v called=%v, want locked FailedPrecondition refusal", method, err, called) + } + if !proto.Equal(got.ToProtoEntry(), expected) { + t.Fatalf("%s changed stored entry on locked refusal: got=%v want=%v", method, got.ToProtoEntry(), expected) + } + if events != 0 { + t.Fatalf("%s emitted %d metadata events on locked refusal", method, events) + } + }) + } +} + +type pendingRenameCreateServer struct { + *FilerServer + beforeCreate func() +} + +func (s *pendingRenameCreateServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + if s.beforeCreate != nil { + s.beforeCreate() + } + return s.FilerServer.CreateEntry(ctx, req) +} + +func TestScopedEntryEqualCreateClientRecognizesDefiniteRefusal(t *testing.T) { + for _, late := range []bool{false, true} { + name := "stored marker" + if late { + name = "marker after admission" + } + t.Run(name, func(t *testing.T) { + initial := pendingRemoteRenameEntry("client-refusal") + expected := proto.Clone(initial.ToProtoEntry()).(*filer_pb.Entry) + if late { + delete(initial.Extended, filer.ExtRemoteRenameSourceKey) + } + request := proto.Clone(initial.ToProtoEntry()).(*filer_pb.Entry) + delete(request.Extended, filer.ExtRemoteRenameSourceKey) + request.RemoteEntry = nil + store := newRenameTestStore() + store.entries[string(initial.FullPath)] = initial + queue := &captureQueue{} + swapNotificationQueue(t, queue) + fs, scope := newScopeRetentionServer(t, store) + impl := &pendingRenameCreateServer{FilerServer: fs} + if late { + impl.beforeCreate = func() { initial.Extended[filer.ExtRemoteRenameSourceKey] = []byte("/buckets/t1/source") } + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + server := grpc.NewServer(scope.ServerOptions()...) + filer_pb.RegisterSeaweedFilerServer(server, impl) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { server.Stop(); _ = listener.Close() }) + conn, err := grpc.NewClient("passthrough:///"+listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + auth, _ := metadata.FromIncomingContext(scopedRetentionContext()) + ctx, cancel := context.WithTimeout(metadata.NewOutgoingContext(context.Background(), auth.Copy()), 5*time.Second) + defer cancel() + client := filer_pb.NewSeaweedFilerClient(conn) + req := &filer_pb.CreateEntryRequest{Directory: aliceWS, Entry: request, Condition: scopedEntryEqualCondition(expected, true), SkipCheckParentDirectory: true} + _, err = filer_pb.CreateEntryWithResponse(ctx, client, req) + if !errors.Is(err, filer_pb.ErrPreconditionFailed) || !filer_pb.IsFilerVerdict(err) { + t.Fatalf("create client error = %v, want definite precondition refusal", err) + } + raw, err := client.CreateEntry(ctx, req) + if err != nil || raw.GetErrorCode() != filer_pb.FilerError_PRECONDITION_FAILED || !strings.Contains(raw.GetError(), "scoped IF_ENTRY_EQUAL") { + t.Fatalf("raw create response=%v error=%v, want clear coded precondition refusal", raw, err) + } + stream, err := client.StreamMutateEntry(ctx) + if err != nil { + t.Fatal(err) + } + if err := stream.Send(&filer_pb.StreamMutateEntryRequest{RequestId: 9, Request: &filer_pb.StreamMutateEntryRequest_CreateRequest{CreateRequest: req}}); err != nil { + t.Fatal(err) + } + if err := stream.CloseSend(); err != nil { + t.Fatal(err) + } + streamed, err := stream.Recv() + if err != nil || streamed.GetRequestId() != 9 || streamed.GetCreateResponse().GetErrorCode() != filer_pb.FilerError_PRECONDITION_FAILED || !strings.Contains(streamed.GetCreateResponse().GetError(), "scoped IF_ENTRY_EQUAL") { + t.Fatalf("streamed create response=%v error=%v, want nested coded refusal", streamed, err) + } + + got, err := store.FindEntry(context.Background(), initial.FullPath) + if err != nil || !proto.Equal(got.ToProtoEntry(), expected) { + t.Fatalf("stored entry changed: got=%v error=%v", got, err) + } + if events := len(queue.snapshot()); events != 0 { + t.Fatalf("refusal emitted %d events", events) + } + }) + } +} + +func TestScopedLocalOverwriteEndsPendingRemoteRename(t *testing.T) { + const dir, name = "/buckets/b/dst", "a.jpg" + for _, method := range []string{"CreateEntry", "UpdateEntry"} { + t.Run(method, func(t *testing.T) { + client := copyingRenameRemoteClient{&renameRemoteClient{copyErr: errors.New("copy refused")}} + server, store := newRenameRemoteTestServer(t, client) + store.entries["/buckets/b/src/a.jpg"] = remoteOnlyRenameEntry("/buckets/b/src/a.jpg", 101) + store.entries[dir+"/"+name] = remoteOnlyRenameEntry(dir+"/"+name, 202) + if err := renameFile(server, "/buckets/b/src/a.jpg", dir+"/"+name); err != nil { + t.Fatalf("rename: %v", err) + } + pending, err := store.FindEntry(context.Background(), dir+"/"+name) + if err != nil || string(pending.Extended[filer.ExtRemoteRenameSourceKey]) != "/buckets/b/src/a.jpg" { + t.Fatalf("pending rename entry=%v err=%v, want the source marker", pending, err) + } + + scope := newFilerGrpcScope(scopeConfig{ + signingKey: func() security.SigningKey { return security.SigningKey(scopeTestKey) }, + }, server) + ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs( + "authorization", "Bearer "+scopedToken("overwrite", time.Hour, []string{dir}, nil), + )) + call := func(method string, req any) (any, error) { + return scope.unary(ctx, req, &grpc.UnaryServerInfo{FullMethod: scopeFilerMethodPrefix + method}, func(handlerCtx context.Context, handlerReq any) (any, error) { + switch r := handlerReq.(type) { + case *filer_pb.CreateEntryRequest: + return server.CreateEntry(handlerCtx, r) + case *filer_pb.UpdateEntryRequest: + return server.UpdateEntry(handlerCtx, r) + case *filer_pb.LookupDirectoryEntryRequest: + return server.LookupDirectoryEntry(handlerCtx, r) + } + return nil, fmt.Errorf("unexpected request %T", handlerReq) + }) + } + + local := &filer_pb.Entry{Name: name, Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 5}, Content: []byte("local")} + if method == "CreateEntry" { + resp, err := call(method, &filer_pb.CreateEntryRequest{Directory: dir, Entry: local}) + if err != nil || resp.(*filer_pb.CreateEntryResponse).GetError() != "" { + t.Fatalf("local overwrite: resp=%v err=%v", resp, err) + } + } else if _, err := call(method, &filer_pb.UpdateEntryRequest{Directory: dir, Entry: local}); err != nil { + t.Fatalf("local overwrite: %v", err) + } + overwritten, err := store.FindEntry(context.Background(), dir+"/"+name) + if err != nil { + t.Fatalf("find overwritten entry: %v", err) + } + if _, marked := overwritten.Extended[filer.ExtRemoteRenameSourceKey]; marked { + t.Fatalf("local overwrite kept the pending rename marker: %v", overwritten.ToProtoEntry()) + } + + looked, err := call("LookupDirectoryEntry", &filer_pb.LookupDirectoryEntryRequest{Directory: dir, Name: name}) + if err != nil { + t.Fatalf("scoped lookup: %v", err) + } + current := looked.(*filer_pb.LookupDirectoryEntryResponse).GetEntry() + next := proto.Clone(current).(*filer_pb.Entry) + next.Content = []byte("again") + condition := &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{ + Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, + ExpectedEntry: current, + }}} + if _, err := call("UpdateEntry", &filer_pb.UpdateEntryRequest{Directory: dir, Entry: next, Condition: condition}); err != nil { + t.Fatalf("guarded write after the local overwrite: %v", err) + } + got, err := store.FindEntry(context.Background(), dir+"/"+name) + if err != nil { + t.Fatalf("find entry after guarded write: %v", err) + } + if string(got.Content) != "again" { + t.Fatalf("after guarded write content=%q, want again", got.Content) + } + }) + } +} diff --git a/weed/server/filer_grpc_scope_harness_test.go b/weed/server/filer_grpc_scope_harness_test.go index 88509c4d7f..5c646ffe5f 100644 --- a/weed/server/filer_grpc_scope_harness_test.go +++ b/weed/server/filer_grpc_scope_harness_test.go @@ -133,7 +133,13 @@ func (f *scopeFakeFiler) scopeKvGet(_ context.Context, key []byte) ([]byte, erro func (f *scopeFakeFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { f.record("LookupDirectoryEntry", req) - return &filer_pb.LookupDirectoryEntryResponse{}, nil + f.mu.Lock() + defer f.mu.Unlock() + entry := f.entries[scopeJoin(req.GetDirectory(), req.GetName())] + if entry == nil { + return &filer_pb.LookupDirectoryEntryResponse{}, nil + } + return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil } func (f *scopeFakeFiler) LookupDirectoryEntries(_ context.Context, req *filer_pb.LookupDirectoryEntriesRequest) (*filer_pb.LookupDirectoryEntriesResponse, error) { diff --git a/weed/server/filer_grpc_scope_hidden_reads_test.go b/weed/server/filer_grpc_scope_hidden_reads_test.go index cff01aa823..28f4872c64 100644 --- a/weed/server/filer_grpc_scope_hidden_reads_test.go +++ b/weed/server/filer_grpc_scope_hidden_reads_test.go @@ -6,12 +6,268 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" ) +func TestScopeLookupHidesRemoteRenameSourceKey(t *testing.T) { + h := newScopeHarness(t) + entry := entryWith("visible", "1,abc") + entry.Extended = map[string][]byte{ + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + "client-tag": []byte("keep"), + } + h.fake.put(aliceWS+"/visible", entry) + h.fake.put(aliceWS+"/other", entryWith("other")) + c := h.client(scopedToken("alice", time.Hour, []string{aliceWS}, nil)) + + single, err := c.LookupDirectoryEntry(scopeCtx(t), &filer_pb.LookupDirectoryEntryRequest{Directory: aliceWS, Name: "visible"}) + if err != nil { + t.Fatalf("single lookup: %v", err) + } + if got := single.GetEntry().GetExtended()[filer.ExtRemoteRenameSourceKey]; len(got) != 0 { + t.Fatalf("single scoped lookup exposed remote rename source %q", got) + } + if got := string(single.GetEntry().GetExtended()["client-tag"]); got != "keep" { + t.Fatalf("single scoped lookup lost client metadata %q", got) + } + + batch, err := c.LookupDirectoryEntries(scopeCtx(t), &filer_pb.LookupDirectoryEntriesRequest{Requests: []*filer_pb.LookupDirectoryEntryRequest{ + {Directory: aliceWS, Name: "visible"}, + {Directory: aliceWS, Name: "other"}, + }}) + if err != nil { + t.Fatalf("batched lookup: %v", err) + } + if got := batch.GetResults()[0].GetEntry().GetExtended()[filer.ExtRemoteRenameSourceKey]; len(got) != 0 { + t.Fatalf("batched scoped lookup exposed remote rename source %q", got) + } + stored, err := h.fake.scopeFindEntry(context.Background(), aliceWS+"/visible") + if err != nil { + t.Fatalf("read stored entry: %v", err) + } + if got := stored.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(got) == 0 { + t.Fatal("scoped lookup redaction mutated the stored entry") + } + for _, tc := range []struct { + name string + token string + }{ + {name: "tokenless"}, + {name: "unscoped", token: unscopedToken()}, + } { + t.Run(tc.name, func(t *testing.T) { + resp, err := h.client(tc.token).LookupDirectoryEntry(scopeCtx(t), &filer_pb.LookupDirectoryEntryRequest{Directory: aliceWS, Name: "visible"}) + if err != nil { + t.Fatalf("%s lookup: %v", tc.name, err) + } + if got := resp.GetEntry().GetExtended()[filer.ExtRemoteRenameSourceKey]; len(got) == 0 { + t.Fatalf("%s lookup lost remote rename source", tc.name) + } + }) + } +} + +func TestScopeResponseRedactionCoversMutationCarriers(t *testing.T) { + marker := func(name string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Extended: map[string][]byte{ + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + }} + } + metadata := func() *filer_pb.SubscribeMetadataResponse { + return &filer_pb.SubscribeMetadataResponse{EventNotification: &filer_pb.EventNotification{ + OldEntry: marker("old"), + NewEntry: marker("new"), + }} + } + tests := []struct { + name string + resp any + entries func(any) []*filer_pb.Entry + }{ + { + name: "create metadata", + resp: &filer_pb.CreateEntryResponse{MetadataEvent: metadata()}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.CreateEntryResponse).GetMetadataEvent().GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + { + name: "update metadata", + resp: &filer_pb.UpdateEntryResponse{MetadataEvent: metadata()}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.UpdateEntryResponse).GetMetadataEvent().GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + { + name: "delete metadata", + resp: &filer_pb.DeleteEntryResponse{MetadataEvent: metadata()}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.DeleteEntryResponse).GetMetadataEvent().GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + { + name: "stream rename", + resp: &filer_pb.StreamRenameEntryResponse{EventNotification: metadata().GetEventNotification()}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.StreamRenameEntryResponse).GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + { + name: "stream mutate create", + resp: &filer_pb.StreamMutateEntryResponse{Response: &filer_pb.StreamMutateEntryResponse_CreateResponse{ + CreateResponse: &filer_pb.CreateEntryResponse{MetadataEvent: metadata()}, + }}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.StreamMutateEntryResponse).GetCreateResponse().GetMetadataEvent().GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + { + name: "stream mutate update", + resp: &filer_pb.StreamMutateEntryResponse{Response: &filer_pb.StreamMutateEntryResponse_UpdateResponse{ + UpdateResponse: &filer_pb.UpdateEntryResponse{MetadataEvent: metadata()}, + }}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.StreamMutateEntryResponse).GetUpdateResponse().GetMetadataEvent().GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + { + name: "stream mutate delete", + resp: &filer_pb.StreamMutateEntryResponse{Response: &filer_pb.StreamMutateEntryResponse_DeleteResponse{ + DeleteResponse: &filer_pb.DeleteEntryResponse{MetadataEvent: metadata()}, + }}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.StreamMutateEntryResponse).GetDeleteResponse().GetMetadataEvent().GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + { + name: "stream mutate rename", + resp: &filer_pb.StreamMutateEntryResponse{Response: &filer_pb.StreamMutateEntryResponse_RenameResponse{ + RenameResponse: &filer_pb.StreamRenameEntryResponse{EventNotification: metadata().GetEventNotification()}, + }}, + entries: func(resp any) []*filer_pb.Entry { + event := resp.(*filer_pb.StreamMutateEntryResponse).GetRenameResponse().GetEventNotification() + return []*filer_pb.Entry{event.GetOldEntry(), event.GetNewEntry()} + }, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + redacted := scopeRedactResponse(tc.resp) + if redacted == tc.resp { + t.Fatal("response was not cloned before redaction") + } + for _, entry := range tc.entries(redacted) { + if marker := entry.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) != 0 { + t.Fatalf("redacted response exposed remote rename source %q", marker) + } + } + for _, entry := range tc.entries(tc.resp) { + if marker := entry.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) == 0 { + t.Fatal("redaction mutated the source response") + } + } + }) + } +} + +func TestScopedUnaryMutationResponseHidesMetadataMarker(t *testing.T) { + h := newScopeHarness(t) + ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs( + "authorization", "Bearer "+scopedToken("alice", time.Hour, []string{aliceWS}, nil), + )) + metadataEvent := func() *filer_pb.SubscribeMetadataResponse { + return &filer_pb.SubscribeMetadataResponse{EventNotification: &filer_pb.EventNotification{ + NewEntry: &filer_pb.Entry{Extended: map[string][]byte{ + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + }}, + }} + } + cases := []struct { + name string + method string + request any + response any + marker func(any) []byte + }{ + { + name: "create", + method: "CreateEntry", + request: &filer_pb.CreateEntryRequest{ + Directory: aliceWS, Entry: entryWith("created"), SkipCheckParentDirectory: true, + }, + response: &filer_pb.CreateEntryResponse{MetadataEvent: metadataEvent()}, + marker: func(resp any) []byte { + return resp.(*filer_pb.CreateEntryResponse).GetMetadataEvent().GetEventNotification().GetNewEntry().GetExtended()[filer.ExtRemoteRenameSourceKey] + }, + }, + { + name: "update", + method: "UpdateEntry", + request: &filer_pb.UpdateEntryRequest{Directory: aliceWS, Entry: entryWith("updated")}, + response: &filer_pb.UpdateEntryResponse{MetadataEvent: metadataEvent()}, + marker: func(resp any) []byte { + return resp.(*filer_pb.UpdateEntryResponse).GetMetadataEvent().GetEventNotification().GetNewEntry().GetExtended()[filer.ExtRemoteRenameSourceKey] + }, + }, + { + name: "delete", + method: "DeleteEntry", + request: &filer_pb.DeleteEntryRequest{Directory: aliceWS, Name: "deleted"}, + response: &filer_pb.DeleteEntryResponse{MetadataEvent: metadataEvent()}, + marker: func(resp any) []byte { + return resp.(*filer_pb.DeleteEntryResponse).GetMetadataEvent().GetEventNotification().GetNewEntry().GetExtended()[filer.ExtRemoteRenameSourceKey] + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + original := tc.response + resp, err := h.scope.unary(ctx, tc.request, &grpc.UnaryServerInfo{FullMethod: scopeFilerMethodPrefix + tc.method}, func(context.Context, any) (any, error) { + return original, nil + }) + if err != nil { + t.Fatalf("scoped %s: %v", tc.method, err) + } + if got := tc.marker(resp); len(got) != 0 { + t.Fatalf("scoped %s exposed remote rename source %q", tc.method, got) + } + if got := tc.marker(original); len(got) == 0 { + t.Fatalf("scoped %s redaction mutated handler response", tc.method) + } + for _, caller := range []struct { + name string + ctx context.Context + }{ + {name: "tokenless", ctx: context.Background()}, + {name: "unscoped", ctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs("authorization", "Bearer "+unscopedToken()))}, + } { + t.Run(caller.name, func(t *testing.T) { + resp, err := h.scope.unary(caller.ctx, tc.request, &grpc.UnaryServerInfo{FullMethod: scopeFilerMethodPrefix + tc.method}, func(context.Context, any) (any, error) { + return original, nil + }) + if err != nil { + t.Fatalf("%s %s: %v", caller.name, tc.method, err) + } + if got := tc.marker(resp); len(got) == 0 { + t.Fatalf("%s %s lost remote rename source", caller.name, tc.method) + } + }) + } + }) + } +} + func TestScopeHidesFilerConfFromSingleAndBatchLookups(t *testing.T) { h := newScopeHarness(t) h.fake.put(scopeFilerConfDir+"/visible-one", entryWith("visible-one")) diff --git a/weed/server/filer_grpc_scope_mutation_flags_test.go b/weed/server/filer_grpc_scope_mutation_flags_test.go index 70299a1bf2..a869e6f363 100644 --- a/weed/server/filer_grpc_scope_mutation_flags_test.go +++ b/weed/server/filer_grpc_scope_mutation_flags_test.go @@ -4,6 +4,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" ) @@ -53,3 +54,49 @@ func TestScopeRejectsMovedMutations(t *testing.T) { return err }) } + +func TestScopeRejectsConditionsOnRemoteRenameSource(t *testing.T) { + h := newScopeHarness(t) + c := h.client(scopedToken("alice", time.Hour, []string{aliceWS}, nil)) + guess := []byte("/buckets/other/file") + notEqual := &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{ + Kind: filer_pb.WriteCondition_IF_EXTENDED_NOT_EQUAL, ExtKey: filer.ExtRemoteRenameSourceKey, ExtValue: string(guess), + }}} + + expectScopeDenied(t, h, "CreateEntry", "create conditioned on the marker", func() error { + _, err := c.CreateEntry(scopeCtx(t), &filer_pb.CreateEntryRequest{ + Directory: aliceWS, Entry: &filer_pb.Entry{Name: "file"}, Condition: notEqual, + }) + return err + }) + expectScopeDenied(t, h, "UpdateEntry", "update conditioned on the marker", func() error { + _, err := c.UpdateEntry(scopeCtx(t), &filer_pb.UpdateEntryRequest{ + Directory: aliceWS, Entry: &filer_pb.Entry{Name: "file"}, Condition: notEqual, + }) + return err + }) + expectScopeDenied(t, h, "UpdateEntry", "update gated on the marker", func() error { + _, err := c.UpdateEntry(scopeCtx(t), &filer_pb.UpdateEntryRequest{ + Directory: aliceWS, Entry: &filer_pb.Entry{Name: "file"}, + Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{ + Kind: filer_pb.WriteCondition_IF_EXTENDED_TIME_ELAPSED, ExtKey: "client.expiry", + GateKey: filer.ExtRemoteRenameSourceKey, GateValue: string(guess), + }}}, + }) + return err + }) + expectScopeDenied(t, h, "UpdateEntry", "update expecting the marker", func() error { + _, err := c.UpdateEntry(scopeCtx(t), &filer_pb.UpdateEntryRequest{ + Directory: aliceWS, Entry: &filer_pb.Entry{Name: "file"}, + ExpectedExtended: map[string][]byte{filer.ExtRemoteRenameSourceKey: guess}, + }) + return err + }) + expectScopeDenied(t, h, "DeleteEntry", "delete expecting the marker", func() error { + _, err := c.DeleteEntry(scopeCtx(t), &filer_pb.DeleteEntryRequest{ + Directory: aliceWS, Name: "file", + ExpectedExtended: map[string][]byte{filer.ExtRemoteRenameSourceKey: guess}, + }) + return err + }) +} diff --git a/weed/server/filer_grpc_scope_redact.go b/weed/server/filer_grpc_scope_redact.go new file mode 100644 index 0000000000..f19509b55e --- /dev/null +++ b/weed/server/filer_grpc_scope_redact.go @@ -0,0 +1,205 @@ +package weed_server + +import ( + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "google.golang.org/protobuf/proto" +) + +func scopeEntryNeedsRedaction(entry *filer_pb.Entry) bool { + if entry == nil { + return false + } + _, ok := entry.GetExtended()[filer.ExtRemoteRenameSourceKey] + return ok +} + +func redactScopeEntry(entry *filer_pb.Entry) { + if entry != nil { + delete(entry.GetExtended(), filer.ExtRemoteRenameSourceKey) + } +} + +func redactScopeMetadataResponseInPlace(resp *filer_pb.SubscribeMetadataResponse) { + if resp == nil { + return + } + if notification := resp.GetEventNotification(); notification != nil { + redactScopeEntry(notification.GetOldEntry()) + redactScopeEntry(notification.GetNewEntry()) + } + for _, nested := range resp.GetEvents() { + redactScopeMetadataResponseInPlace(nested) + } +} + +// scopeRedactLookupResponse clones a scoped lookup response only when the +// filer-owned remote rename marker is present. The handler may have returned +// an entry backed by the filer store, so the response must not be edited in +// place. +func scopeRedactLookupResponse(resp *filer_pb.LookupDirectoryEntryResponse) *filer_pb.LookupDirectoryEntryResponse { + if resp == nil || !scopeEntryNeedsRedaction(resp.GetEntry()) { + return resp + } + out := proto.Clone(resp).(*filer_pb.LookupDirectoryEntryResponse) + redactScopeEntry(out.GetEntry()) + return out +} + +// scopeRedactBatchLookupResponse applies the same rule to every positional +// result while preserving the response shape and all other entry metadata. +func scopeRedactBatchLookupResponse(resp *filer_pb.LookupDirectoryEntriesResponse) *filer_pb.LookupDirectoryEntriesResponse { + if resp == nil { + return nil + } + needsRedaction := false + for _, result := range resp.GetResults() { + if result != nil && scopeEntryNeedsRedaction(result.GetEntry()) { + needsRedaction = true + break + } + } + if !needsRedaction { + return resp + } + out := proto.Clone(resp).(*filer_pb.LookupDirectoryEntriesResponse) + for _, result := range out.GetResults() { + if result != nil { + redactScopeEntry(result.GetEntry()) + } + } + return out +} + +func scopeRedactListResponse(resp *filer_pb.ListEntriesResponse) *filer_pb.ListEntriesResponse { + if resp == nil || !scopeEntryNeedsRedaction(resp.GetEntry()) { + return resp + } + out := proto.Clone(resp).(*filer_pb.ListEntriesResponse) + redactScopeEntry(out.GetEntry()) + return out +} + +func scopeMetadataNeedsRedaction(resp *filer_pb.SubscribeMetadataResponse) bool { + if resp == nil { + return false + } + if notification := resp.GetEventNotification(); notification != nil { + if scopeEntryNeedsRedaction(notification.GetOldEntry()) || scopeEntryNeedsRedaction(notification.GetNewEntry()) { + return true + } + } + for _, nested := range resp.GetEvents() { + if scopeMetadataNeedsRedaction(nested) { + return true + } + } + return false +} + +// scopeRedactMetadataResponse recursively clones a subscription response so +// old and new entries in both the head and batched Events cannot mutate the +// source log or filer state while the internal marker is removed. +func scopeRedactMetadataResponse(resp *filer_pb.SubscribeMetadataResponse) *filer_pb.SubscribeMetadataResponse { + if resp == nil || !scopeMetadataNeedsRedaction(resp) { + return resp + } + out := proto.Clone(resp).(*filer_pb.SubscribeMetadataResponse) + redactScopeMetadataResponseInPlace(out) + return out +} + +func scopeRedactCreateResponse(resp *filer_pb.CreateEntryResponse) *filer_pb.CreateEntryResponse { + if resp == nil || !scopeMetadataNeedsRedaction(resp.GetMetadataEvent()) { + return resp + } + out := proto.Clone(resp).(*filer_pb.CreateEntryResponse) + redactScopeMetadataResponseInPlace(out.GetMetadataEvent()) + return out +} + +func scopeRedactUpdateResponse(resp *filer_pb.UpdateEntryResponse) *filer_pb.UpdateEntryResponse { + if resp == nil || !scopeMetadataNeedsRedaction(resp.GetMetadataEvent()) { + return resp + } + out := proto.Clone(resp).(*filer_pb.UpdateEntryResponse) + redactScopeMetadataResponseInPlace(out.GetMetadataEvent()) + return out +} + +func scopeRedactDeleteResponse(resp *filer_pb.DeleteEntryResponse) *filer_pb.DeleteEntryResponse { + if resp == nil || !scopeMetadataNeedsRedaction(resp.GetMetadataEvent()) { + return resp + } + out := proto.Clone(resp).(*filer_pb.DeleteEntryResponse) + redactScopeMetadataResponseInPlace(out.GetMetadataEvent()) + return out +} + +func scopeRenameResponseNeedsRedaction(resp *filer_pb.StreamRenameEntryResponse) bool { + if resp == nil || resp.GetEventNotification() == nil { + return false + } + return scopeEntryNeedsRedaction(resp.GetEventNotification().GetOldEntry()) || + scopeEntryNeedsRedaction(resp.GetEventNotification().GetNewEntry()) +} + +func scopeRedactRenameResponse(resp *filer_pb.StreamRenameEntryResponse) *filer_pb.StreamRenameEntryResponse { + if !scopeRenameResponseNeedsRedaction(resp) { + return resp + } + out := proto.Clone(resp).(*filer_pb.StreamRenameEntryResponse) + redactScopeEntry(out.GetEventNotification().GetOldEntry()) + redactScopeEntry(out.GetEventNotification().GetNewEntry()) + return out +} + +func scopeMutateResponseNeedsRedaction(resp *filer_pb.StreamMutateEntryResponse) bool { + if resp == nil { + return false + } + return scopeMetadataNeedsRedaction(resp.GetCreateResponse().GetMetadataEvent()) || + scopeMetadataNeedsRedaction(resp.GetUpdateResponse().GetMetadataEvent()) || + scopeMetadataNeedsRedaction(resp.GetDeleteResponse().GetMetadataEvent()) || + scopeRenameResponseNeedsRedaction(resp.GetRenameResponse()) +} + +func scopeRedactMutateResponse(resp *filer_pb.StreamMutateEntryResponse) *filer_pb.StreamMutateEntryResponse { + if !scopeMutateResponseNeedsRedaction(resp) { + return resp + } + out := proto.Clone(resp).(*filer_pb.StreamMutateEntryResponse) + redactScopeMetadataResponseInPlace(out.GetCreateResponse().GetMetadataEvent()) + redactScopeMetadataResponseInPlace(out.GetUpdateResponse().GetMetadataEvent()) + redactScopeMetadataResponseInPlace(out.GetDeleteResponse().GetMetadataEvent()) + if rename := out.GetRenameResponse(); rename != nil && rename.GetEventNotification() != nil { + redactScopeEntry(rename.GetEventNotification().GetOldEntry()) + redactScopeEntry(rename.GetEventNotification().GetNewEntry()) + } + return out +} + +func scopeRedactResponse(resp any) any { + switch out := resp.(type) { + case *filer_pb.LookupDirectoryEntryResponse: + return scopeRedactLookupResponse(out) + case *filer_pb.LookupDirectoryEntriesResponse: + return scopeRedactBatchLookupResponse(out) + case *filer_pb.ListEntriesResponse: + return scopeRedactListResponse(out) + case *filer_pb.SubscribeMetadataResponse: + return scopeRedactMetadataResponse(out) + case *filer_pb.CreateEntryResponse: + return scopeRedactCreateResponse(out) + case *filer_pb.UpdateEntryResponse: + return scopeRedactUpdateResponse(out) + case *filer_pb.DeleteEntryResponse: + return scopeRedactDeleteResponse(out) + case *filer_pb.StreamRenameEntryResponse: + return scopeRedactRenameResponse(out) + case *filer_pb.StreamMutateEntryResponse: + return scopeRedactMutateResponse(out) + default: + return resp + } +} diff --git a/weed/server/filer_grpc_scope_stream.go b/weed/server/filer_grpc_scope_stream.go index b62eb8a1ea..fe6e66618b 100644 --- a/weed/server/filer_grpc_scope_stream.go +++ b/weed/server/filer_grpc_scope_stream.go @@ -207,6 +207,7 @@ func (w *scopedStream) SendMsg(m any) error { } m = out } + m = scopeRedactResponse(m) return w.sendRaw(m) } diff --git a/weed/server/filer_grpc_scope_stream_test.go b/weed/server/filer_grpc_scope_stream_test.go index 3adf399ea2..e458a0896a 100644 --- a/weed/server/filer_grpc_scope_stream_test.go +++ b/weed/server/filer_grpc_scope_stream_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" @@ -15,7 +16,12 @@ import ( func TestScopeListEntriesBoundsDirectoriesAndFiltersFilerConf(t *testing.T) { h := newScopeHarness(t) h.fake.put(scopeFilerConfDir+"/"+scopeFilerConfName, entryWith(scopeFilerConfName)) - h.fake.put(scopeFilerConfDir+"/visible.json", entryWith("visible.json")) + visible := entryWith("visible.json") + visible.Extended = map[string][]byte{ + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + "client-tag": []byte("keep"), + } + h.fake.put(scopeFilerConfDir+"/visible.json", visible) c := h.client(scopedToken("alice", time.Hour, []string{scopeFilerConfDir}, nil)) stream, err := c.ListEntries(scopeCtx(t), &filer_pb.ListEntriesRequest{Directory: scopeFilerConfDir}) @@ -31,6 +37,14 @@ func TestScopeListEntriesBoundsDirectoriesAndFiltersFilerConf(t *testing.T) { if recvErr != nil { t.Fatalf("list response: %v", recvErr) } + if response.GetEntry().GetName() == "visible.json" { + if got := response.GetEntry().GetExtended()[filer.ExtRemoteRenameSourceKey]; len(got) != 0 { + t.Fatalf("scoped list exposed remote rename source %q", got) + } + if got := string(response.GetEntry().GetExtended()["client-tag"]); got != "keep" { + t.Fatalf("scoped list lost client metadata %q", got) + } + } names[response.GetEntry().GetName()] = true } if names[scopeFilerConfName] { @@ -39,6 +53,46 @@ func TestScopeListEntriesBoundsDirectoriesAndFiltersFilerConf(t *testing.T) { if !names["visible.json"] { t.Fatalf("scoped list dropped visible entry: %v", names) } + stored, err := h.fake.scopeFindEntry(context.Background(), scopeFilerConfDir+"/visible.json") + if err != nil { + t.Fatalf("read stored list entry: %v", err) + } + if got := stored.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(got) == 0 { + t.Fatal("scoped list redaction mutated the stored entry") + } + for _, tc := range []struct { + name string + token string + }{ + {name: "tokenless"}, + {name: "unscoped", token: unscopedToken()}, + } { + t.Run(tc.name, func(t *testing.T) { + list, err := h.client(tc.token).ListEntries(scopeCtx(t), &filer_pb.ListEntriesRequest{Directory: scopeFilerConfDir}) + if err != nil { + t.Fatalf("%s list: %v", tc.name, err) + } + found := false + for { + response, recvErr := list.Recv() + if errors.Is(recvErr, io.EOF) { + break + } + if recvErr != nil { + t.Fatalf("%s list response: %v", tc.name, recvErr) + } + if response.GetEntry().GetName() == "visible.json" { + found = true + if got := response.GetEntry().GetExtended()[filer.ExtRemoteRenameSourceKey]; len(got) == 0 { + t.Fatalf("%s list lost remote rename source", tc.name) + } + } + } + if !found { + t.Fatalf("%s list did not return visible entry", tc.name) + } + }) + } before := len(h.fake.received("ListEntries")) out, err := c.ListEntries(scopeCtx(t), &filer_pb.ListEntriesRequest{Directory: "/buckets/t10"}) @@ -162,10 +216,47 @@ func TestScopeStreamExpiryStopsFurtherMessages(t *testing.T) { } } +func TestScopedStreamMutationResponsesHideMetadataMarker(t *testing.T) { + marker := func(name string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Extended: map[string][]byte{ + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + }} + } + rename := &filer_pb.StreamRenameEntryResponse{EventNotification: &filer_pb.EventNotification{ + OldEntry: marker("old"), NewEntry: marker("new"), + }} + mutate := &filer_pb.StreamMutateEntryResponse{Response: &filer_pb.StreamMutateEntryResponse_RenameResponse{ + RenameResponse: rename, + }} + underlying := &scopeExpiryServerStream{ctx: context.Background()} + wrapped := &scopedStream{ServerStream: underlying, sc: &scope{exp: time.Now().Add(time.Minute)}} + if err := wrapped.SendMsg(mutate); err != nil { + t.Fatalf("send scoped mutation response: %v", err) + } + got, ok := underlying.sent.(*filer_pb.StreamMutateEntryResponse) + if !ok { + t.Fatalf("sent response type = %T, want StreamMutateEntryResponse", underlying.sent) + } + for _, entry := range []*filer_pb.Entry{ + got.GetRenameResponse().GetEventNotification().GetOldEntry(), + got.GetRenameResponse().GetEventNotification().GetNewEntry(), + } { + if marker := entry.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) != 0 { + t.Fatalf("scoped mutation response exposed remote rename source %q", marker) + } + } + for _, entry := range []*filer_pb.Entry{rename.GetEventNotification().GetOldEntry(), rename.GetEventNotification().GetNewEntry()} { + if marker := entry.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) == 0 { + t.Fatal("scoped mutation redaction mutated handler response") + } + } +} + type scopeExpiryServerStream struct { ctx context.Context recvCalls int sendCalls int + sent any } func (s *scopeExpiryServerStream) SetHeader(metadata.MD) error { return nil } @@ -173,8 +264,9 @@ func (s *scopeExpiryServerStream) SendHeader(metadata.MD) error { return nil } func (s *scopeExpiryServerStream) SetTrailer(metadata.MD) {} func (s *scopeExpiryServerStream) Context() context.Context { return s.ctx } -func (s *scopeExpiryServerStream) SendMsg(any) error { +func (s *scopeExpiryServerStream) SendMsg(m any) error { s.sendCalls++ + s.sent = m return nil } diff --git a/weed/server/filer_grpc_scope_subscription_test.go b/weed/server/filer_grpc_scope_subscription_test.go index 4b377e0c38..a1c06704c2 100644 --- a/weed/server/filer_grpc_scope_subscription_test.go +++ b/weed/server/filer_grpc_scope_subscription_test.go @@ -2,12 +2,14 @@ package weed_server import ( "context" + "io" "net" "reflect" "sync" "testing" "time" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/util" @@ -19,6 +21,208 @@ import ( "google.golang.org/protobuf/proto" ) +func TestGeneralScopedSubscriptionHidesRemoteRenameSourceKey(t *testing.T) { + token := scopeSubscriptionToken(t, time.Minute, []string{"/t/allowed"}, nil) + h := newScopeSubscriptionGRPCHarness(t, token) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + stream, err := h.client.SubscribeLocalMetadata(ctx, &filer_pb.SubscribeMetadataRequest{ + ClientName: "scope-subscription-remote-source", + ClientId: 77, + PathPrefix: "/t/allowed", + }) + if err != nil { + t.Fatalf("start subscription: %v", err) + } + entry := func(name string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Extended: map[string][]byte{ + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + "client-tag": []byte("keep"), + }} + } + nested := &filer_pb.SubscribeMetadataResponse{ + Directory: "/t/allowed", + TsNs: 2, + EventNotification: &filer_pb.EventNotification{ + OldEntry: entry("nested-old"), + NewEntry: entry("nested-new"), + }, + } + event := &filer_pb.SubscribeMetadataResponse{ + Directory: "/t/allowed", + TsNs: 1, + EventNotification: &filer_pb.EventNotification{ + OldEntry: entry("old"), + NewEntry: entry("new"), + NewParentPath: "/t/allowed", + }, + Events: []*filer_pb.SubscribeMetadataResponse{nested}, + } + appendScopeSubscriptionMetadataEvent(h.subscribeHarness, event) + + resp := nextScopeSubscriptionEvent(t, stream) + checkEntry := func(where string, got *filer_pb.Entry) { + t.Helper() + if got == nil { + t.Fatalf("%s entry missing", where) + } + if marker := got.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) != 0 { + t.Fatalf("%s exposed remote rename source %q", where, marker) + } + if tag := string(got.GetExtended()["client-tag"]); tag != "keep" { + t.Fatalf("%s lost client metadata %q", where, tag) + } + } + checkEntry("old", resp.GetEventNotification().GetOldEntry()) + checkEntry("new", resp.GetEventNotification().GetNewEntry()) + redacted := scopeRedactMetadataResponse(event) + if len(redacted.GetEvents()) != 1 { + t.Fatalf("redacted subscription batch events = %d, want 1", len(redacted.GetEvents())) + } + checkEntry("nested old", redacted.GetEvents()[0].GetEventNotification().GetOldEntry()) + checkEntry("nested new", redacted.GetEvents()[0].GetEventNotification().GetNewEntry()) + for _, source := range []*filer_pb.Entry{ + event.GetEventNotification().GetOldEntry(), event.GetEventNotification().GetNewEntry(), + event.GetEvents()[0].GetEventNotification().GetOldEntry(), event.GetEvents()[0].GetEventNotification().GetNewEntry(), + } { + if marker := source.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) == 0 { + t.Fatalf("redaction mutated the source event") + } + } +} + +func TestGeneralScopedSubscriptionRedactsDeliveredBatchTail(t *testing.T) { + base := time.Now().Add(-time.Hour).UnixNano() + entry := func(name string) *filer_pb.Entry { + return &filer_pb.Entry{Name: name, Extended: map[string][]byte{ + filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source"), + "client-tag": []byte("keep"), + }} + } + events := []*filer_pb.SubscribeMetadataResponse{ + {Directory: "/t/allowed", TsNs: base, EventNotification: &filer_pb.EventNotification{NewEntry: entry("batch-000")}}, + {Directory: "/t/allowed", TsNs: base + 1, EventNotification: &filer_pb.EventNotification{NewEntry: entry("batch-001")}}, + } + sources := proto.Clone(&filer_pb.SubscribeMetadataResponse{Events: events}).(*filer_pb.SubscribeMetadataResponse) + h := newScopeSubscriptionGRPCServerWithService(t, func(fs *FilerServer) filer_pb.SeaweedFilerServer { + return &prefilledLocalMetadataServer{FilerServer: fs, events: events} + }) + h.client = h.clientForToken(t, scopeSubscriptionToken(t, time.Minute, []string{"/t/allowed"}, nil)) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + stream, err := h.client.SubscribeLocalMetadata(ctx, &filer_pb.SubscribeMetadataRequest{ + ClientName: "scope-subscription-batch-redaction", + ClientId: 78, + PathPrefix: "/t/allowed", + ClientSupportsBatching: true, + }) + if err != nil { + t.Fatalf("start subscription: %v", err) + } + resp, err := stream.Recv() + if err != nil { + t.Fatalf("receive metadata batch: %v", err) + } + if len(resp.GetEvents()) != 1 { + t.Fatalf("delivered Events tail length = %d, want 1: %+v", len(resp.GetEvents()), resp) + } + if got := resp.GetEventNotification().GetNewEntry().GetName(); got != "batch-000" { + t.Fatalf("delivered batch head = %q, want batch-000", got) + } + if got := resp.GetEvents()[0].GetEventNotification().GetNewEntry().GetName(); got != "batch-001" { + t.Fatalf("delivered Events tail = %q, want batch-001", got) + } + checkEntry := func(where string, entry *filer_pb.Entry) { + t.Helper() + if entry == nil { + t.Fatalf("%s entry missing", where) + } + if marker := entry.GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) != 0 { + t.Fatalf("%s exposed remote rename source %q", where, marker) + } + if tag := string(entry.GetExtended()["client-tag"]); tag != "keep" { + t.Fatalf("%s lost client metadata %q", where, tag) + } + } + checkEntry("head", resp.GetEventNotification().GetNewEntry()) + checkEntry("tail", resp.GetEvents()[0].GetEventNotification().GetNewEntry()) + if _, err := stream.Recv(); err != io.EOF { + t.Fatalf("second metadata response error = %v, want EOF", err) + } + if !proto.Equal(events[0], sources.GetEvents()[0]) || !proto.Equal(events[1], sources.GetEvents()[1]) { + t.Fatal("scoped batch redaction mutated the source events") + } +} + +func TestDedicatedSubscriptionHidesRemoteRenameSourceKey(t *testing.T) { + event := &filer_pb.SubscribeMetadataResponse{ + Directory: "/t/allowed", + EventNotification: &filer_pb.EventNotification{NewEntry: &filer_pb.Entry{ + Name: "legacy", + Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/source")}, + }}, + } + scoped, cancel := newScopedMetadataStream(context.Background(), &security.MetadataSubscriptionScope{ + Prefixes: []string{"/t/allowed"}, + ExpiresAt: time.Now().Add(time.Minute), + }) + defer cancel() + var got *filer_pb.SubscribeMetadataResponse + if err := scoped.send(event, func(resp *filer_pb.SubscribeMetadataResponse) error { + got = resp + return nil + }); err != nil { + t.Fatalf("dedicated subscription send: %v", err) + } + if got == event { + t.Fatal("dedicated subscription response was not cloned") + } + if marker := got.GetEventNotification().GetNewEntry().GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) != 0 { + t.Fatalf("dedicated subscription exposed remote rename source %q", marker) + } + if marker := event.GetEventNotification().GetNewEntry().GetExtended()[filer.ExtRemoteRenameSourceKey]; len(marker) == 0 { + t.Fatal("dedicated subscription redaction mutated the source event") + } +} + +type prefilledLocalMetadataServer struct { + *FilerServer + events []*filer_pb.SubscribeMetadataResponse +} + +func (s *prefilledLocalMetadataServer) SubscribeLocalMetadata(req *filer_pb.SubscribeMetadataRequest, stream filer_pb.SeaweedFiler_SubscribeLocalMetadataServer) error { + subscription, err := s.metadataSubscriptionScope(stream.Context(), security.MethodSubscribeLocalMetadata) + if err != nil { + return err + } + if subscription == nil { + return s.FilerServer.SubscribeLocalMetadata(req, stream) + } + + req.ClientSupportsMetadataChunks = false + req.ClientId = s.unusedClientId() + req.ClientEpoch = scopedClientEpoch + scoped, cancel := newScopedMetadataStream(stream.Context(), subscription) + defer cancel() + scopedStream := &scopedSubscribeLocalStream{ + SeaweedFiler_SubscribeLocalMetadataServer: stream, + scopedMetadataStream: scoped, + } + sender := &pipelinedSender{ + ctx: scoped.Context(), + sendCh: make(chan *filer_pb.SubscribeMetadataResponse, len(s.events)), + errCh: make(chan error, 1), + done: make(chan struct{}), + canBatch: req.GetClientSupportsBatching(), + scope: "local", + } + for _, event := range s.events { + sender.sendCh <- event + } + go sender.sendLoop(scopedStream) + return scoped.endErr(sender.Close()) +} + const ( scopeSubscriptionScopeKey = "scope-subscription-scope-signing-key" scopeSubscriptionFilerKey = "scope-subscription-handler-filer-key" @@ -39,6 +243,10 @@ func newScopeSubscriptionGRPCHarness(t *testing.T, token string) *scopeSubscript } func newScopeSubscriptionGRPCServer(t *testing.T) *scopeSubscriptionGRPCHarness { + return newScopeSubscriptionGRPCServerWithService(t, nil) +} + +func newScopeSubscriptionGRPCServerWithService(t *testing.T, serviceFactory func(*FilerServer) filer_pb.SeaweedFilerServer) *scopeSubscriptionGRPCHarness { t.Helper() h := newSubscribeHarness(t) h.fs.filerGuard = security.NewGuard(nil, scopeSubscriptionFilerKey, 0, scopeSubscriptionFilerKey, 0, "", "") @@ -59,7 +267,11 @@ func newScopeSubscriptionGRPCServer(t *testing.T) *scopeSubscriptionGRPCHarness t.Fatalf("listen: %v", err) } server := grpc.NewServer(h.fs.grpcScope.ServerOptions()...) - filer_pb.RegisterSeaweedFilerServer(server, h.fs) + service := filer_pb.SeaweedFilerServer(h.fs) + if serviceFactory != nil { + service = serviceFactory(h.fs) + } + filer_pb.RegisterSeaweedFilerServer(server, service) go func() { _ = server.Serve(listener) }() t.Cleanup(func() { server.Stop() diff --git a/weed/server/filer_grpc_server.go b/weed/server/filer_grpc_server.go index b7e8633191..dd739b20ea 100644 --- a/weed/server/filer_grpc_server.go +++ b/weed/server/filer_grpc_server.go @@ -286,6 +286,16 @@ func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntr if findErr == filer_pb.ErrNotFound { current = nil } + var currentExtended map[string][]byte + if current != nil { + currentExtended = current.Extended + } + if refusal := scopeEntryEqualRefusal(ctx, req.Condition, currentExtended); refusal != nil { + return &filer_pb.CreateEntryResponse{ + Error: status.Convert(refusal).Message(), + ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED, + }, nil + } if conditionIsSet(req.Condition) && !writeConditionSatisfied(req.Condition, current) { glog.V(3).InfofCtx(ctx, "CreateEntry %s: precondition failed: %v", fullpath, req.Condition) return &filer_pb.CreateEntryResponse{ @@ -1018,6 +1028,9 @@ func (fs *FilerServer) updateEntry(ctx context.Context, req *filer_pb.UpdateEntr if refusal = validateUpdateEntryPreconditions(entry, req.ExpectedExtended); refusal != nil { return nil } + if refusal = scopeEntryEqualRefusal(ctx, req.Condition, entry.Extended); refusal != nil { + return nil + } if conditionIsSet(req.Condition) && !writeConditionSatisfied(req.Condition, entry) { glog.V(3).InfofCtx(ctx, "UpdateEntry %s: precondition failed: %v", fullpath, req.Condition) refusal = status.Errorf(codes.FailedPrecondition, "precondition failed: %s", fullpath) diff --git a/weed/server/filer_grpc_server_rename_remote_test.go b/weed/server/filer_grpc_server_rename_remote_test.go index 445b1b9acb..3868eb0572 100644 --- a/weed/server/filer_grpc_server_rename_remote_test.go +++ b/weed/server/filer_grpc_server_rename_remote_test.go @@ -386,6 +386,24 @@ func TestRenamePendingEntryAgainCopiesFromItsSource(t *testing.T) { assert.Equal(t, `"copy"`, c.Remote.RemoteETag) } +func TestRenamePendingEntryCopyErrorOmitsItsSource(t *testing.T) { + client := copyingRenameRemoteClient{&renameRemoteClient{copyErr: errors.New("copy s3 origin/src/a.jpg: access denied")}} + server, store := newRenameRemoteTestServer(t, client) + store.entries["/buckets/b/src/a.jpg"] = remoteOnlyRenameEntry("/buckets/b/src/a.jpg", 101) + store.entries["/buckets/b/dst/a.jpg"] = remoteOnlyRenameEntry("/buckets/b/dst/a.jpg", 202) + require.NoError(t, renameFile(server, "/buckets/b/src/a.jpg", "/buckets/b/dst/a.jpg")) + + err := renameFile(server, "/buckets/b/dst/a.jpg", "/buckets/b/dst/c.jpg") + require.Error(t, err) + assert.NotContains(t, err.Error(), "src/a.jpg") + assert.Contains(t, err.Error(), "/buckets/b/dst/a.jpg") + + store.entries["/buckets/b/src/b.jpg"] = remoteOnlyRenameEntry("/buckets/b/src/b.jpg", 303) + err = renameFile(server, "/buckets/b/src/b.jpg", "/buckets/b/dst/b.jpg") + require.Error(t, err) + assert.Contains(t, err.Error(), "access denied", "an entry reading its own key keeps the backend error") +} + func TestRemoteSourcePathStaysInTheMount(t *testing.T) { server, _ := newRenameRemoteTestServer(t, &renameRemoteClient{}) entry := remoteOnlyRenameEntry("/buckets/b/x.jpg", 101) diff --git a/weed/server/filer_grpc_server_sub_meta_scope.go b/weed/server/filer_grpc_server_sub_meta_scope.go index fbdd7958f6..8144056605 100644 --- a/weed/server/filer_grpc_server_sub_meta_scope.go +++ b/weed/server/filer_grpc_server_sub_meta_scope.go @@ -140,6 +140,7 @@ func (s scopedMetadataStream) send(resp *filer_pb.SubscribeMetadataResponse, sen scoped = scopeMetadataResponse(resp, s.scope.Prefixes) } if scoped != nil { + scoped = scopeRedactMetadataResponse(scoped) if err := send(scoped); err != nil { return err } diff --git a/weed/server/scoped_update_stored_state_test.go b/weed/server/scoped_update_stored_state_test.go index cfcc942148..89b1c3496e 100644 --- a/weed/server/scoped_update_stored_state_test.go +++ b/weed/server/scoped_update_stored_state_test.go @@ -170,6 +170,30 @@ func assertScopedEntryUnchanged(t *testing.T, run scopedEntryRun, want *filer.En } } +func TestScopedReplacementsKeepRemoteRenameSourceFilerOwned(t *testing.T) { + for _, create := range []bool{false, true} { + t.Run(map[bool]string{false: "update", true: "create"}[create], func(t *testing.T) { + const name = "remote-rename.txt" + initial := newFileEntry(scopeJoin(aliceWS, name), 1) + requested := &filer_pb.Entry{ + Name: name, + Attributes: &filer_pb.FuseAttributes{FileMode: 0644}, + Content: []byte("new"), + Extended: map[string][]byte{filer.ExtRemoteRenameSourceKey: []byte("/buckets/t1/other-source")}, + } + execute := runScopedUpdateState + if create { + execute = runScopedCreateState + } + run := execute(t, initial, requested, nil) + if status.Code(run.err) != codes.PermissionDenied || run.called { + t.Fatalf("err=%v called=%v, want admission PermissionDenied", run.err, run.called) + } + assertScopedEntryUnchanged(t, run, initial) + }) + } +} + func provenUpdateEntry(name string, chunks ...*filer_pb.FileChunk) *filer_pb.Entry { return &filer_pb.Entry{ Name: name,