Skip to content

oauth2: handle nil headers in Transport.RoundTrip #779

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
}

req2 := req.Clone(req.Context())
if req2.Header == nil {
req2.Header = make(http.Header)
}
token.SetAuthHeader(req2)

// req.Body is assumed to be closed by the base RoundTripper.
Expand Down
49 changes: 49 additions & 0 deletions transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
)
Expand Down Expand Up @@ -154,3 +155,51 @@ func TestExpiredWithExpiry(t *testing.T) {
func newMockServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(handler))
}

// TestTransportWithNilHeader tests that the Transport.RoundTrip method
// correctly handles requests with nil Headers.
func TestTransportWithNilHeader(t *testing.T) {
// Create a mock token source that returns a fixed token
tokenSource := StaticTokenSource(&Token{
AccessToken: "test-access-token",
TokenType: "Bearer",
})

// Create a mock http server to verify the request
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check that the Authorization header was correctly set
authHeader := r.Header.Get("Authorization")
expectedHeader := "Bearer test-access-token"
if authHeader != expectedHeader {
t.Errorf("expected authorization header %q, got %q", expectedHeader, authHeader)
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()

// Create Transport with our token source
transport := &Transport{
Source: tokenSource,
Base: http.DefaultTransport,
}

// Create a request with nil Header
reqURL, _ := url.Parse(server.URL)
req := &http.Request{
Method: "GET",
URL: reqURL,
// Header is intentionally nil
}

// Make the request using our Transport
resp, err := transport.RoundTrip(req)
if err != nil {
t.Fatalf("roundTrip failed with nil Header: %v", err)
}
defer resp.Body.Close()

// Verify response status
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status code %d, got %d", http.StatusOK, resp.StatusCode)
}
}