Skip to content

Commit

Permalink
Merge pull request restic#4853 from MichaelEischer/safer-repo-init
Browse files Browse the repository at this point in the history
init: double check that no repository exists yet
  • Loading branch information
MichaelEischer committed Jun 9, 2024
2 parents 7861fc1 + bab7603 commit da45127
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
8 changes: 8 additions & 0 deletions internal/repository/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,14 @@ func (r *Repository) Init(ctx context.Context, version uint, password string, ch
if err == nil {
return errors.New("repository master key and config already initialized")
}
// double check to make sure that a repository is not accidentally reinitialized
// if the backend somehow fails to stat the config file. An initialized repository
// must always contain at least one key file.
if err := r.List(ctx, restic.KeyFile, func(_ restic.ID, _ int64) error {
return errors.New("repository already contains keys")
}); err != nil {
return err
}

cfg, err := restic.CreateConfig(version)
if err != nil {
Expand Down
17 changes: 17 additions & 0 deletions internal/repository/repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"math/rand"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
Expand Down Expand Up @@ -457,3 +458,19 @@ func TestListPack(t *testing.T) {

rtest.Assert(t, !c.Has(backend.Handle{Type: restic.PackFile, Name: packID.String()}), "tree pack should no longer be cached as ListPack does not set IsMetadata in the backend.Handle")
}

func TestNoDoubleInit(t *testing.T) {
r, be := repository.TestRepositoryWithVersion(t, restic.StableRepoVersion)

repo, err := repository.New(be, repository.Options{})
rtest.OK(t, err)

pol := r.Config().ChunkerPolynomial
err = repo.Init(context.TODO(), r.Config().Version, test.TestPassword, &pol)
rtest.Assert(t, strings.Contains(err.Error(), "repository master key and config already initialized"), "expected config exist error, got %q", err)

// must also prevent init if only keys exist
rtest.OK(t, be.Remove(context.TODO(), backend.Handle{Type: backend.ConfigFile}))
err = repo.Init(context.TODO(), r.Config().Version, test.TestPassword, &pol)
rtest.Assert(t, strings.Contains(err.Error(), "repository already contains keys"), "expected already contains keys error, got %q", err)
}

0 comments on commit da45127

Please sign in to comment.