Skip to content

Commit

Permalink
Merge branch 'username-file-12576' of https://github.com/wasim-nihal/…
Browse files Browse the repository at this point in the history
…common into username-file-12576

Signed-off-by: Wasim Nihal <[email protected]>
  • Loading branch information
wasim-nihal committed Sep 2, 2023
2 parents 06c301c + 0af702d commit 707c0a9
Showing 1 changed file with 16 additions and 23 deletions.
39 changes: 16 additions & 23 deletions config/http_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -657,46 +657,39 @@ type basicAuthRoundTripper struct {

// NewBasicAuthRoundTripper will apply a BASIC auth authorization header to a request unless it has
// already been set.
func NewBasicAuthRoundTripper(username string, password Secret, passwordFile string, usernameFile string, rt http.RoundTripper) http.RoundTripper {
return &basicAuthRoundTripper{username, password, passwordFile, usernameFile, rt}
func NewBasicAuthRoundTripper(username string, password Secret, usernameFile, passwordFile string, rt http.RoundTripper) http.RoundTripper {
return &basicAuthRoundTripper{username, password, usernameFile, passwordFile, rt}
}

func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
var username string
var password string
if len(req.Header.Get("Authorization")) != 0 {
return rt.rt.RoundTrip(req)
}
username, err := getBasicAuthUsername(*rt)
if err != nil {
return nil, err
}
password, err := getBasicAuthPassword(*rt)
if err != nil {
return nil, err
}
req = cloneRequest(req)
req.SetBasicAuth(username, password)
return rt.rt.RoundTrip(req)
}
func getBasicAuthUsername(rt basicAuthRoundTripper) (string, error) {
if rt.usernameFile != "" {
usernameBytes, err := os.ReadFile(rt.usernameFile)
if err != nil {
return "", fmt.Errorf("unable to read basic auth password file %s: %s", rt.usernameFile, err)
return nil, fmt.Errorf("unable to read basic auth username file %s: %s", rt.usernameFile, err)
}
return strings.TrimSpace(string(usernameBytes)), nil
username = strings.TrimSpace(string(usernameBytes))
} else {
username = rt.username
}
return rt.username, nil
}
func getBasicAuthPassword(rt basicAuthRoundTripper) (string, error) {
if rt.passwordFile != "" {
passwordBytes, err := os.ReadFile(rt.passwordFile)
if err != nil {
return "", fmt.Errorf("unable to read basic auth password file %s: %s", rt.passwordFile, err)
return nil, fmt.Errorf("unable to read basic auth password file %s: %s", rt.passwordFile, err)
}
return strings.TrimSpace(string(passwordBytes)), nil
password = strings.TrimSpace(string(passwordBytes))
} else {
password = string(rt.password)
}
return string(rt.password), nil
req = cloneRequest(req)
req.SetBasicAuth(username, password)
return rt.rt.RoundTrip(req)
}

func (rt *basicAuthRoundTripper) CloseIdleConnections() {
if ci, ok := rt.rt.(closeIdler); ok {
ci.CloseIdleConnections()
Expand Down

0 comments on commit 707c0a9

Please sign in to comment.