Find, verify, and analyze leaked credentials
Go credentialsdevsecopsdynamic-analysisprecommitscanningsecretsecret-managementsecretssecuritysecurity-toolstrufflehogverification
Improve Github App installation access token caching (#5324)
mereditha8d284506b79
diff --git a/pkg/sources/github/connector.go b/pkg/sources/github/connector.goindex bd4932511..9e99e4e1f 100644--- a/pkg/sources/github/connector.go+++ b/pkg/sources/github/connector.go@@ -117,7 +117,7 @@ func newConnector(ctx context.Context, source *Source) (Connector, error) {switch cred := source.conn.GetCredential().(type) {case *sourcespb.GitHub_GithubApp:log.RedactGlobally(cred.GithubApp.GetPrivateKey())- return NewAppConnector(ctx, apiEndpoint, cred.GithubApp, source.conn.GetScanAllInstallations())+ return NewAppConnector(apiEndpoint, cred.GithubApp, source.conn.GetScanAllInstallations())case *sourcespb.GitHub_BasicAuth:log.RedactGlobally(cred.BasicAuth.GetPassword())return NewBasicAuthConnector(ctx, apiEndpoint, source.conn.GetClonePath(), cred.BasicAuth)diff --git a/pkg/sources/github/connector_app.go b/pkg/sources/github/connector_app.goindex 4d3c34678..85deddcf2 100644--- a/pkg/sources/github/connector_app.go+++ b/pkg/sources/github/connector_app.go@@ -3,6 +3,7 @@ package githubimport ("fmt""net/http"+ "net/url""strconv""strings""sync"@@ -39,21 +40,25 @@ type appConnector struct {type appInstallationClients struct {apiClient *github.ClientgraphqlClient *githubv4.Client+ transport *ghinstallation.Transport}var _ Connector = (*appConnector)(nil)const githubHTTPTimeoutSeconds = 60-func NewAppConnector(ctx context.Context, apiEndpoint string, app *credentialspb.GitHubApp, scanAllInstallations bool) (Connector, error) {+func NewAppConnector(apiEndpoint string, app *credentialspb.GitHubApp, scanAllInstallations bool) (Connector, error) {var installationID int64+ var err error+if app.InstallationId != "" {- var err errorinstallationID, err = strconv.ParseInt(app.InstallationId, 10, 64)if err != nil {return nil, fmt.Errorf("could not parse app installation ID %q: %w", app.InstallationId, err)}- } else if !scanAllInstallations {+ }++ if installationID == 0 && !scanAllInstallations {return nil, fmt.Errorf("githubApp.installationId is required unless scanAllInstallations is set")}@@ -85,13 +90,10 @@ func NewAppConnector(ctx context.Context, apiEndpoint string, app *credentialspb// possible with scanAllInstallations), installations are discovered and// clients created lazily per-repo, so there is no default client to// validate up front.- if installationID != 0 {- if _, err := connector.APIClientForInstallation(installationID); err != nil {- return nil, fmt.Errorf("could not create API client for configured installation: %w", err)- }-- if _, err := connector.graphqlClientForInstallation(ctx, installationID); err != nil {- return nil, fmt.Errorf("error creating GraphQL client: %w", err)+ if connector.HasDefaultInstallation() {+ _, err := connector.clientsForInstallation(installationID)+ if err != nil {+ return nil, fmt.Errorf("could not create clients for configured installation: %w", err)}}@@ -129,39 +131,16 @@ func (c *appConnector) APIClientForRepo(repoURL string) (*github.Client, error)func (c *appConnector) GraphQLClientForRepo(ctx context.Context, repoURL string) (*githubv4.Client, error) {installID, _ := c.installationIDForRepo(repoURL)- return c.graphqlClientForInstallation(ctx, installID)+ return c.graphqlClientForInstallation(installID)}-func (c *appConnector) graphqlClientForInstallation(ctx context.Context, installID int64) (*githubv4.Client, error) {- c.mu.RLock()- if clients := c.clientsByInstallationID[installID]; clients != nil && clients.graphqlClient != nil {- client := clients.graphqlClient- c.mu.RUnlock()- return client, nil- }- c.mu.RUnlock()-- apiClient, err := c.APIClientForInstallation(installID)- if err != nil {- return nil, err- }- client, err := createGraphqlClient(ctx, apiClient.Client(), c.apiEndpoint)+func (c *appConnector) graphqlClientForInstallation(installID int64) (*githubv4.Client, error) {+ clients, err := c.clientsForInstallation(installID)if err != nil {return nil, err}- c.mu.Lock()- defer c.mu.Unlock()-- clients := c.clientsForInstallationLocked(installID)- if clients.graphqlClient != nil {- return clients.graphqlClient, nil- }- if clients.apiClient == nil {- clients.apiClient = apiClient- }- clients.graphqlClient = client- return client, nil+ return clients.graphqlClient, nil}func (c *appConnector) Clone(ctx context.Context, repoURL string, args ...string) (string, *gogit.Repository, error) {@@ -176,20 +155,25 @@ 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)}- // TODO: Check rate limit for this call.- token, _, err := c.installationClient.Apps.CreateInstallationToken(- ctx,- installID,- &github.InstallationTokenOptions{})+ clients, err := c.clientsForInstallation(installID)+ if err != nil {+ return "", nil, fmt.Errorf("could not prepare github clients for installation %d: %w", installID, err)+ }++ token, err := clients.transport.Token(ctx)if err != nil {return "", nil, fmt.Errorf("could not create installation token for installation %d: %w", installID, err)}- return git.CloneRepoUsingToken(ctx, token.GetToken(), repoURL, "", "x-access-token", true, args...)+ return git.CloneRepoUsingToken(ctx, token, repoURL, "", "x-access-token", true, args...)}// installationIDForRepo returns the mapped installation ID for repoURL. When no// mapping exists, it falls back to the configured installation and returns false.+//+// Note: Because ensureRepoInstallation also stores values in this map with+// c.installationID, the second return value here is NOT indicative of using+// the fallback.func (c *appConnector) installationIDForRepo(repoURL string) (int64, bool) {c.mu.RLock()defer c.mu.RUnlock()@@ -255,7 +239,7 @@ func (c *appConnector) setRepoInstallationForWiki(repoURL string, installationID// installation, lazily creating it if needed. See APIClient for why this// cannot simply return nil when no default installation is configured.func (c *appConnector) GraphQLClient() *githubv4.Client {- client, err := c.graphqlClientForInstallation(context.Background(), c.installationID)+ client, err := c.graphqlClientForInstallation(c.installationID)if err != nil {return nil}@@ -271,40 +255,52 @@ func (c *appConnector) InstallationClient() *github.Client {// orgs — each org's API calls must use that org's installation token to get// proper IP allowlist bypass and permission scoping.func (c *appConnector) APIClientForInstallation(installationID int64) (*github.Client, error) {- c.mu.RLock()- if clients := c.clientsByInstallationID[installationID]; clients != nil && clients.apiClient != nil {- client := clients.apiClient- c.mu.RUnlock()- return client, nil+ clients, err := c.clientsForInstallation(installationID)+ if err != nil {+ return nil, err}++ return clients.apiClient, nil+}++func (c *appConnector) clientsForInstallation(installationID int64) (*appInstallationClients, error) {+ c.mu.RLock()+ clients, ok := c.clientsByInstallationID[installationID]c.mu.RUnlock()+ if ok {+ return clients, nil+ }- client, err := c.createAPIClientForInstallation(installationID)+ clients, err := c.clientsForInstallationLocked(installationID)if err != nil {return nil, err}+ return clients, nil+}++func (c *appConnector) clientsForInstallationLocked(installationID int64) (*appInstallationClients, error) {c.mu.Lock()defer c.mu.Unlock()- clients := c.clientsForInstallationLocked(installationID)- if clients.apiClient != nil {- return clients.apiClient, nil+ if clients, ok := c.clientsByInstallationID[installationID]; ok {+ return clients, nil}- clients.apiClient = client- return client, nil-}-func (c *appConnector) clientsForInstallationLocked(installationID int64) *appInstallationClients {- clients := c.clientsByInstallationID[installationID]- if clients == nil {- clients = &appInstallationClients{}- c.clientsByInstallationID[installationID] = clients+ clients, err := c.createAPIClientsForInstallation(installationID)+ if err != nil {+ return nil, err}- return clients++ c.clientsByInstallationID[installationID] = clients++ return clients, nil}-func (c *appConnector) createAPIClientForInstallation(installationID int64) (*github.Client, error) {+// createAPIClientsForInstallation creates both types of clients at once and+// saves along with the transport in an appInstallationClients, so those+// structs are never in a partially-filled state.+func (c *appConnector) createAPIClientsForInstallation(installationID int64) (*appInstallationClients, error) {appsTransport, err := newAppsTransport(c.apiEndpoint, c.appID, c.appPrivateKey)if err != nil {return nil, fmt.Errorf("could not create app transport for installation %d: %w", installationID, err)@@ -315,11 +311,22 @@ func (c *appConnector) createAPIClientForInstallation(installationID int64) (*gi// with the raw endpoint here or GHE.com token refresh would 401.transport := ghinstallation.NewFromAppsTransport(appsTransport, installationID)- client, err := newGitHubClientWithTransport(c.apiEndpoint, transport)+ apiClient, err := newGitHubClientWithTransport(c.apiEndpoint, transport)if err != nil {return nil, fmt.Errorf("could not create API client for installation %d: %w", installationID, err)}- return client, nil++ // the only thing this uses context for is a level 2 log line...+ gqlClient, err := createGraphqlClient(context.Background(), apiClient.Client(), c.apiEndpoint)+ if err != nil {+ return nil, err+ }++ return &appInstallationClients{+ apiClient: apiClient,+ graphqlClient: gqlClient,+ transport: transport,+ }, nil}func newAppsTransport(apiEndpoint string, appID int64, privateKey []byte) (*ghinstallation.AppsTransport, error) {@@ -337,22 +344,42 @@ func newAppsTransport(apiEndpoint string, appID int64, privateKey []byte) (*ghinif err != nil {return nil, err}- appsTransport.BaseURL = baseURL+ appsTransport.BaseURL = strings.TrimRight(baseURL, "/")return appsTransport, nil}-// appsBaseURL returns the BaseURL that ghinstallation transports should use for-// token exchange/refresh. For GHE.com it resolves to the api.* subdomain with-// the trailing slash trimmed; for github.com and GHES it is the endpoint as-is.+// appsBaseURL returns the BaseURL that ghinstallation transports should use+// for token exchange/refresh. For GHE.com it resolves to the api.* subdomain;+// for what is likely GHES, it ensures /api/v3 is used; and for anything else+// including github.com it is the endpoint as-is.func appsBaseURL(apiEndpoint string) (string, error) {if isGHECloud(apiEndpoint) {normalizedURL, err := normalizeGHECloudAPIEndpoint(apiEndpoint)if err != nil {return "", fmt.Errorf("could not normalize GHE.com endpoint: %w", err)}- return strings.TrimRight(normalizedURL, "/"), nil+ return normalizedURL, nil+ }++ u, err := url.Parse(apiEndpoint)+ if err != nil {+ return "", fmt.Errorf("malformed endpoint url: %w", err)+ }+ h := u.Hostname()++ if !strings.HasSuffix(u.Path, "/") {+ u.Path += "/"+ }++ // If we're not dealing with github.com or GHE, then maybe GHES, which+ // needs /api/v3 for ghinstallation find the right place+ if !strings.HasPrefix(h, "api.") && !strings.Contains(h, ".api.") {+ if !strings.HasSuffix(u.Path, "/api/v3/") {+ u.Path += "api/v3/"+ }}- return apiEndpoint, nil++ return u.String(), nil}func newGitHubClientWithTransport(apiEndpoint string, transport http.RoundTripper) (*github.Client, error) {diff --git a/pkg/sources/github/connector_app_test.go b/pkg/sources/github/connector_app_test.goindex d0bd479d7..c67d609fa 100644--- a/pkg/sources/github/connector_app_test.go+++ b/pkg/sources/github/connector_app_test.go@@ -148,7 +148,7 @@ func TestNewAppConnectorDefaultAPIClientUsesConfiguredInstallation(t *testing.T)}))defer server.Close()- connector, err := NewAppConnector(trContext.Background(), server.URL, &credentialspb.GitHubApp{+ connector, err := NewAppConnector(server.URL, &credentialspb.GitHubApp{PrivateKey: string(privKey),InstallationId: "4242",AppId: "12345",@@ -184,7 +184,7 @@ func TestNewAppConnectorInstallationIDOptionalWithScanAllInstallations(t *testindefer server.Close()// scanAllInstallations=true with no installationId configured should succeed.- connector, err := NewAppConnector(trContext.Background(), server.URL, &credentialspb.GitHubApp{+ connector, err := NewAppConnector(server.URL, &credentialspb.GitHubApp{PrivateKey: string(privKey),AppId: "12345",}, true)@@ -192,7 +192,7 @@ func TestNewAppConnectorInstallationIDOptionalWithScanAllInstallations(t *testinrequire.NotNil(t, connector)// Without scanAllInstallations, installationId is still required.- _, err = NewAppConnector(trContext.Background(), server.URL, &credentialspb.GitHubApp{+ _, err = NewAppConnector(server.URL, &credentialspb.GitHubApp{PrivateKey: string(privKey),AppId: "12345",}, false)@@ -215,7 +215,7 @@ func TestAPIClientAndGraphQLClientNonNilWithoutDefaultInstallation(t *testing.T)}))defer server.Close()- connector, err := NewAppConnector(trContext.Background(), server.URL, &credentialspb.GitHubApp{+ connector, err := NewAppConnector(server.URL, &credentialspb.GitHubApp{PrivateKey: string(privKey),AppId: "12345",}, true)@@ -435,3 +435,25 @@ func TestAddMembersByOrgWithClient(t *testing.T) {assert.Contains(t, s.memberCache, "bob")assert.Contains(t, s.memberCache, "charlie")}++func TestAppsBaseURL(t *testing.T) {+ u, err := appsBaseURL("https://foo.ghe.com/")+ assert.NoError(t, err)+ assert.Equal(t, "https://api.foo.ghe.com/", u)++ u, err = appsBaseURL("https://ghes.intranet/")+ assert.NoError(t, err)+ assert.Equal(t, "https://ghes.intranet/api/v3/", u)++ u, err = appsBaseURL("https://ghes.intranet/api/v3/")+ assert.NoError(t, err)+ assert.Equal(t, "https://ghes.intranet/api/v3/", u)++ u, err = appsBaseURL("https://api.github.com")+ assert.NoError(t, err)+ assert.Equal(t, "https://api.github.com/", u)++ u, err = appsBaseURL("https://api.github.com/")+ assert.NoError(t, err)+ assert.Equal(t, "https://api.github.com/", u)+}diff --git a/pkg/sources/github/github_test.go b/pkg/sources/github/github_test.goindex 9a0d2e6ff..29911c078 100644--- a/pkg/sources/github/github_test.go+++ b/pkg/sources/github/github_test.go@@ -375,15 +375,11 @@ func TestAppConnector_EnterpriseBaseURL(t *testing.T) {privateKey := createPrivateKey()enterpriseEndpoint := "https://api.example.ghe.com"- connector, err := NewAppConnector(- context.Background(),- enterpriseEndpoint,- &credentialspb.GitHubApp{- PrivateKey: privateKey,- InstallationId: "1337",- AppId: "4141",- },- false)+ connector, err := NewAppConnector(enterpriseEndpoint, &credentialspb.GitHubApp{+ PrivateKey: privateKey,+ InstallationId: "1337",+ AppId: "4141",+ }, false)require.NoError(t, err)appConn, ok := connector.(*appConnector)diff --git a/pkg/sources/github/repo.go b/pkg/sources/github/repo.goindex 5ac878a8c..a74698a09 100644--- a/pkg/sources/github/repo.go+++ b/pkg/sources/github/repo.go@@ -55,9 +55,9 @@ type repoInfo struct {owner string // repository owner (user|organization).name string // repository name.fullName string // full repository name (owner/repo).- hasWiki bool // whether the repository is likely to have a wiki.size int // size of the repository in kilobytes.visibility source_metadatapb.Visibility // visibility of the repository (public/private).+ hasWiki bool // whether the repository is likely to have a wiki.}// cloneRepo clones a repository given its URL, returns the path and the repository object.