fix(worktree): handle locked git-crypt repos and localized git errors (#532)
This commit is contained in:
@@ -53,18 +53,20 @@ func hasGitCryptFilter(path string) bool {
|
||||
// unlockGitCryptAndCheckout sets up git-crypt decryption in a worktree created
|
||||
// with --no-checkout and then checks out the files.
|
||||
//
|
||||
// git-crypt unlock cannot be used directly because it refuses to run when the
|
||||
// working directory is not clean (which is always the case after --no-checkout).
|
||||
// Instead we manually replicate what git-crypt unlock does:
|
||||
// 1. Symlink the git-crypt key directory from the main repo (GIT_COMMON_DIR)
|
||||
// into the worktree's own git directory so the smudge filter can find it.
|
||||
// If the main repository is unlocked (has keys), it replicates what git-crypt
|
||||
// unlock does so the worktree gets decrypted files:
|
||||
// 1. Symlink the git-crypt key directory from the main repo into the worktree.
|
||||
// 2. Configure the smudge/clean/diff filters in the worktree's local git config.
|
||||
// 3. Run git checkout to populate the working tree with decrypted files.
|
||||
//
|
||||
// If the main repository is locked (no keys), it skips the git-crypt setup and
|
||||
// checks out without decryption. Encrypted files will remain as binary blobs but
|
||||
// the worktree is still usable for non-encrypted files.
|
||||
func (m *Manager) unlockGitCryptAndCheckout(ctx context.Context, worktreePath string) error {
|
||||
m.logger.Debug("setting up git-crypt filters in worktree",
|
||||
zap.String("worktree_path", worktreePath))
|
||||
|
||||
// Step 1: Resolve the worktree's git dir and the common dir (main repo .git).
|
||||
// Resolve the worktree's git dir and the common dir (main repo .git).
|
||||
commonDir, err := resolveGitDir(ctx, worktreePath, "--git-common-dir")
|
||||
if err != nil {
|
||||
return &GitCryptError{Op: "resolve-common-dir", Path: worktreePath, Output: "", Err: err}
|
||||
@@ -74,19 +76,28 @@ func (m *Manager) unlockGitCryptAndCheckout(ctx context.Context, worktreePath st
|
||||
return &GitCryptError{Op: "resolve-git-dir", Path: worktreePath, Output: "", Err: err}
|
||||
}
|
||||
|
||||
// Step 2: Symlink the git-crypt key directory into the worktree git dir.
|
||||
// Check if the main repo has git-crypt unlocked (keys present).
|
||||
src := filepath.Join(commonDir, "git-crypt")
|
||||
dst := filepath.Join(gitDir, "git-crypt")
|
||||
if err := symlinkGitCryptDir(src, dst); err != nil {
|
||||
return &GitCryptError{Op: "symlink", Path: worktreePath, Output: "", Err: err}
|
||||
unlocked := isGitCryptUnlocked(src)
|
||||
|
||||
if unlocked {
|
||||
// Symlink the git-crypt key directory into the worktree git dir.
|
||||
dst := filepath.Join(gitDir, "git-crypt")
|
||||
if err := symlinkGitCryptDir(src, dst); err != nil {
|
||||
return &GitCryptError{Op: "symlink", Path: worktreePath, Output: "", Err: err}
|
||||
}
|
||||
|
||||
// Configure the smudge/clean/diff filters.
|
||||
if err := configureGitCryptFilters(ctx, worktreePath); err != nil {
|
||||
return &GitCryptError{Op: "config", Path: worktreePath, Output: "", Err: err}
|
||||
}
|
||||
} else {
|
||||
m.logger.Warn("git-crypt is locked in main repository, checking out without decryption",
|
||||
zap.String("common_dir", commonDir),
|
||||
zap.String("worktree_path", worktreePath))
|
||||
}
|
||||
|
||||
// Step 3: Configure the smudge/clean/diff filters.
|
||||
if err := configureGitCryptFilters(ctx, worktreePath); err != nil {
|
||||
return &GitCryptError{Op: "config", Path: worktreePath, Output: "", Err: err}
|
||||
}
|
||||
|
||||
// Step 4: Checkout HEAD to populate the working tree with decrypted files.
|
||||
// Checkout HEAD to populate the working tree.
|
||||
checkoutCmd := exec.CommandContext(ctx, "git", "checkout", "HEAD", "--", ".")
|
||||
checkoutCmd.Dir = worktreePath
|
||||
if output, err := checkoutCmd.CombinedOutput(); err != nil {
|
||||
@@ -102,8 +113,13 @@ func (m *Manager) unlockGitCryptAndCheckout(ctx context.Context, worktreePath st
|
||||
}
|
||||
}
|
||||
|
||||
m.logger.Info("successfully set up git-crypt and checked out worktree",
|
||||
zap.String("worktree_path", worktreePath))
|
||||
if unlocked {
|
||||
m.logger.Info("successfully set up git-crypt and checked out worktree",
|
||||
zap.String("worktree_path", worktreePath))
|
||||
} else {
|
||||
m.logger.Info("checked out worktree without git-crypt decryption (repo is locked)",
|
||||
zap.String("worktree_path", worktreePath))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -125,6 +141,7 @@ func resolveGitDir(ctx context.Context, worktreePath, flag string) (string, erro
|
||||
|
||||
// symlinkGitCryptDir creates a symlink from src (main repo's .git/git-crypt)
|
||||
// to dst (worktree's git dir git-crypt). Skips if dst already exists.
|
||||
// Caller must verify src is valid (via isGitCryptUnlocked) before calling.
|
||||
func symlinkGitCryptDir(src, dst string) error {
|
||||
if _, err := os.Stat(src); err != nil {
|
||||
return fmt.Errorf("git-crypt key dir not found at %s: %w", src, err)
|
||||
@@ -136,6 +153,18 @@ func symlinkGitCryptDir(src, dst string) error {
|
||||
return os.Symlink(src, dst)
|
||||
}
|
||||
|
||||
// isGitCryptUnlocked checks whether a git-crypt directory exists and contains
|
||||
// at least one key file (e.g. keys/default). Returns false if the directory
|
||||
// doesn't exist, has no keys/ subdir, or the keys/ subdir is empty (locked).
|
||||
func isGitCryptUnlocked(gitCryptDir string) bool {
|
||||
keysDir := filepath.Join(gitCryptDir, "keys")
|
||||
entries, err := os.ReadDir(keysDir)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return len(entries) > 0
|
||||
}
|
||||
|
||||
// configureGitCryptFilters sets the smudge/clean/diff filters in the
|
||||
// worktree's local git config so that git checkout can decrypt files.
|
||||
func configureGitCryptFilters(ctx context.Context, worktreePath string) error {
|
||||
@@ -172,9 +201,13 @@ func (e *GitCryptError) Unwrap() error {
|
||||
}
|
||||
|
||||
// isGitCryptSmudgeError checks if a git error is caused by git-crypt smudge filter failure.
|
||||
// The detection is language-agnostic: git translates its own messages but the
|
||||
// filter name ("git-crypt smudge") always appears verbatim in the output.
|
||||
func isGitCryptSmudgeError(output string) bool {
|
||||
lower := strings.ToLower(output)
|
||||
return strings.Contains(lower, "smudge filter git-crypt failed") ||
|
||||
strings.Contains(lower, "filter '\"git-crypt\" smudge' failed") ||
|
||||
strings.Contains(lower, "filter 'git-crypt smudge' failed")
|
||||
// Language-agnostic: look for the filter name which is never translated.
|
||||
if strings.Contains(lower, "git-crypt") && strings.Contains(lower, "smudge") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -87,6 +87,21 @@ func TestIsGitCryptSmudgeError(t *testing.T) {
|
||||
output: "error: external filter 'git-crypt smudge' failed",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "portuguese locale error",
|
||||
output: "error: filtro externo 'git-crypt smudge' falhou 1",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "portuguese fatal with git-crypt smudge command",
|
||||
output: "fatal: tools/config.yml: filtro de mancha git-crypt smudge falhou",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "german locale error",
|
||||
output: "Fehler: externer Filter 'git-crypt smudge' fehlgeschlagen",
|
||||
expected: true,
|
||||
},
|
||||
{
|
||||
name: "unrelated git error",
|
||||
output: "fatal: pathspec 'foo' did not match any files",
|
||||
@@ -102,6 +117,11 @@ func TestIsGitCryptSmudgeError(t *testing.T) {
|
||||
output: "fatal: 'main' is already checked out at '/path/to/worktree'",
|
||||
expected: false,
|
||||
},
|
||||
{
|
||||
name: "only git-crypt without smudge",
|
||||
output: "git-crypt: some other error",
|
||||
expected: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
@@ -149,6 +169,35 @@ func TestUsesGitCrypt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsGitCryptUnlocked(t *testing.T) {
|
||||
t.Run("returns false when dir does not exist", func(t *testing.T) {
|
||||
if isGitCryptUnlocked("/nonexistent/git-crypt") {
|
||||
t.Error("expected false for nonexistent directory")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns false when keys subdir is empty (locked)", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(dir, "keys"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if isGitCryptUnlocked(dir) {
|
||||
t.Error("expected false for empty keys directory (locked repo)")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("returns true when keys subdir has entries (unlocked)", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
defaultKey := filepath.Join(dir, "keys", "default")
|
||||
if err := os.MkdirAll(defaultKey, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !isGitCryptUnlocked(dir) {
|
||||
t.Error("expected true when keys directory has entries (unlocked repo)")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- E2E tests requiring git-crypt binary ----------
|
||||
|
||||
// skipIfNoGitCrypt skips the test if the git-crypt binary is not available.
|
||||
@@ -379,3 +428,88 @@ func TestUnlockGitCryptAndCheckout_ManualWorktree(t *testing.T) {
|
||||
t.Errorf("worktree not clean after unlock+checkout: %s", status)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestCreateWorktree_GitCryptLockedRepo(t *testing.T) {
|
||||
skipIfNoGitCrypt(t)
|
||||
|
||||
cfg := newTestConfig(t)
|
||||
log := newTestLogger()
|
||||
store := newMockStore()
|
||||
|
||||
mgr, err := NewManager(cfg, store, log)
|
||||
if err != nil {
|
||||
t.Fatalf("NewManager: %v", err)
|
||||
}
|
||||
|
||||
repoPath := initGitCryptRepo(t)
|
||||
|
||||
// Export the key before locking (git-crypt lock removes it from .git/).
|
||||
keyFile := filepath.Join(t.TempDir(), "exported.key")
|
||||
exportCmd := exec.Command("git-crypt", "export-key", keyFile)
|
||||
exportCmd.Dir = repoPath
|
||||
if out, err := exportCmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git-crypt export-key failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// Lock the repo — removes keys, re-encrypts working tree files.
|
||||
lockCmd := exec.Command("git-crypt", "lock")
|
||||
lockCmd.Dir = repoPath
|
||||
if out, err := lockCmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("git-crypt lock failed: %v\n%s", err, out)
|
||||
}
|
||||
|
||||
// Verify the repo is locked (secret.txt should be encrypted binary).
|
||||
secretContent, _ := os.ReadFile(filepath.Join(repoPath, "secret.txt"))
|
||||
if strings.Contains(string(secretContent), "top-secret-value") {
|
||||
t.Fatal("expected secret.txt to be encrypted after lock")
|
||||
}
|
||||
|
||||
// Create a worktree from the locked repo — should succeed.
|
||||
wt, err := mgr.Create(context.Background(), CreateRequest{
|
||||
TaskID: "gc-locked-1",
|
||||
SessionID: "gc-locked-session-1",
|
||||
TaskTitle: "Git Crypt Locked Repo",
|
||||
RepositoryID: "repo-gc-locked",
|
||||
RepositoryPath: repoPath,
|
||||
BaseBranch: "main",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create() with locked repo should succeed, got: %v", err)
|
||||
}
|
||||
|
||||
// Public file must be present and readable.
|
||||
pub, err := os.ReadFile(filepath.Join(wt.Path, "public.txt"))
|
||||
if err != nil {
|
||||
t.Fatalf("read public.txt: %v", err)
|
||||
}
|
||||
if strings.TrimSpace(string(pub)) != "public-value" {
|
||||
t.Errorf("public.txt = %q, want %q", string(pub), "public-value")
|
||||
}
|
||||
|
||||
// Encrypted file should exist but be binary (not decrypted).
|
||||
secret, err := os.ReadFile(filepath.Join(wt.Path, "secret.txt"))
|
||||
if err != nil {
|
||||
t.Fatalf("read secret.txt: %v", err)
|
||||
}
|
||||
if strings.Contains(string(secret), "top-secret-value") {
|
||||
t.Error("secret.txt should be encrypted in worktree of locked repo")
|
||||
}
|
||||
|
||||
// Now unlock git-crypt in the worktree — this should work because
|
||||
// no broken filters are configured.
|
||||
unlockCmd := exec.Command("git-crypt", "unlock", keyFile)
|
||||
unlockCmd.Dir = wt.Path
|
||||
if out, unlockErr := unlockCmd.CombinedOutput(); unlockErr != nil {
|
||||
t.Fatalf("git-crypt unlock in worktree should work, got: %v\n%s", unlockErr, out)
|
||||
}
|
||||
|
||||
// After unlock, secret.txt should be decrypted.
|
||||
secret, err = os.ReadFile(filepath.Join(wt.Path, "secret.txt"))
|
||||
if err != nil {
|
||||
t.Fatalf("read secret.txt after unlock: %v", err)
|
||||
}
|
||||
if strings.TrimSpace(string(secret)) != "top-secret-value" {
|
||||
t.Errorf("secret.txt after unlock = %q, want %q", string(secret), "top-secret-value")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user