Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion internal/gitsafe/gitsafe.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
//
// The single-key cases are switched off on the command line. Filter and diff
// driver commands are named per driver, so they cannot be switched off without
// knowing the names; a repository whose own config defines any is skipped instead.
// knowing the names; Command and Check skip repositories defining any instead.
// IndexEntriesCommand has fixed index-only arguments that never read file content,
// so that narrower query does not need to refuse driver definitions.
// Commands defined in the user's own global config, such as git-lfs, are the
// user's choice and are not affected.
package gitsafe
Expand Down
45 changes: 45 additions & 0 deletions internal/gitsafe/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package gitsafe

import (
"context"
"os/exec"
"runtime"
"strings"
)

// IndexEntriesCommand lists cached index paths under one literal path. Its argv
// is fixed: it cannot inspect worktree contents, run filters/textconv, recurse
// into submodules, or accept additional options. Repository driver definitions
// therefore do not require the refusal used by Command for status/diff.
//
// Repository redirects, hooks, fsmonitor and optional index writes retain the
// same protections as Command. The caller must propagate Git errors and reject
// stderr diagnostics even on a zero exit: Git can report a missing sparse tree
// while returning an empty result successfully. Literal pathspecs require Git
// 1.9, the existing floor of memory's privacy query.
//
// Sparse-index expansion can need missing promisor tree objects. Suppress lazy
// fetching where supported and deny every transport as a backstop: otherwise a
// fetch can run the repository's upload-pack or a remote helper. The protocol
// allow-list already exists in Git 2.6.7, before partial clones; older Git ignores
// these environment variables but cannot perform a promisor fetch. No newer
// command-line flag or Git version requirement is introduced.
func IndexEntriesCommand(ctx context.Context, dir, path string) *exec.Cmd {

Check failure on line 27 in internal/gitsafe/index.go

View workflow job for this annotation

GitHub Actions / Code Quality & Lint

unreachable func: IndexEntriesCommand
env := environment()
filtered := env[:0]
for _, entry := range env {
name, _, _ := strings.Cut(entry, "=")
if runtime.GOOS == "windows" {
name = strings.ToUpper(name)
}
switch name {
case "GIT_LITERAL_PATHSPECS", "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS",
"GIT_ALLOW_PROTOCOL", "GIT_NO_LAZY_FETCH":
continue
}
filtered = append(filtered, entry)
}
filtered = append(filtered, "GIT_ALLOW_PROTOCOL=", "GIT_NO_LAZY_FETCH=1")
checked := &Checked{dir: dir, env: filtered}
return checked.Command(ctx, "-c", "advice.sparseIndexExpanded=false", "--literal-pathspecs", "ls-files", "--cached", "-z", "--", path)
}
92 changes: 92 additions & 0 deletions internal/gitsafe/index_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package gitsafe

import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)

func TestIndexEntriesAreLiteralCachedAndNeverRunRepositoryPrograms(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git unavailable")
}
if !gitAtLeast(t, 1, 9) {
t.Skip("literal pathspecs require Git 1.9")
}
t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull)
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
root := t.TempDir()
git := func(args ...string) {
t.Helper()
cmd := exec.Command("git", append([]string{"-C", root}, args...)...)
cmd.Env = environment()
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v: %v: %s", args, err, out)
}
}
git("init", "-q")
for _, dir := range []string{"notes[1]", "notes1", "--others"} {
if err := os.MkdirAll(filepath.Join(root, dir), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(root, dir, "tracked.md"), []byte("tracked"), 0600); err != nil {
t.Fatal(err)
}
}
git("add", ".")
if err := os.WriteFile(filepath.Join(root, "untracked.md"), []byte("untracked"), 0600); err != nil {
t.Fatal(err)
}
marker := filepath.Join(root, "program-ran")
program := "echo invoked >> '" + strings.ReplaceAll(filepath.ToSlash(marker), "'", "'\\''") + "'"
for _, key := range []string{"filter.tripwire.clean", "filter.tripwire.smudge", "filter.tripwire.process", "diff.tripwire.command", "diff.tripwire.textconv", "core.fsmonitor"} {
git("config", key, program)
}
if err := os.WriteFile(filepath.Join(root, ".gitattributes"), []byte("* filter=tripwire diff=tripwire\n"), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("GIT_DIR", filepath.Join(t.TempDir(), ".git"))
t.Setenv("GIT_INDEX_FILE", filepath.Join(t.TempDir(), "empty-index"))
t.Setenv("GIT_ALLOW_PROTOCOL", "file")
t.Setenv("GIT_NO_LAZY_FETCH", "0")
// Conflicting inherited pathspec modes must not turn a literal query into
// an empty or wildcard answer about a different set of tracked paths.
for _, key := range []string{"GIT_LITERAL_PATHSPECS", "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"} {
t.Setenv(key, "1")
}
for _, dir := range []string{"notes[1]", "--others"} {
cmd := IndexEntriesCommand(context.Background(), root, dir)
for key, want := range map[string]string{"GIT_ALLOW_PROTOCOL": "", "GIT_NO_LAZY_FETCH": "1"} {
var values []string
for _, entry := range cmd.Env {
name, value, ok := strings.Cut(entry, "=")
if ok && strings.EqualFold(name, key) {
values = append(values, value)
}
}
if len(values) != 1 || values[0] != want {
t.Fatalf("privacy query %s = %q, want one value %q", key, values, want)
}
}
out, err := cmd.CombinedOutput()
if err != nil || string(out) != dir+"/tracked.md\x00" {
t.Fatalf("literal index query %q = %q, %v", dir, out, err)
}
}
if _, err := Command(context.Background(), root, "status", "--porcelain"); !errors.Is(err, ErrRepositoryDefinesCommands) {
t.Fatalf("status/diff policy was weakened: %v", err)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("repository program executed: %v", err)
}
if err := os.WriteFile(filepath.Join(root, ".git", "index"), []byte("corrupt index"), 0600); err != nil {
t.Fatal(err)
}
if out, err := IndexEntriesCommand(context.Background(), root, ".").CombinedOutput(); err == nil {
t.Fatalf("corrupt index appeared to be a valid empty index: %q", out)
}
}
24 changes: 10 additions & 14 deletions internal/memory/escape_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package memory

