Files
skillshare/internal/gitenv/gitenv_test.go
T
Willie 828ba93f27 fix(git): keep a caller's GIT_DIR out of skillshare's git commands (#854)
* fix(git): keep a caller's GIT_DIR out of skillshare's git commands

Git exports GIT_DIR, GIT_WORK_TREE, GIT_INDEX_FILE and related variables
to hooks that run in a linked worktree. Every git process skillshare
started inherited them, and those variables override the directory the
command runs in. Run from a post-checkout or post-merge hook, skillshare
therefore acted on the hook's repository instead of its own: install's
sparse clone turned on sparse checkout there (a later merge removed every
file outside the skill's path), the remote tree check's `git init --bare`
made it a bare repository, install's reconcile recorded its origin and
branch, and push staged and committed into it.

internal/gitenv builds git commands without the variables that
`git rev-parse --local-env-vars` lists for choosing a repository, work
tree, index, object store or config file. GIT_CONFIG_COUNT and
GIT_CONFIG_PARAMETERS stay, because users pass credentials through them
and install's token auth appends to the existing count. Every git call in
cmd/skillshare, internal/install, internal/git, internal/check and
internal/config now goes through it, and plugin runCommand starts native
CLIs from the same environment because they run git as well. The hooks
service keeps its own stricter filter.

Closes #852

* test(gitenv): fail on new git commands that bypass gitenv

Each git call site converted for #852 is safe only because it goes
through gitenv.Command, and about half have no test of their own. A
future exec.Command("git", ...) would silently bring the bug back, so a
syntactic guard now rejects one outside gitenv, hooks and testutil,
mirroring the sourcefs and sourcewalk ratchets.

The Environ test also checks a lowercase name, since Windows environment
names are case-insensitive, and compares against literal keys so that
removing one from repoVars fails it. The wiki records the rule.
2026-11-11 21:08:47 +08:00

141 lines
3.6 KiB
Go

package gitenv
import (
"go/ast"
"go/parser"
"go/token"
"io/fs"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
)
func TestEnvironDropsRepositorySelection(t *testing.T) {
t.Setenv("GIT_DIR", "/caller/.git")
t.Setenv("GIT_WORK_TREE", "/caller")
t.Setenv("GIT_INDEX_FILE", "/caller/.git/index")
t.Setenv("git_common_dir", "/caller/.git") // Windows names are case-insensitive.
for _, item := range Environ() {
key, _, _ := strings.Cut(item, "=")
if slices.Contains([]string{"GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR"}, strings.ToUpper(key)) {
t.Fatalf("Environ() kept %s", item)
}
}
}
// Users pass credentials through GIT_CONFIG_COUNT, and install's token auth
// appends to it.
func TestEnvironKeepsConfigVariables(t *testing.T) {
t.Setenv("GIT_CONFIG_COUNT", "1")
t.Setenv("GIT_CONFIG_KEY_0", "http.proxy")
t.Setenv("GIT_CONFIG_VALUE_0", "http://proxy")
env := Environ()
for _, want := range []string{"GIT_CONFIG_COUNT=1", "GIT_CONFIG_KEY_0=http.proxy", "GIT_CONFIG_VALUE_0=http://proxy"} {
if !slices.Contains(env, want) {
t.Errorf("Environ() dropped %s", want)
}
}
}
// rawGitAllowed lists the only places that may start git with os/exec.
var rawGitAllowed = map[string]string{
"internal/gitenv/": "the wrapper itself",
"internal/hooks/": "gitcmd.go builds its own sanitized environment",
"internal/testutil/": "test fixtures",
}
// A git command started with os/exec inherits a hook's GIT_DIR and runs
// against the hook's repository (#852), so skillshare's own git goes through
// Command. The check is syntactic: it finds exec.Command and
// exec.CommandContext calls whose program is the literal "git".
func TestNoRawGitCommands(t *testing.T) {
root := filepath.Join("..", "..")
fset := token.NewFileSet()
for _, dir := range []string{"cmd", "internal"} {
err := filepath.WalkDir(filepath.Join(root, dir), func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
if d.Name() == "testdata" || d.Name() == "node_modules" {
return filepath.SkipDir
}
return nil
}
if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
rel, err := filepath.Rel(root, path)
if err != nil {
return err
}
rel = filepath.ToSlash(rel)
for prefix := range rawGitAllowed {
if strings.HasPrefix(rel, prefix) {
return nil
}
}
file, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
if err != nil {
return err
}
for _, pos := range rawGitCalls(file) {
t.Errorf("%s:%d runs git with os/exec; use gitenv.Command", rel, fset.Position(pos).Line)
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
}
// rawGitCalls follows the file's import of os/exec, so an aliased import counts.
func rawGitCalls(file *ast.File) []token.Pos {
execName := ""
for _, imp := range file.Imports {
if p, _ := strconv.Unquote(imp.Path.Value); p == "os/exec" {
execName = "exec"
if imp.Name != nil {
execName = imp.Name.Name
}
}
}
if execName == "" {
return nil
}
var out []token.Pos
ast.Inspect(file, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
if pkg, ok := sel.X.(*ast.Ident); !ok || pkg.Name != execName {
return true
}
prog := 0
switch sel.Sel.Name {
case "Command":
case "CommandContext":
prog = 1
default:
return true
}
if len(call.Args) > prog {
if lit, ok := call.Args[prog].(*ast.BasicLit); ok && lit.Value == `"git"` {
out = append(out, call.Pos())
}
}
return true
})
return out
}