Prevent files from being encrypted twice

This commit is contained in:
Adrian Utrilla 2018-03-28 19:03:01 +02:00
Родитель c67cc9b1dc
Коммит a81f93919c
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: D9B452CB733E4A16
2 изменённых файлов: 32 добавлений и 0 удалений

Просмотреть файл

@ -26,4 +26,5 @@ const (
FileHasNotBeenModified int = 200
NoEditorFound int = 201
FailedToCompareVersions int = 202
FileAlreadyEncrypted int = 203
)

Просмотреть файл

@ -5,6 +5,7 @@ import (
"fmt"
wordwrap "github.com/mitchellh/go-wordwrap"
"go.mozilla.org/sops"
"go.mozilla.org/sops/cmd/sops/codes"
"go.mozilla.org/sops/cmd/sops/common"
@ -22,12 +23,42 @@ type encryptOpts struct {
GroupThreshold int
}
type fileAlreadyEncryptedError struct{}
func (err *fileAlreadyEncryptedError) Error() string {
return "File already encrypted"
}
func (err *fileAlreadyEncryptedError) UserError() string {
message := "The file you have provided contains a top-level entry called " +
"'sops'. This is generally due to the file already being encrypted. " +
"SOPS uses a top-level entry called 'sops' to store the metadata " +
"required to decrypt the file. For this reason, SOPS can not " +
"encrypt files that already contain such an entry.\n\n" +
"If this is an unencrypted file, rename the 'sops' entry.\n\n" +
"If this is an encrypted file and you want to edit it, use the " +
"editor mode, for example: `sops my_file.yaml`"
return wordwrap.WrapString(message, 75)
}
func ensureNoMetadata(opts encryptOpts, bytes []byte) error {
_, err := opts.InputStore.UnmarshalMetadata(bytes)
if err != nil {
// OK, no metadata found
return nil
}
return &fileAlreadyEncryptedError{}
}
func encrypt(opts encryptOpts) (encryptedFile []byte, err error) {
// Load the file
fileBytes, err := ioutil.ReadFile(opts.InputPath)
if err != nil {
return nil, common.NewExitError(fmt.Sprintf("Error reading file: %s", err), codes.CouldNotReadInputFile)
}
if err := ensureNoMetadata(opts, fileBytes); err != nil {
return nil, common.NewExitError(err, codes.FileAlreadyEncrypted)
}
var tree sops.Tree
branch, err := opts.InputStore.Unmarshal(fileBytes)
if err != nil {