Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
fix(github): switch back to fetching access token through apiClient, (#5380)
meredith59e3b04e820c
diff --git a/pkg/sources/github/connector_app.go b/pkg/sources/github/connector_app.goindex 85deddcf2..0739d4c9a 100644--- a/pkg/sources/github/connector_app.go+++ b/pkg/sources/github/connector_app.go@@ -7,6 +7,7 @@ import ("strconv""strings""sync"+ "time""github.com/bradleyfalzon/ghinstallation/v2"gogit "github.com/go-git/go-git/v5"@@ -40,7 +41,15 @@ type appConnector struct {type appInstallationClients struct {apiClient *github.ClientgraphqlClient *githubv4.Client- transport *ghinstallation.Transport+ tokenMu sync.RWMutex+ token *github.InstallationToken+}++func (cs *appInstallationClients) accessTokenIfValid() *github.InstallationToken {+ if cs.token == nil || cs.token.GetExpiresAt().Before(time.Now()) {+ return nil+ }+ return cs.token}var _ Connector = (*appConnector)(nil)@@ -155,17 +164,57 @@ func (c *appConnector) Clone(ctx context.Context, repoURL string, args ...stringreturn "", nil, fmt.Errorf("no GitHub App installation resolved for repo %q; set githubApp.installationId to a fallback installation to scan repos outside installation listings (e.g. member repos with scanUsers) together with scanAllInstallations", repoURL)}+ token, err := c.accessTokenForInstallation(ctx, installID)+ if err != nil {+ return "", nil, err+ }++ return git.CloneRepoUsingToken(ctx, token, repoURL, "", "x-access-token", true, args...)+}++// accessTokenForInstallation returns an installation access token.+func (c *appConnector) accessTokenForInstallation(ctx context.Context, installID int64) (string, error) {+ if installID == 0 {+ return "", fmt.Errorf("tried to fetch installation access token for id 0")+ }+clients, err := c.clientsForInstallation(installID)if err != nil {- return "", nil, fmt.Errorf("could not prepare github clients for installation %d: %w", installID, err)+ return "", err+ }++ clients.tokenMu.RLock()+ token := clients.accessTokenIfValid()+ clients.tokenMu.RUnlock()++ if token != nil {+ return token.GetToken(), nil}- token, err := clients.transport.Token(ctx)+ clients.tokenMu.Lock()+ defer clients.tokenMu.Unlock()++ if token := clients.accessTokenIfValid(); token != nil {+ return token.GetToken(), nil+ }++ token, _, err = c.installationClient.Apps.CreateInstallationToken(+ ctx,+ installID,+ &github.InstallationTokenOptions{},+ )if err != nil {- return "", nil, fmt.Errorf("could not create installation token for installation %d: %w", installID, err)+ return "", fmt.Errorf("could not create installation token for installation %d: %w", installID, err)}- return git.CloneRepoUsingToken(ctx, token, repoURL, "", "x-access-token", true, args...)+ if exp := token.GetExpiresAt(); !exp.IsZero() {+ // Refresh just before the real expiry+ token.ExpiresAt = &github.Timestamp{Time: exp.Add(-time.Minute)}+ }++ clients.token = token++ return token.GetToken(), nil}// installationIDForRepo returns the mapped installation ID for repoURL. When no@@ -325,7 +374,6 @@ func (c *appConnector) createAPIClientsForInstallation(installationID int64) (*areturn &appInstallationClients{apiClient: apiClient,graphqlClient: gqlClient,- transport: transport,}, nil}diff --git a/pkg/sources/github/connector_app_test.go b/pkg/sources/github/connector_app_test.goindex c67d609fa..2d5898395 100644--- a/pkg/sources/github/connector_app_test.go+++ b/pkg/sources/github/connector_app_test.go@@ -10,7 +10,9 @@ import ("net/http/httptest""strings""sync"+ "sync/atomic""testing"+ "time""github.com/google/go-github/v67/github""github.com/shurcooL/githubv4"@@ -243,6 +245,171 @@ func TestCloneErrorsWithoutResolvedInstallation(t *testing.T) {assert.Contains(t, err.Error(), "no GitHub App installation resolved")}+func TestAccessTokenForInstallation(t *testing.T) {+ privKey := generateTestPrivateKey(t)++ accessTokenServer := func(accessTokenHandler func(w http.ResponseWriter, r *http.Request)) *httptest.Server {+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")++ if r.Method == "POST" && strings.Contains(r.URL.Path, "access_tokens") {+ accessTokenHandler(w, r)+ return+ }++ // Default: return empty JSON array for any list endpoint.+ _ = json.NewEncoder(w).Encode([]interface{}{})+ }))+ }++ t.Run("invalid", func(t *testing.T) {+ _, err := (&appConnector{}).accessTokenForInstallation(trContext.Background(), 0)+ require.Error(t, err)+ })++ t.Run("success", func(t *testing.T) {+ server := accessTokenServer(func(w http.ResponseWriter, r *http.Request) {+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "token": "test-token",+ "expires_at": "2099-01-01T00:00:00Z",+ })+ })+ defer server.Close()++ c, err := NewAppConnector(+ server.URL,+ &credentialspb.GitHubApp{PrivateKey: string(privKey), AppId: "12345", InstallationId: "100"},+ false,+ )+ require.NoError(t, err)+ ac := c.(*appConnector)++ _, err = ac.accessTokenForInstallation(trContext.Background(), 100)+ require.NoError(t, err)+ })++ t.Run("rate limit", func(t *testing.T) {+ server := accessTokenServer(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Add("X-RateLimit-Remaining", "0")+ w.WriteHeader(http.StatusForbidden)++ _ = json.NewEncoder(w).Encode(map[string]interface{}{})+ })+ defer server.Close()++ c, err := NewAppConnector(+ server.URL,+ &credentialspb.GitHubApp{PrivateKey: string(privKey), AppId: "12345", InstallationId: "100"},+ false,+ )+ require.NoError(t, err)+ ac := c.(*appConnector)++ _, err = ac.accessTokenForInstallation(trContext.Background(), 100)+ require.Error(t, err)++ var gherr *github.RateLimitError+ require.ErrorAs(t, err, &gherr)+ })++ t.Run("not found / no installation", func(t *testing.T) {+ server := accessTokenServer(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusNotFound)++ _ = json.NewEncoder(w).Encode(map[string]interface{}{})+ })+ defer server.Close()++ c, err := NewAppConnector(+ server.URL,+ &credentialspb.GitHubApp{PrivateKey: string(privKey), AppId: "12345", InstallationId: "100"},+ false,+ )+ require.NoError(t, err)+ ac := c.(*appConnector)++ _, err = ac.accessTokenForInstallation(trContext.Background(), 100)+ require.Error(t, err)+ })++ t.Run("reuse", func(t *testing.T) {+ var hits atomic.Int64++ server := accessTokenServer(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "token": "test-token",+ "expires_at": "2099-01-01T00:00:00Z",+ })+ })+ defer server.Close()++ c, err := NewAppConnector(+ server.URL,+ &credentialspb.GitHubApp{PrivateKey: string(privKey), AppId: "12345", InstallationId: "100"},+ false,+ )+ require.NoError(t, err)+ ac := c.(*appConnector)++ _, err = ac.accessTokenForInstallation(trContext.Background(), 100)+ require.NoError(t, err)++ _, err = ac.accessTokenForInstallation(trContext.Background(), 100)+ require.NoError(t, err)++ require.Equal(t, int64(1), hits.Load())+ })++ t.Run("expire", func(t *testing.T) {+ var hits atomic.Int64+ server := accessTokenServer(func(w http.ResponseWriter, r *http.Request) {+ hits.Add(1)+ _ = json.NewEncoder(w).Encode(map[string]interface{}{+ "token": "test-token",+ "expires_at": "2099-01-01T00:00:00Z",+ })+ })+ defer server.Close()++ c, err := NewAppConnector(+ server.URL,+ &credentialspb.GitHubApp{PrivateKey: string(privKey), AppId: "12345", InstallationId: "100"},+ false,+ )+ require.NoError(t, err)+ ac := c.(*appConnector)++ _, err = ac.accessTokenForInstallation(trContext.Background(), 100)+ require.NoError(t, err)++ cs, err := ac.clientsForInstallation(100)+ require.NoError(t, err)+ token := cs.accessTokenIfValid()+ require.NotNil(t, token)++ token.ExpiresAt = &github.Timestamp{Time: time.Now()}++ token = cs.accessTokenIfValid()+ require.Nil(t, token)++ // race these for good measure+ var wg sync.WaitGroup+ for range 3 {+ wg.Go(func() {+ _, err := ac.accessTokenForInstallation(trContext.Background(), 100)+ require.NoError(t, err)+ })+ }+ wg.Wait()++ token = cs.accessTokenIfValid()+ require.NotNil(t, token)++ require.Equal(t, int64(2), hits.Load())+ })+}+func TestAPIClientForInstallationUsesConfiguredClient(t *testing.T) {defaultClient := github.NewClient(nil)connector := &appConnector{