mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 10:37:23 +01:00
* sftp: copy only the stored bytes on a non-truncating open A size set by a truncate that grows a file stores nothing, but opening the file for writing without O_TRUNC copied its whole logical size into the temp file as zeros. Copy up to the last stored byte and extend the temp file to the size, which leaves the rest sparse. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: upload only up to the written data on close Close streamed the whole temp file, so a hole after the data, from a truncate that grew the file before or during the open, was read back and uploaded as zeros. Track where the copied and written bytes end, upload up to there, and keep the rest as the file's size. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: leave the data end alone on an empty write A zero-length WRITE far past the data moved the data end there, so Close uploaded the hole before it as zeros. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: cap what the test filer reads from an upload An upload that wrongly carries a large hole now fails the test instead of filling memory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: hash nothing past an out-of-range size A stored size past the largest file offset turned negative and sliced the inline content out of range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: refuse a setstat size past the largest file offset Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: fail the hash of an out-of-range size Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sftp: check the size before returning a stored md5 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
323 lines
11 KiB
Go
323 lines
11 KiB
Go
package sftpd
|
|
|
|
import (
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/pkg/sftp"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
|
)
|
|
|
|
// newTestClient serves fs as one SFTP session over in-memory pipes and
|
|
// returns a client connected to it.
|
|
func newTestClient(t *testing.T, fs *SftpServer) *sftp.Client {
|
|
t.Helper()
|
|
serverR, clientW := io.Pipe()
|
|
clientR, serverW := io.Pipe()
|
|
done := make(chan struct{})
|
|
go func() {
|
|
defer close(done)
|
|
_ = handleSFTP(pipeStream{serverR, serverW}, fs)
|
|
}()
|
|
client, err := sftp.NewClientPipe(clientR, clientW)
|
|
if err != nil {
|
|
t.Fatalf("sftp client: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
_ = client.Close()
|
|
<-done
|
|
})
|
|
return client
|
|
}
|
|
|
|
// rwTest serves /buckets/b/rw.txt ("abcdef") and the empty
|
|
// /buckets/b/empty.txt, with a stand-in filer HTTP endpoint that stores
|
|
// uploads and records their bodies.
|
|
type rwTest struct {
|
|
client *sftp.Client
|
|
fs *SftpServer
|
|
fake *lockTestFiler
|
|
mu sync.Mutex
|
|
bodies []string
|
|
}
|
|
|
|
func newRWTest(t *testing.T, perms ...string) *rwTest {
|
|
t.Helper()
|
|
fs, fake := newLockTestServer(t, map[string]*filer_pb.Entry{
|
|
"/buckets/b": {Name: "b", IsDirectory: true},
|
|
"/buckets/b/rw.txt": {Name: "rw.txt", Content: []byte("abcdef"), Attributes: &filer_pb.FuseAttributes{FileSize: 6, FileMode: 0o644}},
|
|
"/buckets/b/empty.txt": {Name: "empty.txt"},
|
|
})
|
|
fs.user.Permissions = map[string][]string{"/buckets": perms}
|
|
rw := &rwTest{fs: fs, fake: fake}
|
|
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
|
rw.mu.Lock()
|
|
rw.bodies = append(rw.bodies, string(body))
|
|
rw.mu.Unlock()
|
|
fake.mu.Lock()
|
|
fake.entries[r.URL.Path] = &filer_pb.Entry{Name: path.Base(r.URL.Path), Content: body, Attributes: &filer_pb.FuseAttributes{FileMode: 0o644, FileSize: uint64(len(body))}}
|
|
fake.mu.Unlock()
|
|
_, _ = w.Write([]byte(`{}`))
|
|
}))
|
|
t.Cleanup(ts.Close)
|
|
_, grpcPort, _ := net.SplitHostPort(fs.filerAddr.ToGrpcAddress())
|
|
fs.filerAddr = pb.ServerAddress(strings.TrimPrefix(ts.URL, "http://") + "." + grpcPort)
|
|
rw.client = newTestClient(t, fs)
|
|
return rw
|
|
}
|
|
|
|
func (rw *rwTest) uploads() []string {
|
|
rw.mu.Lock()
|
|
defer rw.mu.Unlock()
|
|
return append([]string(nil), rw.bodies...)
|
|
}
|
|
|
|
// A read on a handle opened for reading and writing must return the file's
|
|
// bytes and leave them alone. pkg/sftp serves reads on a write-only handle as
|
|
// writes of the read buffer, which put zeros over the start of the file.
|
|
func TestReadWriteOpenReadsExistingContent(t *testing.T) {
|
|
rw := newRWTest(t, PermAll)
|
|
|
|
f, err := rw.client.OpenFile("/b/rw.txt", os.O_RDWR)
|
|
if err != nil {
|
|
t.Fatalf("open read-write: %v", err)
|
|
}
|
|
head := make([]byte, 3)
|
|
if n, err := f.ReadAt(head, 0); n != 3 || string(head) != "abc" {
|
|
t.Fatalf("read 3 at 0 = %q (n=%d, err=%v), want %q", head[:n], n, err, "abc")
|
|
}
|
|
if _, err := f.WriteAt([]byte("XY"), 4); err != nil {
|
|
t.Fatalf("write at 4: %v", err)
|
|
}
|
|
all := make([]byte, 6)
|
|
if n, err := f.ReadAt(all, 0); string(all[:n]) != "abcdXY" {
|
|
t.Fatalf("content after read and write = %q (err=%v), want %q", all[:n], err, "abcdXY")
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
if got := rw.uploads(); len(got) != 1 || got[0] != "abcdXY" {
|
|
t.Fatalf("uploaded on close = %q, want one upload of %q", got, "abcdXY")
|
|
}
|
|
}
|
|
|
|
// Close uploads a read-write handle again only if it changed the file:
|
|
// reading must not rewrite it (nor restore it once removed), while a
|
|
// truncating or creating open, or a setstat on the handle, does change it.
|
|
func TestReadWriteOpenUploadsOnlyChanges(t *testing.T) {
|
|
for _, c := range []struct {
|
|
name string
|
|
path string
|
|
flags int
|
|
do func(*sftp.File, *lockTestFiler) error
|
|
want []string
|
|
mode os.FileMode // stored afterwards, when set
|
|
}{
|
|
{name: "read", path: "/b/rw.txt", flags: os.O_RDWR},
|
|
{name: "read empty", path: "/b/empty.txt", flags: os.O_RDWR},
|
|
{name: "read removed", path: "/b/rw.txt", flags: os.O_RDWR | os.O_CREATE, do: func(_ *sftp.File, fake *lockTestFiler) error {
|
|
fake.mu.Lock()
|
|
defer fake.mu.Unlock()
|
|
delete(fake.entries, "/buckets/b/rw.txt")
|
|
return nil
|
|
}},
|
|
{name: "truncate", path: "/b/rw.txt", flags: os.O_RDWR | os.O_TRUNC, want: []string{""}},
|
|
{name: "create", path: "/b/new.txt", flags: os.O_RDWR | os.O_CREATE, want: []string{""}},
|
|
{name: "ftruncate", path: "/b/rw.txt", flags: os.O_RDWR, do: func(f *sftp.File, _ *lockTestFiler) error { return f.Truncate(3) }, want: []string{"abc"}},
|
|
{name: "fchmod", path: "/b/rw.txt", flags: os.O_RDWR, do: func(f *sftp.File, _ *lockTestFiler) error { return f.Chmod(0o600) }, want: []string{"abcdef"}, mode: 0o600},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
rw := newRWTest(t, PermAll)
|
|
|
|
f, err := rw.client.OpenFile(c.path, c.flags)
|
|
if err != nil {
|
|
t.Fatalf("open: %v", err)
|
|
}
|
|
if _, err := f.ReadAt(make([]byte, 6), 0); err != nil && err != io.EOF {
|
|
t.Fatalf("read: %v", err)
|
|
}
|
|
if c.do != nil {
|
|
if err := c.do(f, rw.fake); err != nil {
|
|
t.Fatalf("%s: %v", c.name, err)
|
|
}
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
if got := rw.uploads(); !slices.Equal(got, c.want) {
|
|
t.Fatalf("uploaded on close = %q, want %q", got, c.want)
|
|
}
|
|
if mode := os.FileMode(rw.fake.lastUpdate.GetEntry().GetAttributes().GetFileMode()).Perm(); c.mode != 0 && mode != c.mode {
|
|
t.Errorf("stored mode %o, want %o", mode, c.mode)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// A truncate can grow a file to any size without storing anything. Opening it
|
|
// for writing must not turn that size into zeros on the server's disk.
|
|
func TestReadWriteOpenGrownFile(t *testing.T) {
|
|
rw := newRWTest(t, PermAll)
|
|
const size = 1 << 40
|
|
rw.fake.mu.Lock()
|
|
rw.fake.entries["/buckets/b/grown.txt"] = &filer_pb.Entry{Name: "grown.txt", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: size, FileMode: 0o644}}
|
|
rw.fake.mu.Unlock()
|
|
|
|
f, err := rw.client.OpenFile("/b/grown.txt", os.O_RDWR)
|
|
if err != nil {
|
|
t.Fatalf("open read-write: %v", err)
|
|
}
|
|
buf := make([]byte, 2)
|
|
if n, err := f.ReadAt(buf, 0); n != 2 || string(buf) != "x\x00" {
|
|
t.Fatalf("read at 0 = %q (err=%v), want %q", buf[:n], err, "x\x00")
|
|
}
|
|
if n, err := f.ReadAt(buf, size-2); n != 2 || string(buf) != "\x00\x00" {
|
|
t.Fatalf("read at the end = %q (err=%v), want two zeros", buf[:n], err)
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
if got := rw.uploads(); len(got) != 0 {
|
|
t.Fatalf("uploaded %d times on close, want none", len(got))
|
|
}
|
|
}
|
|
|
|
// Close uploads the bytes up to the last one copied or written, and keeps a
|
|
// hole after them, however it was made, as the file's size.
|
|
func TestCloseKeepsTrailingHoleAsSize(t *testing.T) {
|
|
const size = 1 << 40
|
|
for _, c := range []struct {
|
|
name string
|
|
flags int
|
|
do func(*sftp.File) error
|
|
want string
|
|
}{
|
|
{name: "write in grown file", flags: os.O_RDWR, do: func(f *sftp.File) error {
|
|
_, err := f.WriteAt([]byte("y"), 1)
|
|
return err
|
|
}, want: "xy"},
|
|
{name: "empty write past the data", flags: os.O_RDWR, do: func(f *sftp.File) error {
|
|
if _, err := f.WriteAt([]byte("y"), 1); err != nil {
|
|
return err
|
|
}
|
|
_, err := f.WriteAt(nil, size-1)
|
|
return err
|
|
}, want: "xy"},
|
|
{name: "ftruncate up", flags: os.O_RDWR | os.O_TRUNC, do: func(f *sftp.File) error {
|
|
if _, err := f.Write([]byte("abc")); err != nil {
|
|
return err
|
|
}
|
|
return f.Truncate(size)
|
|
}, want: "abc"},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
rw := newRWTest(t, PermAll)
|
|
rw.fake.mu.Lock()
|
|
rw.fake.entries["/buckets/b/grown.txt"] = &filer_pb.Entry{Name: "grown.txt", Content: []byte("x"), Attributes: &filer_pb.FuseAttributes{FileSize: size, FileMode: 0o644}}
|
|
rw.fake.mu.Unlock()
|
|
|
|
f, err := rw.client.OpenFile("/b/grown.txt", c.flags)
|
|
if err != nil {
|
|
t.Fatalf("open: %v", err)
|
|
}
|
|
if err := c.do(f); err != nil {
|
|
t.Fatalf("%s: %v", c.name, err)
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
if got := rw.uploads(); len(got) != 1 || got[0] != c.want {
|
|
t.Fatalf("uploaded on close = %q, want one upload of %q", got, c.want)
|
|
}
|
|
if got := rw.fake.lastUpdate.GetEntry().GetAttributes().GetFileSize(); got != size {
|
|
t.Fatalf("stored size %d, want %d", got, uint64(size))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// Without read permission a read-write open still writes, as a write-only
|
|
// open would, but reads only what the handle itself wrote.
|
|
func TestReadWriteOpenWithoutReadPermission(t *testing.T) {
|
|
for _, c := range []struct {
|
|
name string
|
|
path string
|
|
flags int
|
|
readable bool // the handle starts empty, so reading needs no permission
|
|
want string
|
|
}{
|
|
{"existing", "/b/rw.txt", os.O_RDWR, false, "XYcdef"},
|
|
{"truncate", "/b/rw.txt", os.O_RDWR | os.O_TRUNC, true, "XY"},
|
|
{"create", "/b/new.txt", os.O_RDWR | os.O_CREATE, true, "XY"},
|
|
} {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
rw := newRWTest(t, "write")
|
|
|
|
f, err := rw.client.OpenFile(c.path, c.flags)
|
|
if err != nil {
|
|
t.Fatalf("open: %v", err)
|
|
}
|
|
if _, err := f.WriteAt([]byte("XY"), 0); err != nil {
|
|
t.Fatalf("write: %v", err)
|
|
}
|
|
b := make([]byte, 2)
|
|
n, err := f.ReadAt(b, 0)
|
|
if c.readable && string(b[:n]) != "XY" {
|
|
t.Fatalf("read back own write = %q (err=%v), want %q", b[:n], err, "XY")
|
|
}
|
|
if !c.readable && (err == nil || n > 0) {
|
|
t.Fatalf("read without read permission = %q (err=%v), want refused", b[:n], err)
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
t.Fatalf("close: %v", err)
|
|
}
|
|
if got := rw.uploads(); len(got) != 1 || got[0] != c.want {
|
|
t.Fatalf("uploaded on close = %q, want one upload of %q", got, c.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// Read permission is decided on the entry that was copied. Looked up again
|
|
// after the file is removed during the copy, the check would fall back to
|
|
// the folder's rights, which here are wider than the file's.
|
|
func TestReadWriteOpenFileRemovedDuringCopyNeedsRead(t *testing.T) {
|
|
rw := newRWTest(t, PermAll)
|
|
rw.fs.user.Permissions["/buckets/b/x.bin"] = []string{"write"}
|
|
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
rw.fake.mu.Lock()
|
|
delete(rw.fake.entries, "/buckets/b/x.bin")
|
|
rw.fake.mu.Unlock()
|
|
_, _ = w.Write([]byte("secret"))
|
|
}))
|
|
t.Cleanup(volume.Close)
|
|
rw.fake.mu.Lock()
|
|
rw.fake.volume = volume.Listener.Addr().String()
|
|
rw.fake.entries["/buckets/b/x.bin"] = &filer_pb.Entry{
|
|
Name: "x.bin",
|
|
Attributes: &filer_pb.FuseAttributes{FileSize: 6, FileMode: 0o644},
|
|
Chunks: []*filer_pb.FileChunk{fileChunk("3,01", 0, 6)},
|
|
}
|
|
rw.fake.mu.Unlock()
|
|
|
|
f, err := rw.client.OpenFile("/b/x.bin", os.O_RDWR)
|
|
if err != nil {
|
|
t.Fatalf("open: %v", err)
|
|
}
|
|
defer f.Close()
|
|
b := make([]byte, 6)
|
|
if n, err := f.ReadAt(b, 0); err == nil || n > 0 {
|
|
t.Fatalf("read of a write-only file removed during the copy = %q (err=%v), want refused", b[:n], err)
|
|
}
|
|
}
|