From a9d4714aed133be429650f2c095e22a90d2a6ce8 Mon Sep 17 00:00:00 2001 From: Yip Leo Date: Thu, 3 Dec 2026 04:04:04 +0800 Subject: [PATCH] s3api, filer: keep a symlink a symlink when CopyObject copies it (#13298) * s3api, filer: keep a symlink a symlink when CopyObject copies it A symlink made through weed mount is an entry with the symlink mode bit, a SymlinkTarget and no data. CopyObject builds the destination's attributes afresh, with the permission bits from the request, so a copy to another key dropped both and landed as an empty regular file. A metadata-only self-copy (REPLACE) kept the target but reset the mode, leaving the link an empty regular file in place. Keep the symlink mode bit and the target on both paths. The permission bits still come from the request, as for any other copy. The filer's own copy (copyEntry) already carries the source's whole attribute set. A copy into a new prefix creates the symlink in a missing directory, and the filer gave each parent it created the entry's whole mode plus ModeDir. With the symlink bit as well, a mount shows those directories as regular files, and nothing under them can be reached. Parents now take the entry's permission bits only. Co-Authored-By: Claude Opus 5.5 * filer: drop the symlink type when promoting an entry to a directory A key nested under a symlink promotes the symlink's entry to a directory. The promotion added ModeDir and kept the symlink bit, so a mount showed the directory as a regular file and could not reach the nested key. Keep only the permission bits there too, with the same restorableModeBits a missing parent now takes from its entry. Co-Authored-By: Claude Opus 5.5 * s3api: keep a self-copied prefix object a directory when it was a symlink A prefix object promoted from a symlink before the filer change still has the symlink bit. A routed self-copy of it restored ModeDir and then keepSymlink added the symlink bit back, leaving a directory a mount shows as a regular file. keepSymlink now leaves directory destinations alone. Co-Authored-By: Claude Opus 5.5 * filer_pb: a prefix object keeps no type bit but the directory's MarkPrefixObject added ModeDir and the execute bits to whatever mode the object had. A symlink copied onto a key that other keys are nested under, or a self-copy outside the owner route of a prefix object promoted from a symlink before the filer change, kept the symlink bit next to ModeDir, which a mount shows as a regular file. Clear the other type bits first. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Chris Lu --- weed/filer/filer.go | 10 +- weed/filer/filer_implicit_dir_test.go | 38 +++++ weed/pb/filer_pb/filer_pb_helper.go | 5 +- weed/pb/filer_pb/filer_pb_helper_test.go | 14 ++ weed/s3api/s3api_object_handlers_copy.go | 15 ++ ...s3api_object_handlers_copy_symlink_test.go | 139 ++++++++++++++++++ weed/sftpd/sftp_permissions.go | 7 +- weed/sftpd/sftp_permissions_test.go | 38 +++++ 8 files changed, 259 insertions(+), 7 deletions(-) create mode 100644 weed/s3api/s3api_object_handlers_copy_symlink_test.go diff --git a/weed/filer/filer.go b/weed/filer/filer.go index 6b49ed83f9..a05d584988 100644 --- a/weed/filer/filer.go +++ b/weed/filer/filer.go @@ -874,12 +874,15 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di // create the directory now := time.Now() + // The directory takes the entry's permission bits, not its type: with + // a symlink's type bit as well, a mount shows the directory as a + // regular file. dirEntry = &Entry{ FullPath: util.FullPath(dirPath), Attr: Attr{ Mtime: now, Crtime: now, - Mode: os.ModeDir | entry.Mode | 0111, + Mode: os.ModeDir | entry.Mode&restorableModeBits | 0111, Uid: entry.Uid, Gid: entry.Gid, UserName: entry.UserName, @@ -924,7 +927,10 @@ func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, di // existing file to a directory, preserving its content/chunks so // the original object data remains accessible. glog.V(2).InfofCtx(ctx, "promoting %s from file to directory for %s", dirPath, entry.FullPath) - dirEntry.Attr.Mode |= os.ModeDir | 0111 + // A promoted symlink keeps no type bit but the directory's: with both, + // a mount shows the directory as a regular file. + dirEntry.Attr.Mode = os.ModeDir | dirEntry.Attr.Mode&restorableModeBits | 0111 + dirEntry.Attr.SymlinkTarget = "" // Expiring the entry now deletes the directory row and strands the keys under // it, so the prefix object gives up its lazy TTL. The lifecycle worker still // expires it, through the delete that leaves the directory behind. diff --git a/weed/filer/filer_implicit_dir_test.go b/weed/filer/filer_implicit_dir_test.go index 61c53545d6..2aeadd7464 100644 --- a/weed/filer/filer_implicit_dir_test.go +++ b/weed/filer/filer_implicit_dir_test.go @@ -117,3 +117,41 @@ func waitForDirectoryCreateWaiter(t *testing.T, done chan error) { } t.Fatal("the directory create neither waited nor finished") } + +// A missing parent takes the permission bits of the entry created under it, +// never its type: the parents of a symlink made in a new directory are plain +// directories, not entries a mount shows as regular files. +func TestImplicitParentOfSymlinkIsPlainDirectory(t *testing.T) { + f, stub := newTestFilerWithStubStore(t) + ctx := context.Background() + link := &Entry{FullPath: "/buckets/bkt/cold/env/bin/python", Attr: Attr{Mode: os.ModeSymlink | 0o660, SymlinkTarget: "python3.10"}} + require.NoError(t, f.CreateEntry(ctx, link, nil, false, false, nil, false, f.MaxFilenameLength)) + + for _, p := range []util.FullPath{"/buckets/bkt", "/buckets/bkt/cold", "/buckets/bkt/cold/env", "/buckets/bkt/cold/env/bin"} { + dir, err := stub.FindEntry(ctx, p) + require.NoError(t, err, p) + assert.Equal(t, os.ModeDir|0o771, dir.Mode, "%s", p) + } + stored, err := stub.FindEntry(ctx, link.FullPath) + require.NoError(t, err) + assert.Equal(t, os.ModeSymlink|0o660, stored.Mode) + assert.Equal(t, "python3.10", stored.SymlinkTarget) +} + +// A symlink that gets a key nested under it is promoted to a directory. It +// keeps its permission bits but not the symlink type, or a mount shows the +// directory as a regular file and cannot reach the nested key. +func TestPromotedSymlinkIsPlainDirectory(t *testing.T) { + f, stub := newTestFilerWithStubStore(t) + ctx := context.Background() + link := &Entry{FullPath: "/buckets/bkt/cold/link", Attr: Attr{Mode: os.ModeSymlink | 0o660, SymlinkTarget: "elsewhere"}} + require.NoError(t, f.CreateEntry(ctx, link, nil, false, false, nil, false, f.MaxFilenameLength)) + child := &Entry{FullPath: "/buckets/bkt/cold/link/child", Attr: Attr{Mode: 0o660}} + require.NoError(t, f.CreateEntry(ctx, child, nil, false, false, nil, false, f.MaxFilenameLength)) + + promoted, err := stub.FindEntry(ctx, link.FullPath) + require.NoError(t, err) + assert.Equal(t, os.ModeDir|0o771, promoted.Mode) + assert.Empty(t, promoted.SymlinkTarget) + assert.Equal(t, []byte("true"), promoted.Extended[s3_constants.SeaweedFSPrefixObject]) +} diff --git a/weed/pb/filer_pb/filer_pb_helper.go b/weed/pb/filer_pb/filer_pb_helper.go index 58d7cd76c1..9654b379c1 100644 --- a/weed/pb/filer_pb/filer_pb_helper.go +++ b/weed/pb/filer_pb/filer_pb_helper.go @@ -46,7 +46,10 @@ func (entry *Entry) IsPrefixObject() bool { func (entry *Entry) MarkPrefixObject() { entry.IsDirectory = true if entry.Attributes != nil { - entry.Attributes.FileMode |= uint32(os.ModeDir) | 0111 + // No type bit but the directory's: a copied symlink landing on a + // directory would otherwise make a mount show it as a regular file. + entry.Attributes.FileMode = entry.Attributes.FileMode&^uint32(os.ModeType) | uint32(os.ModeDir) | 0111 + entry.Attributes.SymlinkTarget = "" } if entry.Extended == nil { entry.Extended = make(map[string][]byte) diff --git a/weed/pb/filer_pb/filer_pb_helper_test.go b/weed/pb/filer_pb/filer_pb_helper_test.go index 077e00e4ff..b416e55c37 100644 --- a/weed/pb/filer_pb/filer_pb_helper_test.go +++ b/weed/pb/filer_pb/filer_pb_helper_test.go @@ -84,3 +84,17 @@ func TestMarkPrefixObject(t *testing.T) { t.Error("a demoted directory names no key") } } + +// A symlink copied onto a key other keys are nested under becomes that +// directory's prefix object. The directory keeps no other type bit: with the +// symlink's as well, a mount shows it as a regular file. +func TestMarkPrefixObjectDropsOtherTypeBits(t *testing.T) { + entry := &Entry{Name: "foo", Attributes: &FuseAttributes{FileMode: uint32(os.ModeSymlink | 0660), SymlinkTarget: "bar"}} + entry.MarkPrefixObject() + if mode := os.FileMode(entry.Attributes.FileMode); mode != os.ModeDir|0771 { + t.Errorf("FileMode = %v, want %v", mode, os.ModeDir|0771) + } + if target := entry.Attributes.SymlinkTarget; target != "" { + t.Errorf("SymlinkTarget = %q, want none on a directory", target) + } +} diff --git a/weed/s3api/s3api_object_handlers_copy.go b/weed/s3api/s3api_object_handlers_copy.go index 66afafada3..6d19287d02 100644 --- a/weed/s3api/s3api_object_handlers_copy.go +++ b/weed/s3api/s3api_object_handlers_copy.go @@ -442,6 +442,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request if updatedEntry.IsDirectory { updatedEntry.Attributes.FileMode |= uint32(os.ModeDir) } + keepSymlink(updatedEntry.Attributes, currentEntry.Attributes) updatedEntry.Attributes.Mtime = t.Unix() size = int64(filer.FileSize(currentEntry)) if owner != "" { @@ -624,6 +625,7 @@ func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request }, Extended: dstMeta.Extended, } + keepSymlink(dstEntry.Attributes, entry.Attributes) // For zero-size files or files without chunks, handle inline content // This includes encrypted inline files that need decryption/re-encryption @@ -793,6 +795,19 @@ func (s3a *S3ApiServer) applyCopyObjectLockHeaders(r *http.Request, dstBucket, d return s3err.ErrNone } +// keepSymlink keeps the copy of a symlink a symlink to the same target. A copy +// takes its permission bits from the request, and a symlink made through a +// mount has no data, so without its type and target the copy would be an +// empty regular file. A directory, such as a prefix object promoted from a +// symlink, stays a directory. +func keepSymlink(dst, src *filer_pb.FuseAttributes) { + if dst == nil || os.FileMode(dst.FileMode)&os.ModeDir != 0 || os.FileMode(src.GetFileMode())&os.ModeSymlink == 0 { + return + } + dst.FileMode |= uint32(os.ModeSymlink) + dst.SymlinkTarget = src.GetSymlinkTarget() +} + func cloneProtoEntry(entry *filer_pb.Entry) *filer_pb.Entry { if entry == nil { return nil diff --git a/weed/s3api/s3api_object_handlers_copy_symlink_test.go b/weed/s3api/s3api_object_handlers_copy_symlink_test.go new file mode 100644 index 0000000000..1402ea12ef --- /dev/null +++ b/weed/s3api/s3api_object_handlers_copy_symlink_test.go @@ -0,0 +1,139 @@ +package s3api + +import ( + "context" + "net/http" + "net/http/httptest" + "os" + "testing" + "time" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/cluster" + "github.com/seaweedfs/seaweedfs/weed/pb" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/stretchr/testify/require" +) + +// dirAwareFiler answers a file create over a directory the way the filer does, +// so the gateway writes the object onto the directory as a prefix object. +type dirAwareFiler struct{ *copyACLFiler } + +func (f *dirAwareFiler) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) { + f.mu.Lock() + existing := f.entries[req.Directory+"/"+req.Entry.Name] + f.mu.Unlock() + if existing != nil && existing.IsDirectory && !req.Entry.IsDirectory { + return &filer_pb.CreateEntryResponse{Error: "existing entry is a directory", ErrorCode: filer_pb.FilerError_EXISTING_IS_DIRECTORY}, nil + } + return f.copyACLFiler.CreateEntry(ctx, req) +} + +// A symlink made through a mount is an entry with a target and no data. Its +// copy must be a symlink to the same target, not an empty regular file, both +// when it goes to another key and when a self-copy rewrites its metadata. The +// permission bits still come from the request, as for any other copy. +func TestCopyObjectKeepsSymlink(t *testing.T) { + const bucket, source, target = "copy-symlink", "env/bin/python", "python3.10" + for _, tt := range []struct { + name string + self bool + routed bool + replace bool + regular bool + prefix bool + ontoDir bool + }{ + {name: "to another key"}, + {name: "to another key replacing metadata", replace: true}, + {name: "onto itself replacing metadata", self: true, replace: true}, + {name: "onto itself through the owner filer", self: true, replace: true, routed: true}, + {name: "regular file stays regular", regular: true}, + {name: "prefix object promoted from a symlink stays a directory", self: true, replace: true, routed: true, prefix: true}, + {name: "prefix object promoted from a symlink stays a directory under the bucket lock", self: true, replace: true, prefix: true}, + {name: "onto a key other keys are nested under", ontoDir: true}, + } { + t.Run(tt.name, func(t *testing.T) { + filer := &dirAwareFiler{©ACLFiler{ambiguousPutFiler: &ambiguousPutFiler{apply: true, entries: map[string]*filer_pb.Entry{}}}} + address := startFakeFiler(t, filer) + s3a := newPutTestServer(t, address) + s3a.iam = &IdentityAccessManagement{} + s3a.bucketConfigCache = NewBucketConfigCache(time.Minute) + s3a.bucketConfigCache.Set(bucket, &BucketConfig{Name: bucket, Ownership: s3_constants.OwnershipObjectWriter}) + filer.entries["/buckets/"+bucket] = &filer_pb.Entry{Name: bucket, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}} + if tt.routed { + s3a.objectWriteLockClient = cluster.NewLockClient(s3a.option.GrpcDialOption, address) + s3a.objectWriteLockClient.SetRing([]pb.ServerAddress{address}, 1) + } + link := &filer_pb.Entry{Name: "python", Attributes: &filer_pb.FuseAttributes{ + FileMode: uint32(os.ModeSymlink | 0777), SymlinkTarget: target, Mtime: 1, Crtime: 1}} + if tt.regular { + link = &filer_pb.Entry{Name: "python", Content: []byte("data"), + Attributes: &filer_pb.FuseAttributes{FileMode: 0755, FileSize: 4, Mtime: 1, Crtime: 1}} + } + if tt.prefix { + link.IsDirectory = true + link.Attributes.FileMode |= uint32(os.ModeDir) + link.Extended = map[string][]byte{s3_constants.SeaweedFSPrefixObject: []byte("true")} + filer.entries["/buckets/"+bucket+"/"+source+"/child"] = &filer_pb.Entry{Name: "child", Content: []byte("child data")} + } + filer.entries["/buckets/"+bucket+"/"+source] = link + + key := "copied/python" + if tt.self { + key = source + } + if tt.ontoDir { + filer.entries["/buckets/"+bucket+"/"+key] = &filer_pb.Entry{Name: "python", IsDirectory: true, + Attributes: &filer_pb.FuseAttributes{FileMode: uint32(os.ModeDir | 0755)}} + filer.entries["/buckets/"+bucket+"/"+key+"/child"] = &filer_pb.Entry{Name: "child", Content: []byte("child data")} + } + req := httptest.NewRequest(http.MethodPut, "/"+bucket+"/"+key, nil) + req = mux.SetURLVars(req, map[string]string{"bucket": bucket, "object": key}) + req.Header.Set("X-Amz-Copy-Source", "/"+bucket+"/"+source) + if tt.replace { + req.Header.Set(s3_constants.AmzUserMetaDirective, DirectiveReplace) + req.Header.Set("X-Amz-Meta-Note", "new") + } + rr := httptest.NewRecorder() + s3a.CopyObjectHandler(rr, req) + require.Equal(t, http.StatusOK, rr.Code, rr.Body.String()) + + filer.mu.Lock() + defer filer.mu.Unlock() + stored := filer.entries["/buckets/"+bucket+"/"+key] + require.NotNil(t, stored) + if tt.regular { + require.Equal(t, defaultFileMode, stored.Attributes.FileMode) + require.Empty(t, stored.Attributes.SymlinkTarget) + require.Equal(t, []byte("data"), stored.Content) + return + } + if tt.prefix || tt.ontoDir { + // The object lands on the directory, which must keep no type bit + // but its own. Written as a prefix object (all but the routed + // self-copy), it is also made traversable. + want := uint32(os.ModeDir) | defaultFileMode + if !tt.routed { + want |= 0111 + } + require.True(t, stored.IsDirectory) + require.Equal(t, want, stored.Attributes.FileMode, + "copy onto a prefix object stored mode %v", os.FileMode(stored.Attributes.FileMode)) + require.True(t, stored.IsPrefixObject()) + require.NotNil(t, filer.entries["/buckets/"+bucket+"/"+key+"/child"]) + return + } + require.Equal(t, uint32(os.ModeSymlink)|defaultFileMode, stored.Attributes.FileMode, + "copy of a symlink stored mode %v", os.FileMode(stored.Attributes.FileMode)) + require.Equal(t, target, stored.Attributes.SymlinkTarget) + if tt.replace { + require.Equal(t, []byte("new"), stored.Extended["X-Amz-Meta-Note"]) + } + if tt.routed { + require.Len(t, filer.updates, 1, "the self-copy must commit through the owner") + } + }) + } +} diff --git a/weed/sftpd/sftp_permissions.go b/weed/sftpd/sftp_permissions.go index 1a32107839..379b1ccbc3 100644 --- a/weed/sftpd/sftp_permissions.go +++ b/weed/sftpd/sftp_permissions.go @@ -78,11 +78,10 @@ func (fs *SftpServer) CheckFilePermission(path string, perm string) error { // Rest of the function remains the same... // Handle symlinks by resolving them - if entry.Attributes.GetSymlinkTarget() != "" { - // Get the actual entry for the resolved path - entry, err = fs.getEntry(entry.Attributes.GetSymlinkTarget()) + if target := entry.Attributes.GetSymlinkTarget(); target != "" && !entry.IsDirectory { + entry, err = fs.getEntry(target) if err != nil { - return fmt.Errorf("failed to get entry for resolved path %s: %w", entry.Attributes.SymlinkTarget, err) + return fmt.Errorf("failed to get entry for resolved path %s: %w", target, err) } } diff --git a/weed/sftpd/sftp_permissions_test.go b/weed/sftpd/sftp_permissions_test.go index af317a47de..6715b681df 100644 --- a/weed/sftpd/sftp_permissions_test.go +++ b/weed/sftpd/sftp_permissions_test.go @@ -759,3 +759,41 @@ func TestRenameEntryRejectsConcurrentTarget(t *testing.T) { t.Error("expected rename to fail when the target appears concurrently and the user lacks delete access") } } + +// A directory that still holds the target of a symlink it replaced is checked +// as itself, and a dangling symlink is refused instead of panicking. +func TestCheckFilePermissionFollowsOnlySymlinks(t *testing.T) { + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + filer := &permissionTestFiler{entries: map[string]*filer_pb.Entry{ + "/": {IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: 0755}}, + "/data": {IsDirectory: true, Attributes: &filer_pb.FuseAttributes{FileMode: 0755}}, + "/data/secret": {IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Uid: 2000, FileMode: uint32(os.ModeDir | 0700)}}, + "/data/dir": {IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Uid: 1000, FileMode: uint32(os.ModeDir | 0771), SymlinkTarget: "/data/secret"}}, + "/data/link": {Attributes: &filer_pb.FuseAttributes{Uid: 1000, FileMode: uint32(os.ModeSymlink | 0777), SymlinkTarget: "/data/secret"}}, + "/data/dangles": {Attributes: &filer_pb.FuseAttributes{Uid: 1000, FileMode: uint32(os.ModeSymlink | 0777), SymlinkTarget: "/data/missing"}}, + }} + grpcServer := grpc.NewServer() + filer_pb.RegisterSeaweedFilerServer(grpcServer, filer) + go func() { _ = grpcServer.Serve(lis) }() + t.Cleanup(grpcServer.Stop) + + _, port, _ := net.SplitHostPort(lis.Addr().String()) + fs := &SftpServer{ + filerAddr: pb.ServerAddress("127.0.0.1:0." + port), + grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), + user: &user.User{Username: "alice", Uid: 1000, Gid: 1000, HomeDir: "/home/alice"}, + } + + if err := fs.CheckFilePermission("/data/dir", PermList); err != nil { + t.Errorf("directory checked as its stale target: %v", err) + } + if err := fs.CheckFilePermission("/data/link", PermList); err == nil { + t.Error("symlink not checked as its target") + } + if err := fs.CheckFilePermission("/data/dangles", PermRead); err == nil { + t.Error("dangling symlink allowed") + } +}