fix: harden exclusive file creation and webdav writes
This commit is contained in:
@@ -107,6 +107,14 @@ func (m Multi) Create(p string) (*os.File, error) {
|
||||
}
|
||||
return r.Create(rel)
|
||||
}
|
||||
|
||||
func (m Multi) CreateExclusive(p string) (*os.File, error) {
|
||||
r, rel, ok := m.find(p)
|
||||
if !ok {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
return r.CreateExclusive(rel)
|
||||
}
|
||||
func (m Multi) Remove(p string) error {
|
||||
r, rel, ok := m.find(p)
|
||||
if !ok || rel == "" {
|
||||
|
||||
@@ -46,3 +46,44 @@ func TestMultiRemoveCannotRemoveVirtualRoot(t *testing.T) {
|
||||
t.Fatal("expected virtual root removal to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalCreateExclusiveRejectsExistingFile(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
st := Local{Root: root}
|
||||
if err := os.WriteFile(filepath.Join(root, "x.txt"), []byte("old"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := st.CreateExclusive("x.txt")
|
||||
if !os.IsExist(err) || f != nil {
|
||||
t.Fatalf("expected EEXIST, file=%v err=%v", f, err)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(root, "x.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "old" {
|
||||
t.Fatalf("existing file changed: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalCreateExclusiveCreatesMissingFile(t *testing.T) {
|
||||
st := Local{Root: t.TempDir()}
|
||||
f, err := st.CreateExclusive("nested/x.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.WriteString("new"); err != nil {
|
||||
f.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(st.Root, "nested", "x.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got) != "new" {
|
||||
t.Fatalf("unexpected content: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,10 @@ type Storage interface {
|
||||
List(path string) ([]os.FileInfo, error)
|
||||
}
|
||||
|
||||
type ExclusiveCreator interface {
|
||||
CreateExclusive(path string) (*os.File, error)
|
||||
}
|
||||
|
||||
type Local struct{ Root string }
|
||||
|
||||
func (s Local) real(path string) (string, error) {
|
||||
@@ -95,6 +99,17 @@ func (s Local) Create(path string) (*os.File, error) {
|
||||
}
|
||||
return os.Create(p)
|
||||
}
|
||||
|
||||
func (s Local) CreateExclusive(path string) (*os.File, error) {
|
||||
p, e := s.real(path)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = os.MkdirAll(filepath.Dir(p), 0755); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
|
||||
}
|
||||
func (s Local) Remove(path string) error {
|
||||
p, e := s.real(path)
|
||||
if e == nil {
|
||||
|
||||
Reference in New Issue
Block a user