Skip to content

Commit ff9d47a

Browse files
author
Athos
authored
Do basic dump file validation before uploading it (#870)
1 parent 77719b6 commit ff9d47a

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

internal/cmd/group_flag.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package cmd
22

33
import (
4+
"bufio"
45
"bytes"
56
"errors"
67
"fmt"
@@ -147,9 +148,36 @@ func validateDumpFile(name string) (*os.File, error) {
147148
if fileStat.Size() > MaxDumpFileSizeBytes {
148149
return nil, fmt.Errorf("dump file is too large. max allowed size is 2GB")
149150
}
151+
if err := checkDumpFileFirstLines(name, file); err != nil {
152+
return nil, fmt.Errorf("invalid dump file: %w", err)
153+
}
150154
return file, nil
151155
}
152156

157+
func checkDumpFileFirstLines(name string, file *os.File) error {
158+
scanner := bufio.NewScanner(file)
159+
scanner.Scan()
160+
if scanner.Text() != "PRAGMA foreign_keys=OFF;" {
161+
if checkSQLiteFile(name) == nil {
162+
return fmt.Errorf("you're trying to use a SQLite database file as a dump. Use the --from-db flag instead of --from-dump")
163+
}
164+
return fmt.Errorf("file doens't look like a dump: first line should be 'PRAGMA foreign_keys=OFF;'")
165+
}
166+
167+
scanner.Scan()
168+
if scanner.Text() != "BEGIN TRANSACTION;" {
169+
if checkSQLiteFile(name) == nil {
170+
return fmt.Errorf("you're trying to use a SQLite database file as a dump. Use --from-db instead")
171+
}
172+
return fmt.Errorf("file doens't look like a dump: second line should be 'BEGIN TRANSACTION;'")
173+
}
174+
175+
if _, err := file.Seek(0, 0); err != nil {
176+
return fmt.Errorf("could not seek to the beginning of dump after validating it: %w", err)
177+
}
178+
return nil
179+
}
180+
153181
func countFlags(flags ...string) (count int) {
154182
for _, flag := range flags {
155183
if flag != "" {

0 commit comments

Comments
 (0)