Skip to content

Commit f0d605c

Browse files
authored
fix(compute/metadata): remove leading slash for Get suffix (#2760)
Updates #2750
1 parent 03d78b5 commit f0d605c

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

compute/metadata/metadata.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,7 @@ func (c *Client) getETag(suffix string) (value, etag string, err error) {
296296
// being stable anyway.
297297
host = metadataIP
298298
}
299+
suffix = strings.TrimLeft(suffix, "/")
299300
u := "http://" + host + "/computeMetadata/v1/" + suffix
300301
req, err := http.NewRequest("GET", u, nil)
301302
if err != nil {

compute/metadata/metadata_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,42 @@ func TestGetFailsOnBadURL(t *testing.T) {
7373
}
7474
}
7575

76+
func TestGet_LeadingSlash(t *testing.T) {
77+
want := "http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/identity?audience=http://example.com"
78+
tests := []struct {
79+
name string
80+
suffix string
81+
}{
82+
{
83+
name: "without leading slash",
84+
suffix: "instance/service-accounts/default/identity?audience=http://example.com",
85+
},
86+
{
87+
name: "with leading slash",
88+
suffix: "/instance/service-accounts/default/identity?audience=http://example.com",
89+
},
90+
}
91+
for _, tc := range tests {
92+
t.Run(tc.name, func(t *testing.T) {
93+
ct := &captureTransport{}
94+
c := NewClient(&http.Client{Transport: ct})
95+
c.Get(tc.suffix)
96+
if ct.url != want {
97+
t.Fatalf("got %v, want %v", ct.url, want)
98+
}
99+
})
100+
}
101+
}
102+
103+
type captureTransport struct {
104+
url string
105+
}
106+
107+
func (ct *captureTransport) RoundTrip(req *http.Request) (*http.Response, error) {
108+
ct.url = req.URL.String()
109+
return &http.Response{Body: ioutil.NopCloser(bytes.NewReader(nil))}, nil
110+
}
111+
76112
type userAgentTransport struct {
77113
userAgent string
78114
base http.RoundTripper

0 commit comments

Comments
 (0)