Skip to content

Commit

Permalink
fix: Don't modify ciphertext in edit command if plaintext did not change
Browse files Browse the repository at this point in the history
  • Loading branch information
twpayne committed Aug 5, 2024
1 parent c0a8059 commit d6b20c3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
19 changes: 15 additions & 4 deletions internal/cmd/editcmd.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cmd

import (
"crypto/sha512"
"crypto/subtle"
"log/slog"
"os"
"runtime"
Expand Down Expand Up @@ -85,8 +87,9 @@ func (c *Config) runEditCmd(cmd *cobra.Command, args []string) error {

editorArgs := make([]string, 0, len(targetRelPaths))
type transparentlyDecryptedFile struct {
sourceAbsPath chezmoi.AbsPath
decryptedAbsPath chezmoi.AbsPath
sourceAbsPath chezmoi.AbsPath
decryptedAbsPath chezmoi.AbsPath
preEditPlaintextSum [sha512.Size]byte
}
var transparentlyDecryptedFiles []transparentlyDecryptedFile
TARGET_REL_PATH:
Expand Down Expand Up @@ -117,8 +120,9 @@ TARGET_REL_PATH:
return err
}
transparentlyDecryptedFile := transparentlyDecryptedFile{
sourceAbsPath: c.SourceDirAbsPath.Join(sourceRelPath.RelPath()),
decryptedAbsPath: decryptedAbsPath,
sourceAbsPath: c.SourceDirAbsPath.Join(sourceRelPath.RelPath()),
decryptedAbsPath: decryptedAbsPath,
preEditPlaintextSum: sha512.Sum512(contents),
}
transparentlyDecryptedFiles = append(transparentlyDecryptedFiles, transparentlyDecryptedFile)
editorArgs = append(editorArgs, decryptedAbsPath.String())
Expand Down Expand Up @@ -165,6 +169,13 @@ TARGET_REL_PATH:

postEditFunc := func() error {
for _, transparentlyDecryptedFile := range transparentlyDecryptedFiles {
postEditPlaintext, err := c.baseSystem.ReadFile(transparentlyDecryptedFile.decryptedAbsPath)
if err != nil {
return err
}
if postEditPlaintextSum := sha512.Sum512(postEditPlaintext); subtle.ConstantTimeCompare(transparentlyDecryptedFile.preEditPlaintextSum[:], postEditPlaintextSum[:]) != 0 {
return nil
}
contents, err := c.encryption.EncryptFile(transparentlyDecryptedFile.decryptedAbsPath)
if err != nil {
return err
Expand Down
19 changes: 19 additions & 0 deletions internal/cmd/testdata/scripts/issue3887.txtar
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
mkageconfig
mkgitconfig
prependline ${CHEZMOICONFIGDIR}/chezmoi.toml 'edit.command = "/bin/true"'

# add an initial encrypted file
exec chezmoi init
exec chezmoi add --encrypt ${HOME}${/}.encrypted
exec chezmoi git add .
exec chezmoi git commit -- -m 'initial commit' .

# test that chezmoi edit on an encrypted file with no changes does not change the ciphertext
exec chezmoi edit ${HOME}${/}.encrypted
exec chezmoi diff
! stdout .
exec chezmoi git diff
! stdout .

-- home/user/.encrypted --
plaintext

0 comments on commit d6b20c3

Please sign in to comment.