package main import ( "bytes" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/json" "encoding/pem" "errors" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "git.unkin.net/unkin/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) { 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) } }