Skip to content
This repository was archived by the owner on Oct 5, 2023. It is now read-only.

Commit 7e1de1f

Browse files
authored
fix: use https URI when multiaddress specifies tls (#177)
Currently any clients created through `NewApiWithClient` will make a HTTP request to the api, even if the multiaddress specifies TLS or (the deprecated multiaddr option) https. This commit addresses this by having NewApiWithClient iterate the available protocols for the multiaddress, specifying the URL proto as https if it finds TLS or HTTPS is specified. The default continues to be http for those multiaddresses that do not specify these options. Should resolve #176
1 parent ae996cb commit 7e1de1f

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

api.go

+15-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,21 @@ func NewApiWithClient(a ma.Multiaddr, c *http.Client) (*HttpApi, error) {
107107
}
108108
}
109109

110-
return NewURLApiWithClient(url, c)
110+
proto := "http://"
111+
112+
// By default, DialArgs is going to provide details suitable for connecting
113+
// a socket to, but not really suitable for making an informed choice of http
114+
// protocol. For multiaddresses specifying tls and/or https we want to make
115+
// a https request instead of a http request.
116+
protocols := a.Protocols()
117+
for _, p := range protocols {
118+
if p.Code == ma.P_HTTPS || p.Code == ma.P_TLS {
119+
proto = "https://"
120+
break
121+
}
122+
}
123+
124+
return NewURLApiWithClient(proto+url, c)
111125
}
112126

113127
func NewURLApiWithClient(url string, c *http.Client) (*HttpApi, error) {

api_test.go

+28
Original file line numberDiff line numberDiff line change
@@ -246,3 +246,31 @@ func Test_NewURLApiWithClient_With_Headers(t *testing.T) {
246246
t.Fatal(err)
247247
}
248248
}
249+
250+
func Test_NewURLApiWithClient_HTTP_Variant(t *testing.T) {
251+
testcases := []struct {
252+
address string
253+
expected string
254+
}{
255+
{address: "/ip4/127.0.0.1/tcp/80", expected: "http://127.0.0.1:80"},
256+
{address: "/ip4/127.0.0.1/tcp/443/tls", expected: "https://127.0.0.1:443"},
257+
{address: "/ip4/127.0.0.1/tcp/443/https", expected: "https://127.0.0.1:443"},
258+
{address: "/ip4/127.0.0.1/tcp/443/tls/http", expected: "https://127.0.0.1:443"},
259+
}
260+
261+
for _, tc := range testcases {
262+
address, err := ma.NewMultiaddr(tc.address)
263+
if err != nil {
264+
t.Fatal(err)
265+
}
266+
267+
api, err := NewApiWithClient(address, &http.Client{})
268+
if err != nil {
269+
t.Fatal(err)
270+
}
271+
272+
if api.url != tc.expected {
273+
t.Errorf("Expected = %s; got %s", tc.expected, api.url)
274+
}
275+
}
276+
}

0 commit comments

Comments
 (0)