diff --git a/compute/metadata/metadata.go b/compute/metadata/metadata.go index 6b13424fd97..545bd9d379c 100644 --- a/compute/metadata/metadata.go +++ b/compute/metadata/metadata.go @@ -296,6 +296,7 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) { // being stable anyway. host = metadataIP } + suffix = strings.TrimLeft(suffix, "/") u := "http://" + host + "/computeMetadata/v1/" + suffix req, err := http.NewRequest("GET", u, nil) if err != nil { diff --git a/compute/metadata/metadata_test.go b/compute/metadata/metadata_test.go index 76eb7a66f79..f779c18b719 100644 --- a/compute/metadata/metadata_test.go +++ b/compute/metadata/metadata_test.go @@ -73,6 +73,42 @@ func TestGetFailsOnBadURL(t *testing.T) { } } +func TestGet_LeadingSlash(t *testing.T) { + want := "http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/identity?audience=http://example.com" + tests := []struct { + name string + suffix string + }{ + { + name: "without leading slash", + suffix: "instance/service-accounts/default/identity?audience=http://example.com", + }, + { + name: "with leading slash", + suffix: "/instance/service-accounts/default/identity?audience=http://example.com", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ct := &captureTransport{} + c := NewClient(&http.Client{Transport: ct}) + c.Get(tc.suffix) + if ct.url != want { + t.Fatalf("got %v, want %v", ct.url, want) + } + }) + } +} + +type captureTransport struct { + url string +} + +func (ct *captureTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ct.url = req.URL.String() + return &http.Response{Body: ioutil.NopCloser(bytes.NewReader(nil))}, nil +} + type userAgentTransport struct { userAgent string base http.RoundTripper