Skip to content

🎧 Your Personal Streaming Service

fix(db): refuse to restore a backup file that is not a Navidrome database - #6295 (#6296)

DawidKrynski563c5c72a16f
diff --git a/cmd/backup.go b/cmd/backup.go
index 932a833f2..6b3a94221 100644
--- a/cmd/backup.go
+++ b/cmd/backup.go
@@ -12,10 +12,11 @@ import (
)
var (
- backupCount int
- backupDir string
- force bool
- restorePath string
+ backupCount int
+ backupDir string
+ force bool
+ integrityCheck bool
+ restorePath string
)
func init() {
@@ -31,6 +32,7 @@ func init() {
restoreCommand.Flags().StringVarP(&restorePath, "backup-file", "b", "", "file name of the backup database to restore (resolved against the backup directory unless it is an absolute path)")
restoreCommand.Flags().BoolVarP(&force, "force", "f", false, "bypass restore warning")
+ restoreCommand.Flags().BoolVarP(&integrityCheck, "integrity-check", "i", false, "check the backup file with a full integrity check before restoring. Finds more kinds of damage, but takes longer")
_ = restoreCommand.MarkFlagRequired("backup-file")
backupRoot.AddCommand(restoreCommand)
}
@@ -136,7 +138,7 @@ func runRestore(ctx context.Context) {
}
start := time.Now()
- err := db.Restore(ctx, restorePath)
+ err := db.Restore(ctx, restorePath, integrityCheck)
if err != nil {
log.Fatal("Error restoring database", "backupFile", restorePath, err)
}
diff --git a/db/backup.go b/db/backup.go
index 74cae553e..8c99f2a25 100644
--- a/db/backup.go
+++ b/db/backup.go
@@ -33,59 +33,41 @@ func backupPath(t time.Time) string {
)
}
-func backupOrRestore(ctx context.Context, isBackup bool, path string) error {
- // heavily inspired by https://codingrabbits.dev/posts/go_and_sqlite_backup_and_maybe_restore/
- existingConn, err := Db().Conn(ctx)
+func openBackupFile(path string) (*sql.DB, error) {
+ Db() // Registers Driver, which the CLI commands haven't done at this point.
+ backupDb, err := sql.Open(Driver, path)
if err != nil {
- return fmt.Errorf("getting existing connection: %w", err)
- }
- defer existingConn.Close()
-
- // The driver opens with SQLITE_OPEN_CREATE, so without this check a typo in the
- // path would create an empty database and "restore" it over the live one.
- if !isBackup {
- // The driver splits the DSN at '?', so such a path would open a different file.
- if strings.ContainsRune(path, '?') {
- return fmt.Errorf("backup path cannot contain '?': %s", path)
- }
- if _, err := os.Stat(path); err != nil {
- return fmt.Errorf("backup file not available: %w", err)
- }
+ return nil, fmt.Errorf("opening backup database in '%s': %w", path, err)
}
+ return backupDb, nil
+}
- backupDb, err := sql.Open(Driver, path)
+func copyDatabase(ctx context.Context, dest, source *sql.DB) error {
+ // heavily inspired by https://codingrabbits.dev/posts/go_and_sqlite_backup_and_maybe_restore/
+ destConn, err := dest.Conn(ctx)
if err != nil {
- return fmt.Errorf("opening backup database in '%s': %w", path, err)
+ return fmt.Errorf("getting destination connection: %w", err)
}
- defer backupDb.Close()
+ defer destConn.Close()
- backupConn, err := backupDb.Conn(ctx)
+ sourceConn, err := source.Conn(ctx)
if err != nil {
- return fmt.Errorf("getting backup connection: %w", err)
+ return fmt.Errorf("getting source connection: %w", err)
}
- defer backupConn.Close()
+ defer sourceConn.Close()
- err = existingConn.Raw(func(existing any) error {
- return backupConn.Raw(func(backup any) error {
- var sourceOk, destOk bool
- var sourceConn, destConn *sqlite3.SQLiteConn
-
- if isBackup {
- sourceConn, sourceOk = existing.(*sqlite3.SQLiteConn)
- destConn, destOk = backup.(*sqlite3.SQLiteConn)
- } else {
- sourceConn, sourceOk = backup.(*sqlite3.SQLiteConn)
- destConn, destOk = existing.(*sqlite3.SQLiteConn)
+ return destConn.Raw(func(rawDest any) error {
+ return sourceConn.Raw(func(rawSource any) error {
+ sqliteDest, destOk := rawDest.(*sqlite3.SQLiteConn)
+ if !destOk {
+ return fmt.Errorf("error trying to convert destination to sqlite connection")
}
-
+ sqliteSource, sourceOk := rawSource.(*sqlite3.SQLiteConn)
if !sourceOk {
return fmt.Errorf("error trying to convert source to sqlite connection")
}
- if !destOk {
- return fmt.Errorf("error trying to convert destination to sqlite connection")
- }
- backupOp, err := destConn.Backup("main", sourceConn, "main")
+ backupOp, err := sqliteDest.Backup("main", sqliteSource, "main")
if err != nil {
return fmt.Errorf("error starting sqlite backup: %w", err)
}
@@ -109,24 +91,89 @@ func backupOrRestore(ctx context.Context, isBackup bool, path string) error {
return nil
})
})
+}
+
+// checkRestoreSource runs sanity checks on a file about to be restored over the live
+// database. They catch the common ways a backup goes bad, not every kind of damage.
+func checkRestoreSource(ctx context.Context, backupDb *sql.DB, path string, integrityCheck bool) error {
+ // SQLite opens an empty file as an empty database, and restoring it would wipe the live one.
+ // user and media_file exist since the first migration, so backups of any age have them.
+ var tables int
+ err := backupDb.QueryRowContext(ctx,
+ "SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name IN ('goose_db_version', 'user', 'media_file')").Scan(&tables)
+ if err != nil {
+ return fmt.Errorf("reading backup file '%s': %w", path, err)
+ }
+ if tables != 3 {
+ return fmt.Errorf("backup file '%s' is not a Navidrome database", path)
+ }
+
+ // The table can be there with nothing in it, or with only the row goose adds when it creates it.
+ var applied int
+ err = backupDb.QueryRowContext(ctx,
+ "SELECT count(*) FROM goose_db_version WHERE is_applied = 1 AND version_id > 0").Scan(&applied)
+ if err != nil {
+ return fmt.Errorf("reading backup file '%s': %w", path, err)
+ }
+ if applied == 0 {
+ return fmt.Errorf("backup file '%s' has no applied migrations", path)
+ }
- return err
+ // The queries above only read the first pages. Both checks walk the whole file, and
+ // integrity_check also compares indexes to their tables, which is much slower.
+ check := "PRAGMA quick_check(1)"
+ if integrityCheck {
+ check = "PRAGMA integrity_check(1)"
+ }
+ var result string
+ if err := backupDb.QueryRowContext(ctx, check).Scan(&result); err != nil {
+ return fmt.Errorf("checking backup file '%s': %w", path, err)
+ }
+ if result != "ok" {
+ return fmt.Errorf("backup file '%s' is damaged: %s", path, result)
+ }
+ return nil
}
func Backup(ctx context.Context) (string, error) {
destPath := backupPath(time.Now())
log.Debug(ctx, "Creating backup", "path", destPath)
- err := backupOrRestore(ctx, true, destPath)
+ backupDb, err := openBackupFile(destPath)
if err != nil {
return "", err
}
+ defer backupDb.Close()
+
+ if err := copyDatabase(ctx, backupDb, Db()); err != nil {
+ return "", err
+ }
return destPath, nil
}
-func Restore(ctx context.Context, path string) error {
+func Restore(ctx context.Context, path string, integrityCheck bool) error {
log.Debug(ctx, "Restoring backup", "path", path)
- return backupOrRestore(ctx, false, path)
+
+ // The driver splits the DSN at '?', so such a path would open a different file.
+ if strings.ContainsRune(path, '?') {
+ return fmt.Errorf("backup path cannot contain '?': %s", path)
+ }
+ // The driver opens with SQLITE_OPEN_CREATE, so without this check a typo in the
+ // path would create an empty database and "restore" it over the live one.
+ if _, err := os.Stat(path); err != nil {
+ return fmt.Errorf("backup file not available: %w", err)
+ }
+
+ backupDb, err := openBackupFile(path)
+ if err != nil {
+ return err
+ }
+ defer backupDb.Close()
+
+ if err := checkRestoreSource(ctx, backupDb, path, integrityCheck); err != nil {
+ return err
+ }
+ return copyDatabase(ctx, Db(), backupDb)
}
func Prune(ctx context.Context) (int, error) {
diff --git a/db/backup_test.go b/db/backup_test.go
index 609cba3d6..6dacdad04 100644
--- a/db/backup_test.go
+++ b/db/backup_test.go
@@ -21,6 +21,22 @@ func shortTime(year int, month time.Month, day, hour, minute int) time.Time {
return time.Date(year, month, day, hour, minute, 0, 0, time.UTC)
}
+const (
+ gooseTableDDL = "CREATE TABLE goose_db_version(version_id, is_applied)"
+ navidromeTablesDDL = "CREATE TABLE user(id); CREATE TABLE media_file(id)"
+)
+
+func sqliteFile(statements string) func(path string) {
+ return func(path string) {
+ GinkgoHelper()
+ other, err := sql.Open(Driver, path)
+ Expect(err).ToNot(HaveOccurred())
+ defer other.Close()
+ _, err = other.Exec(statements)
+ Expect(err).ToNot(HaveOccurred())
+ }
+}
+
var _ = Describe("database backups", func() {
When("there are a few backup files", func() {
var ctx context.Context
@@ -158,7 +174,7 @@ var _ = Describe("database backups", func() {
Expect(err).ToNot(HaveOccurred())
Expect(IsSchemaEmpty(ctx, Db())).To(BeTrue())
- err = Restore(ctx, path)
+ err = Restore(ctx, path, false)
Expect(err).ToNot(HaveOccurred())
Expect(IsSchemaEmpty(ctx, Db())).To(BeFalse())
})
@@ -176,6 +192,7 @@ var _ = Describe("database backups", func() {
var err error
tempFolder, err = os.MkdirTemp("", "navidrome_restore")
Expect(err).ToNot(HaveOccurred())
+ conf.Server.Backup.Path = conf.NewDir(tempFolder)
DeferCleanup(func() {
Close(ctx)
_ = os.RemoveAll(tempFolder)
@@ -209,7 +226,7 @@ var _ = Describe("database backups", func() {
Expect(err).ToNot(HaveOccurred())
By("restoring the backup")
- Expect(Restore(ctx, path)).To(Succeed())
+ Expect(Restore(ctx, path, false)).To(Succeed())
By("verifying the restored data is readable through a fresh connection")
singleton.DeleteInstance[*sql.DB]()
@@ -218,23 +235,91 @@ var _ = Describe("database backups", func() {
Expect(userName).To(Equal("drilladmin"))
})
- It("fails to restore from a backup file that does not exist, leaving the database intact", func() {
+ expectRestoreRefused := func(path, expectedErr string) {
+ GinkgoHelper()
By("seeding user data in the current database")
- _, err := Db().ExecContext(ctx, `INSERT INTO user (id, user_name, name, email, password, is_admin, created_at, updated_at)
+ _, err := Db().ExecContext(ctx, `INSERT OR REPLACE INTO user (id, user_name, name, email, password, is_admin, created_at, updated_at)
VALUES ('u-restore-2', 'keepme', 'keepme', '[email protected]', 'x', 1, datetime('now'), datetime('now'))`)
Expect(err).ToNot(HaveOccurred())
- By("attempting a restore from a nonexistent file")
- missingPath := filepath.Join(tempFolder, "does_not_exist.db")
- err = Restore(ctx, missingPath)
- Expect(err).To(HaveOccurred())
+ By("attempting the restore")
+ Expect(Restore(ctx, path, false)).To(MatchError(ContainSubstring(expectedErr)))
By("verifying the database was not wiped")
var userName string
Expect(Db().QueryRowContext(ctx, "SELECT user_name FROM user WHERE id = 'u-restore-2'").Scan(&userName)).To(Succeed())
Expect(userName).To(Equal("keepme"))
+ }
+
+ It("fails to restore from a backup file that does not exist, leaving the database intact", func() {
+ missingPath := filepath.Join(tempFolder, "does_not_exist.db")
+ expectRestoreRefused(missingPath, "backup file not available")
_, statErr := os.Stat(missingPath)
Expect(statErr).To(MatchError(os.ErrNotExist))
})
+
+ DescribeTable("fails to restore from a file that is not a Navidrome database, leaving the database intact",
+ func(createFile func(path string), expectedErr string) {
+ invalidPath := filepath.Join(GinkgoT().TempDir(), "invalid_backup.db")
+ createFile(invalidPath)
+ expectRestoreRefused(invalidPath, expectedErr)
+ },
+ Entry("empty file", func(path string) {
+ Expect(os.WriteFile(path, nil, 0600)).To(Succeed())
+ }, "is not a Navidrome database"),
+ Entry("file that is not a SQLite database", func(path string) {
+ Expect(os.WriteFile(path, []byte("this is not a database, just some text"), 0600)).To(Succeed())
+ }, "reading backup file"),
+ Entry("SQLite database without the Navidrome schema",
+ sqliteFile("CREATE TABLE something_else(x)"), "is not a Navidrome database"),
+ Entry("another project's goose database",
+ sqliteFile(gooseTableDDL+"; INSERT INTO goose_db_version VALUES (1, 1)"), "is not a Navidrome database"),
+ Entry("goose database with only one of the Navidrome tables",
+ sqliteFile(gooseTableDDL+"; INSERT INTO goose_db_version VALUES (1, 1); CREATE TABLE media_file(id)"), "is not a Navidrome database"),
+ Entry("SQLite database with an empty goose_db_version table",
+ sqliteFile(gooseTableDDL+"; "+navidromeTablesDDL), "has no applied migrations"),
+ Entry("SQLite database with only goose's initial version row",
+ sqliteFile(gooseTableDDL+"; "+navidromeTablesDDL+"; INSERT INTO goose_db_version VALUES (0, 1)"), "has no applied migrations"),
+ Entry("SQLite database whose migrations were all rolled back",
+ sqliteFile(gooseTableDDL+"; "+navidromeTablesDDL+"; INSERT INTO goose_db_version VALUES (1, 0)"), "has no applied migrations"),
+ Entry("backup with garbage over its last pages", func(path string) {
+ // Filler rows go to the end of the file, so the damage below stays clear of
+ // the schema and of goose_db_version, which still read fine.
+ _, err := Db().ExecContext(ctx, "CREATE TABLE _restore_filler AS SELECT zeroblob(1000000) AS x")
+ Expect(err).ToNot(HaveOccurred())
+ backupFile, err := Backup(ctx)
+ Expect(err).ToNot(HaveOccurred())
+ data, err := os.ReadFile(backupFile)
+ Expect(err).ToNot(HaveOccurred())
+
+ for i := len(data) * 4 / 5; i < len(data); i++ {
+ data[i] = 0xFF
+ }
+ Expect(os.WriteFile(path, data, 0600)).To(Succeed())
+ }, "is damaged"),
+ )
+
+ It("restores a good backup with the integrity check", func() {
+ path, err := Backup(ctx)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(Restore(ctx, path, true)).To(Succeed())
+ })
+
+ It("refuses an index that doesn't match its table only with the integrity check", func() {
+ path, err := Backup(ctx)
+ Expect(err).ToNot(HaveOccurred())
+ writeMismatchedIndex(ctx, path, 1)
+ restored := func() int {
+ var count int
+ Expect(Db().QueryRowContext(ctx, "SELECT count(*) FROM sqlite_master WHERE name = 't'").Scan(&count)).To(Succeed())
+ return count
+ }
+
+ Expect(Restore(ctx, path, true)).To(MatchError(ContainSubstring("is damaged")))
+ Expect(restored()).To(BeZero())
+
+ Expect(Restore(ctx, path, false)).To(Succeed())
+ Expect(restored()).To(Equal(1))
+ })
})
})
diff --git a/db/repair_test.go b/db/repair_test.go
index eb7321939..892a4f326 100644
--- a/db/repair_test.go
+++ b/db/repair_test.go
@@ -38,18 +38,13 @@ func newDB(ctx context.Context, upTo int64) *sql.DB {
return d
}
-// openMismatchedIndexDB builds a database whose index is declared over a different
-// column than the one it was populated from, so integrity_check reports one issue per row.
-func openMismatchedIndexDB(ctx context.Context, rows int) *sql.DB {
+// writeMismatchedIndex adds an index declared over a different column than the one it
+// was populated from, so integrity_check reports one issue per row and quick_check none.
+func writeMismatchedIndex(ctx context.Context, path string, rows int) {
GinkgoHelper()
- path := filepath.Join(GinkgoT().TempDir(), "mismatched.db")
- open := func() *sql.DB {
- d, err := sql.Open(db.Dialect, path)
- Expect(err).ToNot(HaveOccurred())
- d.SetMaxOpenConns(1)
- return d
- }
- d := open()
+ d, err := sql.Open(db.Dialect, path)
+ Expect(err).ToNot(HaveOccurred())
+ d.SetMaxOpenConns(1)
for _, stmt := range []string{
`create table t(a, b)`,
fmt.Sprintf(`with recursive s(x) as (select 1 union all select x+1 from s where x < %d)
@@ -62,8 +57,16 @@ func openMismatchedIndexDB(ctx context.Context, rows int) *sql.DB {
Expect(err).ToNot(HaveOccurred())
}
Expect(d.Close()).To(Succeed()) // reopen so SQLite reparses the doctored schema
+}
- d = open()
+func openMismatchedIndexDB(ctx context.Context, rows int) *sql.DB {
+ GinkgoHelper()
+ path := filepath.Join(GinkgoT().TempDir(), "mismatched.db")
+ writeMismatchedIndex(ctx, path, rows)
+
+ d, err := sql.Open(db.Dialect, path)
+ Expect(err).ToNot(HaveOccurred())
+ d.SetMaxOpenConns(1)
DeferCleanup(func() { _ = d.Close() })
return d
}