Add option to crash autorestic when key is missing instead of generating a new key (#383)

* feat(backend): add requireKey option to backend

This option will prevent `autorestic` from generating a key and will
cause it to crash instead. This is intended for use cases where you want
to provision the key yourself and don't want `autorestic` to
accidentally generate one for you.

* doc(backend): document requireKey
This commit is contained in:
Boris Bera
2024-08-28 11:21:01 -04:00
committed by GitHub
parent dd01e97cf3
commit bc74d3f13e
5 changed files with 54 additions and 11 deletions

View File

@@ -18,13 +18,14 @@ type BackendRest struct {
}
type Backend struct {
name string
Type string `mapstructure:"type,omitempty"`
Path string `mapstructure:"path,omitempty"`
Key string `mapstructure:"key,omitempty"`
Env map[string]string `mapstructure:"env,omitempty"`
Rest BackendRest `mapstructure:"rest,omitempty"`
Options Options `mapstructure:"options,omitempty"`
name string
Type string `mapstructure:"type,omitempty"`
Path string `mapstructure:"path,omitempty"`
Key string `mapstructure:"key,omitempty"`
RequireKey bool `mapstructure:"requireKey,omitempty"`
Env map[string]string `mapstructure:"env,omitempty"`
Rest BackendRest `mapstructure:"rest,omitempty"`
Options Options `mapstructure:"options,omitempty"`
}
func GetBackend(name string) (Backend, bool) {
@@ -104,6 +105,9 @@ func (b Backend) validate() error {
// Check if key is set in environment
env, _ := b.getEnv()
if _, found := env["RESTIC_PASSWORD"]; !found {
if b.RequireKey {
return fmt.Errorf("backend %s requires a key but none was provided", b.name)
}
// No key set in config file or env => generate random key and save file
key := generateRandomKey()
b.Key = key

View File

@@ -6,6 +6,7 @@ import (
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
)
func TestGenerateRepo(t *testing.T) {
@@ -222,4 +223,16 @@ func TestValidate(t *testing.T) {
}
assertEqual(t, err.Error(), "Backend \"foo\" has no \"path\"")
})
t.Run("require key with no key", func(t *testing.T) {
b := Backend{
name: "foo",
Type: "local",
Path: "~/foo/bar",
RequireKey: true,
}
err := b.validate()
fmt.Printf("error: %v\n", err)
assert.EqualError(t, err, "backend foo requires a key but none was provided")
})
}