import (
"context"
"errors"
"fmt"
"os"
Expand Down Expand Up @@ -980,28 +981,23 @@ func TestACorruptRepositoryStillRefusesLocalWrites(t *testing.T) {
}
}

// A REPOSITORY THAT DEFINES FILTER OR DIFF COMMANDS IS NOT ASKED, so the local
// write stays refused — but the refusal has to say that, not that git failed:
// git was never run, and "git could not say" sends the reader looking for a
// broken repository instead of at the config that made Zero decline to ask.
func TestALocalWriteInAFilterRepositoryNamesTheConfigRefusal(t *testing.T) {
// The fixed cached-index query can establish privacy without reading worktree
// contents. General status/diff commands still refuse repository-defined drivers.
func TestLocalPrivacyQueryDoesNotWeakenGeneralFilterRefusal(t *testing.T) {
root := t.TempDir()
paths := DefaultPaths(root)
seedStoreRepo(t, root)
runStoreGit(t, root, "config", "filter.crypt.clean", "cat")

_, err := Write(paths, ScopeLocal, "private", "d", "machine-local secret")
if !errors.Is(err, ErrNotPrivate) {
t.Fatalf("Write in a repository defining a filter command = %v, want ErrNotPrivate", err)
}
_, err := gitsafe.Command(context.Background(), root, "status", "--porcelain")
if !errors.Is(err, gitsafe.ErrRepositoryDefinesCommands) {
t.Errorf("the refusal does not carry the config cause: %v", err)
t.Fatalf("general Git commands no longer refuse filter definitions: %v", err)
}
if strings.Contains(err.Error(), "git could not say") {
t.Errorf("the refusal blames git, which was never run: %v", err)
if _, err := Write(paths, ScopeLocal, "private", "d", "machine-local secret"); err != nil {
t.Fatalf("fixed index-only privacy query refused the local write: %v", err)
}
if _, statErr := os.Lstat(filepath.Join(paths.LocalDir, "private.md")); !os.IsNotExist(statErr) {
t.Errorf("the refused note was written anyway: %v", statErr)
if _, err := os.Lstat(filepath.Join(paths.LocalDir, "private.md")); err != nil {
t.Fatalf("private note was not saved: %v", err)
}
}

Expand Down
19 changes: 8 additions & 11 deletions internal/memory/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -773,12 +773,6 @@ func refuseTrackedLocalStore(handle *os.Root, relative, dir string) error {
}
for _, repo := range repos {
tracked, err := trackedStoreEntries(repo, resolved)
if errors.Is(err, gitsafe.ErrRepositoryDefinesCommands) {
// Still a refusal, but git was never run, so it must not read as
// git failing to answer.
return fmt.Errorf("%w: %s is inside the git repository at %s, and %w; without asking git, Zero cannot confirm that nothing there is tracked",
ErrNotPrivate, dir, repo, err)
}
if err != nil {
return fmt.Errorf("%w: %s is inside the git repository at %s, and git could not say which files there are tracked: %v",
ErrNotPrivate, dir, repo, err)
Expand Down Expand Up @@ -902,14 +896,10 @@ func trackedStoreEntries(repo, dir string) ([]string, error) {
// Query from this repository's root, not the store, where Git could select
// a nested repository. Literal pathspecs prevent glob characters in a
// directory name from selecting a different set of indexed paths.
cmd, err := gitsafe.Command(ctx, repo, "ls-files", "-z", "--", filepath.ToSlash(relative))
if err != nil {
return nil, err
}
cmd := gitsafe.IndexEntriesCommand(ctx, repo, filepath.ToSlash(relative))
// Cancelling the context does not by itself return control here: WaitDelay is
// what stops a git holding its pipes open from outliving the deadline.
cmd.WaitDelay = gitIndexTimeout
cmd.Env = append(gitDiscoveryEnv(cmd.Env), "GIT_LITERAL_PATHSPECS=1")
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
Expand All @@ -919,6 +909,13 @@ func trackedStoreEntries(repo, dir string) ([]string, error) {
}
return nil, err
}
// Some Git versions report an unreadable sparse tree on stderr but return
// success with no entries. That is not proof of privacy. Harmless sparse
// expansion advice is suppressed by the fixed query; other diagnostics fail
// closed just like a nonzero exit.
if detail := singleLine(stderr.String()); detail != "" {
return nil, fmt.Errorf("git index query emitted diagnostics: %s", detail)
}
entries := make([]string, 0, 4)
prefix := filepath.ToSlash(relative)
if prefix == "." {
Expand Down
71 changes: 71 additions & 0 deletions internal/memory/privacy_index_review_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package memory

import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"

"github.com/Twigpine/zero/internal/gitsafe"
)

func TestLocalPrivacyIndexReadDoesNotExecuteConfiguredGitPrograms(t *testing.T) {
for _, tracked := range []bool{false, true} {
t.Run(map[bool]string{false: "untracked", true: "tracked"}[tracked], func(t *testing.T) {
root := t.TempDir()
paths := DefaultPaths(root)
seedStoreRepo(t, root)
note := writeStoreFile(t, paths, "private.md", "---\nname: private\n---\n\noriginal\n")
writeStoreFile(t, paths, gitignoreName, localIgnoreContent)
if tracked {
runStoreGit(t, root, "add", "-f", ".zero/memory/local/private.md")
}
marker := filepath.Join(root, "repository-program-ran")
program := "echo invoked >> '" + strings.ReplaceAll(filepath.ToSlash(marker), "'", "'\\''") + "'"
for _, key := range []string{"filter.tripwire.clean", "filter.tripwire.smudge", "filter.tripwire.process", "diff.tripwire.command", "diff.tripwire.textconv", "core.fsmonitor"} {
runStoreGit(t, root, "config", key, program)
}
if err := os.WriteFile(filepath.Join(root, ".gitattributes"), []byte("* filter=tripwire diff=tripwire\n"), 0600); err != nil {
t.Fatal(err)
}
if _, err := gitsafe.Command(context.Background(), root, "status", "--porcelain"); !errors.Is(err, gitsafe.ErrRepositoryDefinesCommands) {
t.Fatalf("general Git safety gate changed: %v", err)
}
_, err := Write(paths, ScopeLocal, "private", "d", "replacement")
if tracked {
if !errors.Is(err, ErrNotPrivate) {
t.Errorf("tracked private note accepted: %v", err)
}
body, readErr := os.ReadFile(note)
if readErr != nil || !strings.Contains(string(body), "original") {
t.Errorf("tracked note changed: %q %v", body, readErr)
}
} else if err != nil {
t.Errorf("index-only privacy query refused a harmless filter definition: %v", err)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatalf("repository-defined program ran: %v", err)
}
})
}
}

func TestLocalPrivacyIndexErrorStaysClosed(t *testing.T) {
root := t.TempDir()
paths := DefaultPaths(root)
seedStoreRepo(t, root)
path := writeStoreFile(t, paths, "private.md", "---\nname: private\n---\n\noriginal\n")
writeStoreFile(t, paths, gitignoreName, localIgnoreContent)
if err := os.WriteFile(filepath.Join(root, ".git", "index"), []byte("corrupt index"), 0600); err != nil {
t.Fatal(err)
}
if _, err := Write(paths, ScopeLocal, "private", "d", "replacement"); !errors.Is(err, ErrNotPrivate) {
t.Fatalf("failed index query admitted a local write: %v", err)
}
body, err := os.ReadFile(path)
if err != nil || !strings.Contains(string(body), "original") {
t.Fatalf("failed privacy query replaced the note: %q %v", body, err)
}
}
Loading
Loading