package weed_server import ( "bytes" "context" "encoding/hex" "fmt" "io" "net/http" "net/http/httptest" "os" "strings" "sync" "testing" "golang.org/x/net/webdav" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/protobuf/proto" "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" ) func TestParseOCMtime(t *testing.T) { for in, want := range map[string]int64{ "": 0, "1577836800": 1577836800, " 1577836800.75 ": 1577836800, "-5": 0, "0": 0, "yesterday": 0, "1e300": 0, "NaN": 0, "-Inf": 0, } { if got := parseOCMtime(in); got != want { t.Errorf("parseOCMtime(%q) = %d, want %d", in, got, want) } } } func newTestDavFS(t *testing.T, impl filer_pb.SeaweedFilerServer) *WebDavFileSystem { return &WebDavFileSystem{option: &WebDavOption{ Filer: startFakeWebDavFiler(t, impl), GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()), }} } func davHandler(fs webdav.FileSystem) http.Handler { return copyMoveGuardHandler{fs: fs, next: &webdav.Handler{FileSystem: fs, LockSystem: webdav.NewMemLS()}} } // an empty PUT never writes, so the mtime has to land at create func TestPutKeepsOCMtime(t *testing.T) { filer := &createRecordingFiler{dirs: map[string]bool{"/": true}} h := davHandler(newTestDavFS(t, filer)) req := httptest.NewRequest("PUT", "/f.txt", strings.NewReader("")) req.Header.Set("X-OC-Mtime", "1577836800") rec := httptest.NewRecorder() h.ServeHTTP(rec, req) if rec.Code != http.StatusCreated { t.Fatalf("PUT = %d, want 201", rec.Code) } if got := filer.req.Entry.Attributes.Mtime; got != 1577836800 { t.Errorf("stored mtime = %d, want 1577836800", got) } if got := rec.Header().Get("X-OC-Mtime"); got != "accepted" { t.Errorf("X-OC-Mtime response = %q, want accepted", got) } } func TestPutWithoutOCMtimeUsesNow(t *testing.T) { filer := &createRecordingFiler{dirs: map[string]bool{"/": true}} h := davHandler(newTestDavFS(t, filer)) rec := httptest.NewRecorder() h.ServeHTTP(rec, httptest.NewRequest("PUT", "/f.txt", strings.NewReader(""))) if filer.req.Entry.Attributes.Mtime < 1700000000 { t.Errorf("stored mtime = %d, want the upload time", filer.req.Entry.Attributes.Mtime) } if got := rec.Header().Get("X-OC-Mtime"); got != "" { t.Errorf("X-OC-Mtime response = %q without a request header", got) } } func TestCloseAppliesOCMtime(t *testing.T) { outcome := &putOutcome{mtime: 1577836800} ctx := context.WithValue(context.Background(), putOutcomeKey{}, outcome) if got := putMtime(ctx); got != 1577836800 { t.Errorf("putMtime = %d, want the X-OC-Mtime", got) } if got := putMtime(context.Background()); got < 1700000000 { t.Errorf("putMtime without a PUT = %d, want now", got) } } func propfind(t *testing.T, h http.Handler, name, body string) string { t.Helper() req := httptest.NewRequest("PROPFIND", name, strings.NewReader(body)) req.Header.Set("Depth", "0") rec := httptest.NewRecorder() h.ServeHTTP(rec, req) if rec.Code != http.StatusMultiStatus { t.Fatalf("PROPFIND %s = %d, want 207", name, rec.Code) } return rec.Body.String() } const ocChecksumsPropfind = ` ` func TestPropfindReportsOCChecksum(t *testing.T) { md5 := []byte{0x5d, 0x41, 0x40, 0x2a, 0xbc, 0x4b, 0x2a, 0x76, 0xb9, 0x71, 0x9d, 0x91, 0x10, 0x17, 0xc5, 0x92} filer := &deleteRecordingFiler{existing: &filer_pb.Entry{ Name: "f.txt", Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 5, Md5: md5}, Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Size: 5}}, }} h := davHandler(newTestDavFS(t, filer)) body := propfind(t, h, "/f.txt", ocChecksumsPropfind) if !strings.Contains(body, "MD5:5d41402abc4b2a76b9719d911017c592") { t.Errorf("PROPFIND lacks the MD5 checksum:\n%s", body) } } func TestPropfindOmitsUnknownChecksum(t *testing.T) { // a chunked upload: the filer has no whole-content MD5 filer := &deleteRecordingFiler{existing: &filer_pb.Entry{ Name: "f.txt", Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 5}, Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Size: 5, ETag: "XUFAKrxLKna5cZ2REBfFkg=="}}, }} h := davHandler(newTestDavFS(t, filer)) body := propfind(t, h, "/f.txt", ocChecksumsPropfind) if strings.Contains(body, "MD5:") { t.Errorf("PROPFIND reports a checksum the filer does not have:\n%s", body) } } func TestProppatchStillForbidden(t *testing.T) { filer := &deleteRecordingFiler{existing: &filer_pb.Entry{ Name: "f.txt", Attributes: &filer_pb.FuseAttributes{FileMode: 0644, Md5: make([]byte, 16)}, }} h := davHandler(newTestDavFS(t, filer)) req := httptest.NewRequest("PROPPATCH", "/f.txt", strings.NewReader(` x`)) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) if !strings.Contains(rec.Body.String(), "403") { t.Errorf("PROPPATCH was not refused:\n%s", rec.Body.String()) } } func TestWriteRecordsContentMd5(t *testing.T) { newFile := func(created bool) *WebDavFile { return &WebDavFile{created: created, entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}} } write := func(f *WebDavFile, off int64, data string) { f.off = off f.hashWrite([]byte(data)) f.off += int64(len(data)) if size := uint64(f.off); size > f.entry.Attributes.FileSize { f.entry.Attributes.FileSize = size } } f := newFile(true) write(f, 0, "abc") write(f, 3, "def") if got, want := hex.EncodeToString(f.contentMd5()), hex.EncodeToString(util.Md5([]byte("abcdef"))); got != want { t.Errorf("in-order write MD5 = %q", got) } f = newFile(true) write(f, 3, "def") write(f, 0, "abc") if f.contentMd5() != nil { t.Error("out-of-order write got an MD5") } // a file opened without creating it may already hold other bytes f = newFile(false) write(f, 0, "hello") if f.contentMd5() != nil { t.Error("write into an existing file got an MD5") } } // uploadFiler stores what WebDAV uploads commit: chunks go to a stand-in // volume server, and the last UpdateEntry is kept type uploadFiler struct { createRecordingFiler volume string // host:port of the stand-in volume server existing map[string]*filer_pb.Entry mu sync.Mutex updated *filer_pb.Entry } func (f *uploadFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) { if entry, ok := f.existing[string(util.NewFullPath(req.Directory, req.Name))]; ok { return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil } return f.createRecordingFiler.LookupDirectoryEntry(ctx, req) } func (f *uploadFiler) AssignVolume(context.Context, *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) { return &filer_pb.AssignVolumeResponse{FileId: "1,0000000100001234", Location: &filer_pb.Location{Url: f.volume}}, nil } func (f *uploadFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) { f.mu.Lock() defer f.mu.Unlock() f.updated = proto.Clone(req.Entry).(*filer_pb.Entry) return &filer_pb.UpdateEntryResponse{}, nil } func newUploadFiler(t *testing.T) *uploadFiler { volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { n, _ := io.Copy(io.Discard, r.Body) fmt.Fprintf(w, `{"size":%d}`, n) })) t.Cleanup(volume.Close) return &uploadFiler{ createRecordingFiler: createRecordingFiler{dirs: map[string]bool{"/": true}}, volume: strings.TrimPrefix(volume.URL, "http://"), } } // a PUT larger than the write buffer commits several chunks; the entry it // commits carries the X-OC-Mtime and the MD5 of the whole body func TestPutCommitsOCMtimeAndMd5(t *testing.T) { filer := newUploadFiler(t) fs := newTestDavFS(t, filer) fs.option.MaxMB = 1 body := bytes.Repeat([]byte("0123456789abcdef"), 160*1024) // 2.5 MiB req := httptest.NewRequest("PUT", "/big.bin", bytes.NewReader(body)) req.Header.Set("X-OC-Mtime", "1577836800") rec := httptest.NewRecorder() davHandler(fs).ServeHTTP(rec, req) if rec.Code != http.StatusCreated { t.Fatalf("PUT = %d, want 201: %s", rec.Code, rec.Body.String()) } if filer.updated == nil { t.Fatal("the upload committed no entry") } if n := len(filer.updated.GetChunks()); n < 2 { t.Errorf("committed %d chunks, want the upload to cross a buffer flush", n) } if got := filer.updated.Attributes.Mtime; got != 1577836800 { t.Errorf("committed mtime = %d, want 1577836800", got) } want := util.Md5(body) if got := filer.updated.Attributes.Md5; !bytes.Equal(got, want) { t.Errorf("committed MD5 = %x, want %x", got, want) } } // writing into a file this open did not create leaves its content unknown, // so the MD5 stored for the old content goes func TestRewriteClearsStoredMd5(t *testing.T) { filer := newUploadFiler(t) filer.existing = map[string]*filer_pb.Entry{"/f.txt": { Name: "f.txt", Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 5, Md5: []byte("old-md5-old-md5!")}, Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Size: 5}}, }} fs := newTestDavFS(t, filer) fs.option.MaxMB = 1 f, err := fs.OpenFile(context.Background(), "/f.txt", os.O_RDWR, 0644) if err != nil { t.Fatal(err) } if _, err := f.Write([]byte("HE")); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } if filer.updated == nil { t.Fatal("the write committed no entry") } if got := filer.updated.Attributes.Md5; got != nil { t.Errorf("rewritten file kept MD5 %q", got) } } func TestContentMd5OnlyForWholeInlineContent(t *testing.T) { hello := []byte("hello") for name, tc := range map[string]struct { entry *filer_pb.Entry want bool }{ "inline": {&filer_pb.Entry{Content: hello, Attributes: &filer_pb.FuseAttributes{FileSize: 5}}, true}, "empty": {&filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}, true}, "inline and chunks": {&filer_pb.Entry{Content: hello, Attributes: &filer_pb.FuseAttributes{FileSize: 10}, Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Offset: 5, Size: 5}}}, false}, "short of the size": {&filer_pb.Entry{Content: hello, Attributes: &filer_pb.FuseAttributes{FileSize: 10}}, false}, "directory": {&filer_pb.Entry{IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}, false}, } { if got := contentMd5(tc.entry) != nil; got != tc.want { t.Errorf("%s: has MD5 = %v, want %v", name, got, tc.want) } } }