cli/pkg/cmd/factory/http.go
Mislav Marohnić 33fd6b1149 Change API authentication to allow asset downloads
We install an HTTP middleware that adds the "Authorization" header on
every HTTP request. However, our asset download process might redirect
to a 3rd-party host (Amazon S3) and we want to allow those requests but
not require that they are authenticated.

Furthermore, we need the ability to specify the `Accept` request header
without it being overwritten by middleware, so now middleware only adds
headers that are not present in a request.
2020-08-21 18:00:52 +02:00

55 lines
1.5 KiB
Go

package factory
import (
"fmt"
"net/http"
"os"
"strings"
"github.com/cli/cli/api"
"github.com/cli/cli/internal/config"
"github.com/cli/cli/internal/ghinstance"
"github.com/cli/cli/pkg/iostreams"
)
// generic authenticated HTTP client for commands
func httpClient(io *iostreams.IOStreams, cfg config.Config, appVersion string, setAccept bool) *http.Client {
var opts []api.ClientOption
if verbose := os.Getenv("DEBUG"); verbose != "" {
logTraffic := strings.Contains(verbose, "api")
opts = append(opts, api.VerboseLog(io.ErrOut, logTraffic, io.IsStderrTTY()))
}
opts = append(opts,
api.AddHeader("User-Agent", fmt.Sprintf("GitHub CLI %s", appVersion)),
api.AddHeaderFunc("Authorization", func(req *http.Request) (string, error) {
if token := os.Getenv("GITHUB_TOKEN"); token != "" {
return fmt.Sprintf("token %s", token), nil
}
hostname := ghinstance.NormalizeHostname(req.URL.Hostname())
token, err := cfg.Get(hostname, "oauth_token")
if err != nil || token == "" {
return "", nil
}
return fmt.Sprintf("token %s", token), nil
}),
)
if setAccept {
opts = append(opts,
api.AddHeaderFunc("Accept", func(req *http.Request) (string, error) {
// antiope-preview: Checks
accept := "application/vnd.github.antiope-preview+json"
if ghinstance.IsEnterprise(req.URL.Hostname()) {
// shadow-cat-preview: Draft pull requests
accept += ", application/vnd.github.shadow-cat-preview"
}
return accept, nil
}),
)
}
return api.NewHTTPClient(opts...)
}