diff --git a/internal/server.go b/internal/server.go index f12fead..d3b1a15 100644 --- a/internal/server.go +++ b/internal/server.go @@ -8,6 +8,7 @@ import ( "mime" "net/http" "net/url" + "path" "strings" ) @@ -284,6 +285,12 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) error { } } + // RFC 4918 sections 9.8.5 and 9.9.4: overwriting the destination would + // delete the source. + if path.Clean(r.URL.Path) == path.Clean(dest.Path) { + return HTTPErrorf(http.StatusForbidden, "webdav: source and destination are the same") + } + var created bool if r.Method == "COPY" { var recursive bool diff --git a/server_test.go b/server_test.go new file mode 100644 index 0000000..4fc0cbb --- /dev/null +++ b/server_test.go @@ -0,0 +1,40 @@ +package webdav + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +func TestHandlerCopyMoveOntoItself(t *testing.T) { + dir := t.TempDir() + p := filepath.Join(dir, "a.txt") + if err := os.WriteFile(p, []byte("a"), 0o644); err != nil { + t.Fatal(err) + } + + ts := httptest.NewServer(&Handler{FileSystem: LocalFileSystem(dir)}) + defer ts.Close() + + for _, method := range []string{"COPY", "MOVE"} { + req, err := http.NewRequest(method, ts.URL+"/a.txt", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Destination", ts.URL+"/a.txt") + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusForbidden { + t.Errorf("%v onto itself: status = %v, want %v", method, resp.StatusCode, http.StatusForbidden) + } + } + + if got, err := os.ReadFile(p); err != nil || string(got) != "a" { + t.Errorf("a.txt = %q, %v; want %q", got, err, "a") + } +}