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 This commit was moved from ipfs/go-ipfs-http-client@7e1de1f7ccfa8cd1f616e94664886fe04d70806e
Ross Jones committed
May 15, 2023 at 17:18 UTC
7d8262307cb40c1f21fd79fe52cdfd36a7dcb5cd
2 files changed
+43
-1
client/httpapi/api.go
+15
-1
@@ -107,7 +107,21 @@ func NewApiWithClient(a ma.Multiaddr, c *http.Client) (*HttpApi, error) {
107
}
108
}
109
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)
125
}
126
127
func NewURLApiWithClient(url string, c *http.Client) (*HttpApi, error) {
client/httpapi/api_test.go
+28
@@ -246,3 +246,31 @@ func Test_NewURLApiWithClient_With_Headers(t *testing.T) {
246
t.Fatal(err)
247
}
248
}
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
+}