package main import ( "bytes" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/json" "encoding/pem" "errors" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "testing" "github.com/IUCLabs/agent-tools/internal/agent" ) func TestCredentialGetHostFiltering(t *testing.T) { calls := 0 load := func() (*agent.GitHubApp, error) { calls++ return nil, errors.New("no vault in this test") } for _, in := range []string{ "protocol=https\nhost=git.unkin.net\n\n", "protocol=https\nhost=github.com.evil.example\n\n", "protocol=https\nhost=api.github.com\n\n", "protocol=https\n\n", "protocol=http\nhost=github.com\n\n", "host=github.com\n\n", } { var out bytes.Buffer if err := credentialGet(strings.NewReader(in), &out, load); err != nil || out.Len() != 0 { t.Errorf("%q: out=%q err=%v, want silent", in, out.String(), err) } } if calls != 0 { t.Errorf("loaded app creds %d times for foreign hosts", calls) } if err := credentialGet(strings.NewReader("protocol=https\nhost=github.com\n\n"), &bytes.Buffer{}, load); err == nil { t.Error("github.com request did not reach the loader") } } func TestCredentialStoreEraseAndUnknown(t *testing.T) { for args, wantErr := range map[string]bool{"store": false, "erase": false, "bogus": true} { cmd := newRootCmd() cmd.SetArgs([]string{"credential", args}) cmd.SetIn(strings.NewReader("host=github.com\npassword=x\n\n")) var out bytes.Buffer cmd.SetOut(&out) if err := cmd.Execute(); (err != nil) != wantErr || out.Len() != 0 { t.Errorf("%s: err=%v out=%q", args, err, out.String()) } } } // fakeStack wires a fake Vault holding both apps and a fake GitHub minting a // per-app token, so the full CLI path runs without network access. func fakeStack(t *testing.T) { t.Helper() key, _ := rsa.GenerateKey(rand.Reader, 2048) pemKey := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})) vault := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/v1/auth/approle/login" { _, _ = w.Write([]byte(`{"auth":{"client_token":"vt"}}`)) return } inst := map[string]string{"/v1/kv/data/service/github/iuclabs/coder": "1", "/v1/kv/data/service/github/iuclabs/reviewer": "2"}[r.URL.Path] if inst == "" { w.WriteHeader(http.StatusForbidden) return } _ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"data": map[string]any{ "app_id": "9", "installation_id": inst, "private_key": pemKey, }}}) })) gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.URL.Path == "/app": _, _ = w.Write([]byte(`{"slug":"iuclabs-coder"}`)) return case strings.HasPrefix(r.URL.Path, "/users/"): _, _ = w.Write([]byte(`{"id":42}`)) return } inst := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/app/installations/"), "/access_tokens") w.WriteHeader(http.StatusCreated) _, _ = w.Write([]byte(`{"token":"ghs_inst` + inst + `"}`)) })) t.Cleanup(vault.Close) t.Cleanup(gh.Close) t.Setenv("VAULT_ADDR", vault.URL) t.Setenv("GITHUB_API_URL", gh.URL) t.Setenv("AGENTGH_KV_PATH", "") } func run(t *testing.T, stdin string, args ...string) (string, error) { t.Helper() cmd := newRootCmd() cmd.SetArgs(args) cmd.SetIn(strings.NewReader(stdin)) var out bytes.Buffer cmd.SetOut(&out) cmd.SetErr(&out) err := cmd.Execute() return out.String(), err } func TestAppSelection(t *testing.T) { fakeStack(t) t.Setenv("AGENTGH_APP", "") if out, err := run(t, "", "token"); err != nil || out != "ghs_inst1\n" { t.Errorf("default app: %q %v", out, err) } if out, err := run(t, "", "--app", "reviewer", "token"); err != nil || out != "ghs_inst2\n" { t.Errorf("--app reviewer: %q %v", out, err) } t.Setenv("AGENTGH_APP", "reviewer") out, err := run(t, "protocol=https\nhost=github.com\n\n", "credential", "get") if err != nil || out != "username=x-access-token\npassword=ghs_inst2\n" { t.Errorf("AGENTGH_APP=reviewer credential: %q %v", out, err) } if out, err := run(t, "", "--app", "coder", "token"); err != nil || out != "ghs_inst1\n" { t.Errorf("--app beats AGENTGH_APP: %q %v", out, err) } if _, err := run(t, "", "--app", "nope", "token"); err == nil { t.Error("unknown app accepted") } } func fakeGH(t *testing.T, script string) string { t.Helper() dir := t.TempDir() if err := os.WriteFile(filepath.Join(dir, "gh"), []byte("#!/bin/sh\n"+script), 0o755); err != nil { t.Fatal(err) } t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) return dir } func TestRunGHPassesTokenInEnvOnly(t *testing.T) { dir := fakeGH(t, `printf '%s\n' "$@" > "$(dirname "$0")/argv"; echo "GH_TOKEN=$GH_TOKEN GITHUB_TOKEN=$GITHUB_TOKEN GH_HOST=$GH_HOST GH_ENTERPRISE_TOKEN=$GH_ENTERPRISE_TOKEN GITHUB_ENTERPRISE_TOKEN=$GITHUB_ENTERPRISE_TOKEN"; cat; exit 7`) for _, k := range []string{"GH_TOKEN", "GITHUB_TOKEN", "GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"} { t.Setenv(k, "stale") } t.Setenv("GH_HOST", "ghe.example") var out bytes.Buffer err := runGH([]string{"pr", "list", "--repo", "o/r"}, "ghs_secret", strings.NewReader("piped\n"), &out, &out) var code exitCode if !errors.As(err, &code) || code != 7 { t.Errorf("err = %v, want exit code 7", err) } if out.String() != "GH_TOKEN=ghs_secret GITHUB_TOKEN= GH_HOST=github.com GH_ENTERPRISE_TOKEN= GITHUB_ENTERPRISE_TOKEN=\npiped\n" { t.Errorf("child saw %q", out.String()) } argv, _ := os.ReadFile(filepath.Join(dir, "argv")) if string(argv) != "pr\nlist\n--repo\no/r\n" { t.Errorf("argv = %q", argv) } } func TestGHCommandPassesFlagsThroughWithApp(t *testing.T) { fakeStack(t) fakeGH(t, `echo "$GH_TOKEN $*"`) out, err := run(t, "", "--app", "reviewer", "gh", "api", "--paginate", "/user") if err != nil || out != "ghs_inst2 api --paginate /user\n" { t.Errorf("out=%q err=%v", out, err) } } func TestRunGHSignalExitCode(t *testing.T) { fakeGH(t, `kill -TERM $$`) err := runGH(nil, "tok", strings.NewReader(""), &bytes.Buffer{}, &bytes.Buffer{}) var code exitCode if !errors.As(err, &code) || code != 128+15 { t.Errorf("err = %v, want exit code 143", err) } } func git(t *testing.T, dir string, args ...string) string { t.Helper() out, err := agent.Git(dir, args...) if err != nil { t.Fatal(err) } return out } // hijackedGlobal points git at a global config carrying the ways a user's // config steals github.com pushes: SSH pushInsteadOf and a URL-scoped helper. func hijackedGlobal(t *testing.T, extra string) { t.Helper() cfg := filepath.Join(t.TempDir(), "gitconfig") body := "[url \"git@github.com:\"]\n\tpushInsteadOf = https://github.com/\n" + "[credential \"https://github.com\"]\n\thelper = \"!f() { echo username=neoloc; echo password=hijack; }; f\"\n" + "[credential]\n\thelper = \"!f() { echo username=generic; echo password=hijack; }; f\"\n" + extra if err := os.WriteFile(cfg, []byte(body), 0o644); err != nil { t.Fatal(err) } t.Setenv("GIT_CONFIG_GLOBAL", cfg) t.Setenv("GIT_CONFIG_NOSYSTEM", "1") } func TestConfigureBeatsGlobalHijacks(t *testing.T) { hijackedGlobal(t, "[url \"git@github.com:\"]\n\tinsteadOf = https://github.com/\n") dir := t.TempDir() git(t, dir, "init", "-q") git(t, dir, "remote", "add", "origin", "https://github.com/o/r.git") if got := git(t, dir, "remote", "get-url", "origin"); got != "git@github.com:o/r.git" { t.Fatalf("precondition: insteadOf not active, url %q", got) } helper := filepath.Join(t.TempDir(), "helper") if err := os.WriteFile(helper, []byte("#!/bin/sh\necho username=x-access-token\necho password=app\n"), 0o755); err != nil { t.Fatal(err) } for range 2 { if err := configure(dir, helper, "iuclabs-coder[bot]", "42+iuclabs-coder[bot]@users.noreply.github.com"); err != nil { t.Fatal(err) } } for _, args := range [][]string{{"remote", "get-url", "origin"}, {"remote", "get-url", "--push", "origin"}} { if got := git(t, dir, args...); got != "https://github.com/o/r.git" { t.Errorf("%v = %q", args, got) } } c := exec.Command("git", "credential", "fill") c.Dir = dir c.Stdin = strings.NewReader("protocol=https\nhost=github.com\n\n") out, err := c.Output() if err != nil || !strings.Contains(string(out), "username=x-access-token\npassword=app\n") { t.Errorf("credential fill = %q %v", out, err) } if got := git(t, dir, "config", "user.email"); got != "42+iuclabs-coder[bot]@users.noreply.github.com" { t.Errorf("user.email = %q", got) } } func TestConfigureRejectsNonRepo(t *testing.T) { hijackedGlobal(t, "") t.Setenv("GIT_CEILING_DIRECTORIES", os.TempDir()) if err := configure(t.TempDir(), "h", "n", "e"); err == nil || !strings.Contains(err.Error(), "not a git repository") { t.Errorf("err = %v", err) } } func TestCredentialHelper(t *testing.T) { exe, _ := os.Executable() t.Setenv("PATH", t.TempDir()) if got, _ := credentialHelper("it's"); got != "!"+shellQuote(exe)+` --app 'it'\''s' credential` { t.Errorf("off PATH: %q", got) } dir := t.TempDir() if err := os.Symlink(exe, filepath.Join(dir, "agentgh")); err != nil { t.Fatal(err) } t.Setenv("PATH", dir) if got, _ := credentialHelper("coder"); got != "!agentgh --app 'coder' credential" { t.Errorf("on PATH: %q", got) } out, err := exec.Command("/bin/sh", "-c", "printf %s "+shellQuote("a b'c\"$d")).Output() if err != nil || string(out) != "a b'c\"$d" { t.Errorf("shellQuote round-trip = %q %v", out, err) } } func TestConfigureRejectsNonHTTPSOrigin(t *testing.T) { hijackedGlobal(t, "") dir := t.TempDir() git(t, dir, "init", "-q") git(t, dir, "remote", "add", "origin", "git@github.com:o/r.git") if err := configure(dir, "h", "n", "e"); err == nil { t.Error("ssh origin accepted") } } func TestCloneCommand(t *testing.T) { fakeStack(t) src := t.TempDir() git(t, src, "init", "-q", "-b", "main") git(t, src, "-c", "user.name=x", "-c", "user.email=x@x", "commit", "-q", "--allow-empty", "-m", "init") git(t, src, "branch", "feat") hijackedGlobal(t, "[url \""+src+"\"]\n\tinsteadOf = https://github.com/o/r.git\n[url \"git@github.com:\"]\n\tinsteadOf = https://github.com/\n") dst := filepath.Join(t.TempDir(), "r") out, err := run(t, "", "--app", "reviewer", "clone", "o/r", dst, "--branch", "feat") if err != nil || !strings.Contains(out, "pushing as iuclabs-coder[bot]") { t.Fatalf("clone: %q %v", out, err) } if got := git(t, dst, "rev-parse", "--abbrev-ref", "HEAD"); got != "feat" { t.Errorf("branch = %q", got) } if got := git(t, dst, "config", "remote.origin.pushurl"); got != "https://github.com/o/r.git" { t.Errorf("pushurl = %q", got) } exe, _ := os.Executable() got := git(t, dst, "config", "--local", "--get-all", "--null", helperKey) if got != "\x00!"+shellQuote(exe)+" --app 'reviewer' credential\x00" { t.Errorf("helper chain = %q", got) } if _, err := run(t, "", "clone", "not-a-repo"); err == nil { t.Error("bad repo accepted") } }