scorecard/roundtripper/roundtripper.go

66 lines
2.1 KiB
Go
Raw Normal View History

// Copyright 2020 Security Scorecard Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2020-10-09 17:47:59 +03:00
package roundtripper
import (
"context"
"log"
2020-10-09 17:47:59 +03:00
"net/http"
"os"
"strconv"
"strings"
2020-10-09 17:47:59 +03:00
"github.com/bradleyfalzon/ghinstallation"
2020-10-13 19:29:29 +03:00
"go.uber.org/zap"
"github.com/ossf/scorecard/clients/githubrepo"
2020-10-09 17:47:59 +03:00
)
const (
// GithubAuthToken is for making requests to GiHub's API.
GithubAuthToken = "GITHUB_AUTH_TOKEN" // #nosec G101
// GithubAppKeyPath is the path to file for GitHub App key.
GithubAppKeyPath = "GITHUB_APP_KEY_PATH"
// GithubAppID is the app ID for the GitHub App.
GithubAppID = "GITHUB_APP_ID"
// GithubAppInstallationID is the installation ID for the GitHub App.
GithubAppInstallationID = "GITHUB_APP_INSTALLATION_ID"
)
2020-10-09 17:47:59 +03:00
// NewTransport returns a configured http.Transport for use with GitHub.
2020-10-13 19:29:29 +03:00
func NewTransport(ctx context.Context, logger *zap.SugaredLogger) http.RoundTripper {
2020-10-09 17:47:59 +03:00
transport := http.DefaultTransport
if token := os.Getenv(GithubAuthToken); token != "" {
// Use GitHub PAT
transport = githubrepo.MakeGitHubTransport(transport, strings.Split(token, ","))
} else if keyPath := os.Getenv(GithubAppKeyPath); keyPath != "" { // Also try a GITHUB_APP
appID, err := strconv.Atoi(os.Getenv(GithubAppID))
if err != nil {
log.Panic(err)
}
installationID, err := strconv.Atoi(os.Getenv(GithubAppInstallationID))
if err != nil {
log.Panic(err)
}
transport, err = ghinstallation.NewKeyFromFile(transport, int64(appID), int64(installationID), keyPath)
if err != nil {
log.Panic(err)
}
2020-10-09 17:47:59 +03:00
}
return MakeRateLimitedTransport(transport, logger)
}