package gitea import ( "context" "encoding/json" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "strings" "sync/atomic" "testing" "time" ) func TestBuildAuthorizeURL(t *testing.T) { uStr := BuildAuthorizeURL( "https://git.site.latha.org", "cid-123", "https://deploy.site.latha.org/oauth/callback", "st-456", "chal-789", ) u, err := url.Parse(uStr) if err != nil { t.Fatalf("parse url: %v", err) } if u.Path != "/login/oauth/authorize" { t.Fatalf("unexpected path: %s", u.Path) } q := u.Query() if q.Get("client_id") != "cid-123" || q.Get("redirect_uri") != "https://deploy.site.latha.org/oauth/callback" || q.Get("response_type") != "code" || q.Get("state") != "st-456" || q.Get("code_challenge") != "chal-789" || q.Get("code_challenge_method") != "S256" { t.Fatalf("unexpected query params: %v", q) } } func TestPollRelayAndExchangeCode(t *testing.T) { var polls atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/api/oauth/poll": if r.URL.Query().Get("state") != "st-1" { w.WriteHeader(http.StatusBadRequest) return } n := polls.Add(1) w.Header().Set("Content-Type", "application/json") if n < 2 { w.WriteHeader(http.StatusAccepted) _ = json.NewEncoder(w).Encode(map[string]string{"status": "pending"}) return } w.WriteHeader(http.StatusOK) _ = json.NewEncoder(w).Encode(map[string]string{"status": "ready", "code": "code-abc"}) case "/login/oauth/access_token": if err := r.ParseForm(); err != nil { w.WriteHeader(http.StatusBadRequest) return } if r.Form.Get("grant_type") != "authorization_code" || r.Form.Get("client_id") != "cid-1" || r.Form.Get("code") != "code-abc" || r.Form.Get("code_verifier") != "ver-xyz" { w.WriteHeader(http.StatusBadRequest) _ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_request"}) return } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(TokenResponse{ AccessToken: "tok-999", TokenType: "bearer", ExpiresIn: 3600, }) default: w.WriteHeader(http.StatusNotFound) } })) defer srv.Close() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() code, err := PollRelay(ctx, srv.Client(), srv.URL, "st-1", 10*time.Millisecond) if err != nil { t.Fatalf("PollRelay: %v", err) } if code != "code-abc" { t.Fatalf("code = %q, want %q", code, "code-abc") } tok, err := ExchangeCode(ctx, srv.Client(), srv.URL, "cid-1", RedirectURI(srv.URL), code, "ver-xyz") if err != nil { t.Fatalf("ExchangeCode: %v", err) } if tok.AccessToken != "tok-999" { t.Fatalf("AccessToken = %q, want %q", tok.AccessToken, "tok-999") } } func TestFindGTBinary(t *testing.T) { if got, err := FindGTBinary("/custom/gt"); err != nil || got != "/custom/gt" { t.Fatalf("override = (%q, %v), want (/custom/gt, nil)", got, err) } tmp := t.TempDir() binDir := filepath.Join(tmp, "bin") if err := os.MkdirAll(binDir, 0o755); err != nil { t.Fatal(err) } gtPath := filepath.Join(binDir, "gt") if err := os.WriteFile(gtPath, []byte("#!/bin/sh\n"), 0o755); err != nil { t.Fatal(err) } t.Setenv("PATH", binDir) t.Setenv("HOME", tmp) if got, err := FindGTBinary(""); err != nil || got != gtPath { t.Fatalf("PATH lookup = (%q, %v), want (%q, nil)", got, err, gtPath) } t.Setenv("PATH", filepath.Join(tmp, "empty")) localBin := filepath.Join(tmp, ".local", "bin") if err := os.MkdirAll(localBin, 0o755); err != nil { t.Fatal(err) } localGT := filepath.Join(localBin, "gt") if err := os.WriteFile(localGT, []byte("#!/bin/sh\n"), 0o755); err != nil { t.Fatal(err) } if got, err := FindGTBinary(""); err != nil || got != localGT { t.Fatalf("~/.local/bin fallback = (%q, %v), want (%q, nil)", got, err, localGT) } } func writeFakeGT(t *testing.T, logPath, scriptBody string) string { t.Helper() gtPath := filepath.Join(t.TempDir(), "gt") script := "#!/bin/sh\nset -eu\nLOG_FILE=" + logPath + "\n" + scriptBody if err := os.WriteFile(gtPath, []byte(script), 0o755); err != nil { t.Fatal(err) } return gtPath } func TestConfigureGTAndGit(t *testing.T) { t.Run("default auto succeeds with keyring", func(t *testing.T) { logPath := filepath.Join(t.TempDir(), "calls.log") gtPath := writeFakeGT(t, logPath, ` if [ "$1" = "auth" ] && [ "$2" = "login" ]; then token=$(cat) printf "login|%s|%s\n" "$*" "$token" >> "$LOG_FILE" exit 0 fi if [ "$1" = "auth" ] && [ "$2" = "setup-git" ]; then printf "setup-git|%s\n" "$*" >> "$LOG_FILE" exit 0 fi exit 1 `) if err := ConfigureGTAndGit(context.Background(), gtPath, "https://git.site.latha.org/", "secret-tok", "auto"); err != nil { t.Fatalf("ConfigureGTAndGit: %v", err) } got, err := os.ReadFile(logPath) if err != nil { t.Fatal(err) } want := "login|auth login --host https://git.site.latha.org --with-token --yes --no-input|secret-tok\n" + "setup-git|auth setup-git --host https://git.site.latha.org --no-input\n" if string(got) != want { t.Fatalf("calls:\n%s\nwant:\n%s", got, want) } }) t.Run("auto falls back to file store when keyring unavailable", func(t *testing.T) { logPath := filepath.Join(t.TempDir(), "calls.log") gtPath := writeFakeGT(t, logPath, ` if [ "$1" = "auth" ] && [ "$2" = "login" ]; then token=$(cat) printf "login|%s|%s\n" "$*" "$token" >> "$LOG_FILE" case "$*" in *"--credential-store file"*) exit 0 ;; *) echo "error: secure credential storage unavailable; use --credential-store file" >&2; exit 1 ;; esac fi if [ "$1" = "auth" ] && [ "$2" = "setup-git" ]; then printf "setup-git|%s\n" "$*" >> "$LOG_FILE" exit 0 fi exit 1 `) if err := ConfigureGTAndGit(context.Background(), gtPath, "https://git.site.latha.org", "secret-tok", ""); err != nil { t.Fatalf("ConfigureGTAndGit fallback: %v", err) } got, err := os.ReadFile(logPath) if err != nil { t.Fatal(err) } want := "login|auth login --host https://git.site.latha.org --with-token --yes --no-input|secret-tok\n" + "login|auth login --host https://git.site.latha.org --with-token --yes --no-input --credential-store file|secret-tok\n" + "setup-git|auth setup-git --host https://git.site.latha.org --no-input\n" if string(got) != want { t.Fatalf("calls:\n%s\nwant:\n%s", got, want) } }) t.Run("explicit keyring does not fall back to file", func(t *testing.T) { logPath := filepath.Join(t.TempDir(), "calls.log") gtPath := writeFakeGT(t, logPath, ` echo "error: secure credential storage unavailable" >&2 exit 1 `) err := ConfigureGTAndGit(context.Background(), gtPath, "https://git.site.latha.org", "secret-tok", "keyring") if err == nil || !strings.Contains(err.Error(), "gt auth login failed") { t.Fatalf("unexpected err: %v", err) } }) t.Run("invalid credential store", func(t *testing.T) { err := ConfigureGTAndGit(context.Background(), "/nonexistent/gt", "https://git.site.latha.org", "secret-tok", "bogus") if err == nil || !strings.Contains(err.Error(), "invalid credential store") { t.Fatalf("unexpected err: %v", err) } }) }