From 6c82ef0f1b445ea8395be1f7692bcd8fe384c353 Mon Sep 17 00:00:00 2001 From: Ibrahim Jarif Date: Fri, 24 Apr 2020 01:14:37 +0530 Subject: [PATCH] Restore: Handle incorrect encryption key (#5284) (#5286) Jira - DGRAPH-1281 and DGRAPH-1282 When the restore is started, we open a badger instance with the provided encryption key and then check if the backup file can be opened using the encryption key. If the backup cannot be opened using the encryption key, we return an error to the user but the badger DB stores the encryption key. When the user tries to restore the same backup to the same badger instance without a key (because backup is unencrypted), badger complaints about the missing key. This PR fixes by opening badger after opening the backup file. This ensures we don't open an encrypted badger db for an unencrypted backup file. (cherry picked from commit 25c37c823593fe4480ca10e3354336503be3785b) --- ee/backup/restore.go | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/ee/backup/restore.go b/ee/backup/restore.go index a1155f18c72..aaf711a4e32 100644 --- a/ee/backup/restore.go +++ b/ee/backup/restore.go @@ -47,6 +47,22 @@ func RunRestore(pdir, location, backupId, keyfile string) LoadResult { func(r io.Reader, groupId int, preds predicateSet) (uint64, error) { dir := filepath.Join(pdir, fmt.Sprintf("p%d", groupId)) + r, err := enc.GetReader(keyfile, r) + if err != nil { + return 0, err + } + + gzReader, err := gzip.NewReader(r) + if err != nil { + if len(keyfile) != 0 { + err = errors.Wrap(err, + "Unable to read the backup. Ensure the encryption key is correct.") + } + return 0, err + + } + // The badger DB should be opened only after creating the backup + // file reader and verifying the encryption in the backup file. db, err := badger.OpenManaged(badger.DefaultOptions(dir). WithSyncWrites(false). WithTableLoadingMode(options.MemoryMap). @@ -61,14 +77,7 @@ func RunRestore(pdir, location, backupId, keyfile string) LoadResult { if !pathExist(dir) { fmt.Println("Creating new db:", dir) } - r, err = enc.GetReader(keyfile, r) - if err != nil { - return 0, err - } - gzReader, err := gzip.NewReader(r) - if err != nil { - return 0, err - } + maxUid, err := loadFromBackup(db, gzReader, preds) if err != nil { return 0, err