diff --git a/changelog/unreleased/issue-5717 b/changelog/unreleased/issue-5717 new file mode 100644 index 000000000..f2d4d6d46 --- /dev/null +++ b/changelog/unreleased/issue-5717 @@ -0,0 +1,12 @@ +Bugfix: Fix damaged repository after concurrent `init` on REST backend + +When two `restic init` runs raced against the same empty repository on +the REST backend, the repository could end up with a leftover key file +that did not belong to the stored config. Clients that happened to pick +that key failed with a "config or key ... is damaged" error. + +Restic now stores the config file before the key file during `init`, so +the losing run no longer leaves a key file behind. + +https://github.com/restic/restic/issues/5717 +https://github.com/restic/restic/pull/21944 diff --git a/internal/repository/key.go b/internal/repository/key.go index e1b0a3dcd..279fbf2b6 100644 --- a/internal/repository/key.go +++ b/internal/repository/key.go @@ -59,12 +59,6 @@ const ( KDFMemory = 60 ) -// createMasterKey creates a new master key in the given backend and encrypts -// it with the password. -func createMasterKey(ctx context.Context, s *Repository, password string) (*Key, error) { - return AddKey(ctx, s, password, "", "", nil) -} - // openKey tries do decrypt the key specified by name with the given password. func openKey(ctx context.Context, s *Repository, id restic.ID, password string) (*Key, error) { if key, ok := testKeyInjection.Load(id); ok { @@ -208,8 +202,9 @@ func LoadKey(ctx context.Context, s *Repository, id restic.ID) (k *Key, err erro return k, nil } -// AddKey adds a new key to an already existing repository. -func AddKey(ctx context.Context, s *Repository, password, username, hostname string, template *crypto.Key) (*Key, error) { +// AddKey adds a new key to an already existing repository. masterKey is the +// master key encrypted and stored in the new key file; it must not be nil. +func AddKey(ctx context.Context, s *Repository, password, username, hostname string, masterKey *crypto.Key) (*Key, error) { // make sure we have valid KDF parameters if params == nil { p, err := crypto.Calibrate(KDFTimeout, KDFMemory) @@ -257,13 +252,7 @@ func AddKey(ctx context.Context, s *Repository, password, username, hostname str return nil, err } - if template == nil { - // generate new random master keys - newkey.master = crypto.NewRandomKey() - } else { - // copy master keys from old key - newkey.master = template - } + newkey.master = masterKey // encrypt master keys (as json) with user key buf, err := json.Marshal(newkey.master) diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 0a3ca836d..7d59d2b67 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -936,16 +936,27 @@ func (r *Repository) Init(ctx context.Context, version uint, password string, ch // init creates a new master key with the supplied password and uses it to save // the config into the repo. +// +// The config is uploaded before the key file. On a backend that rejects +// overwriting an existing file (e.g. rest), a losing concurrent init then +// fails at the config upload and leaves no stray key file behind. func (r *Repository) init(ctx context.Context, password string, cfg restic.Config) error { - key, err := createMasterKey(ctx, r, password) + masterKey := crypto.NewRandomKey() + // r.key must be set before SaveConfig, since saveUnpacked encrypts the + // config file with it. + r.key = masterKey + + if err := restic.SaveConfig(ctx, &internalRepository{r}, cfg); err != nil { + return err + } + r.setConfig(cfg) + + key, err := AddKey(ctx, r, password, "", "", masterKey) if err != nil { return err } - - r.key = key.master r.keyID = key.ID() - r.setConfig(cfg) - return restic.SaveConfig(ctx, &internalRepository{r}, cfg) + return nil } // Key returns the current master key. diff --git a/internal/repository/repository_test.go b/internal/repository/repository_test.go index 5e7a88948..e66c18102 100644 --- a/internal/repository/repository_test.go +++ b/internal/repository/repository_test.go @@ -8,6 +8,7 @@ import ( "io" "math/rand" "path/filepath" + "slices" "strings" "sync" "sync/atomic" @@ -515,6 +516,35 @@ func TestNoDoubleInit(t *testing.T) { rtest.Assert(t, strings.Contains(err.Error(), "repository already contains snapshots"), "expected already contains snapshots error, got %q", err) } +// saveOrderBackend records the types of files in the order they were saved. +type saveOrderBackend struct { + backend.Backend + order []backend.FileType +} + +func (be *saveOrderBackend) Save(ctx context.Context, h backend.Handle, rd backend.RewindReader) error { + be.order = append(be.order, h.Type) + return be.Backend.Save(ctx, h, rd) +} + +// TestInitSavesConfigBeforeKey makes sure that Init uploads the config file +// before the key file, such that a failed config write also prevents the key +// file upload. +func TestInitSavesConfigBeforeKey(t *testing.T) { + be := &saveOrderBackend{Backend: mem.New()} + repo, err := repository.New(be, repository.Options{}) + rtest.OK(t, err) + + rtest.OK(t, repo.Init(context.TODO(), restic.StableRepoVersion, rtest.TestPassword, nil)) + + keyIdx := slices.Index(be.order, backend.KeyFile) + configIdx := slices.Index(be.order, backend.ConfigFile) + + rtest.Assert(t, keyIdx != -1, "key file was never saved") + rtest.Assert(t, configIdx != -1, "config file was never saved") + rtest.Assert(t, configIdx < keyIdx, "expected config file (index %d) to be saved before key file (index %d)", configIdx, keyIdx) +} + func TestSaveBlobAsync(t *testing.T) { repo, _, _ := repository.TestRepositoryWithVersion(t, 2) ctx := context.Background()