Skip to content

Commit db5e7e1

Browse files
committed
fix: Refactor OpenDestination func
- Replaced os.Stat call and os.Create with os.OpenFile with O_EXCL to avoid TOCTOU. - Improved logic to handle file size check only when the file exists. Signed-off-by: Gofastasf <gofastasf@gmail.com>
1 parent 231857b commit db5e7e1

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

pkg/snapshot/pack.go

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,27 +32,22 @@ func PackFrom(snapshotName, sourceRoot string) error {
3232
// if the file seems to exist and have existing content already.
3333
// This is done to avoid accidental overwrites.
3434
func OpenDestination(snapshotName string) (*os.File, error) {
35-
var f *os.File
36-
var err error
37-
38-
if _, err = os.Stat(snapshotName); errors.Is(err, os.ErrNotExist) {
39-
if f, err = os.Create(snapshotName); err != nil {
35+
f, err := os.OpenFile(snapshotName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
36+
if err != nil {
37+
if !errors.Is(err, os.ErrExist) {
4038
return nil, err
4139
}
42-
} else if err != nil {
43-
return nil, err
44-
} else {
45-
f, err := os.OpenFile(snapshotName, os.O_WRONLY, 0600)
40+
fs, err := os.Stat(snapshotName)
4641
if err != nil {
4742
return nil, err
4843
}
49-
fs, err := f.Stat()
44+
if fs.Size() > 0 {
45+
return nil, fmt.Errorf("file %s already exists and is of size > 0", snapshotName)
46+
}
47+
f, err = os.OpenFile(snapshotName, os.O_WRONLY, 0600)
5048
if err != nil {
5149
return nil, err
5250
}
53-
if fs.Size() > 0 {
54-
return nil, fmt.Errorf("File %s already exists and is of size >0", snapshotName)
55-
}
5651
}
5752
return f, nil
5853
}

0 commit comments

Comments
 (0)