Skip to content

Commit 1bacfb2

Browse files
lidelWalter Beegle
authored and
Walter Beegle
committed
fix(gateway): curl without redirect on localhost
When request is sent to http://localhost:8080/ipfs/$cid response has HTTP 301 status code and "Location" header with redirect destination at $cid.ipfs.localhost:8080 Redirect is followed by browsersi, but not by commandline tools. Status 301 is ignored by curl in default mode: it will print response and won't follow redirect, user needs to add -L for that. To fix curl, we return correct payload in body of HTTP 301 response, but set Clear-Site-Data header to ensure Origin sandbox can't be abused. This requires a surgical workaround: If Location header is present in ResponseWriter's Header map, we ensure http.ServeContent() returns HTTP 301 Context: ipfs#6982 License: MIT Signed-off-by: Marcin Rataj <[email protected]>
1 parent 195420a commit 1bacfb2

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

core/corehttp/gateway_handler.go

+20
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,25 @@ type gatewayHandler struct {
3838
api coreiface.CoreAPI
3939
}
4040

41+
// StatusResponseWriter enables us to override HTTP Status Code passed to
42+
// WriteHeader function inside of http.ServeContent. Decision is based on
43+
// presence of HTTP Headers such as Location.
44+
type statusResponseWriter struct {
45+
http.ResponseWriter
46+
}
47+
48+
func (sw *statusResponseWriter) WriteHeader(code int) {
49+
// Check if we need to adjust Status Code to account for scheduled redirect
50+
// This enables us to return payload along with HTTP 301
51+
// for subdomain redirect in web browsers while also returning body for cli
52+
// tools which do not follow redirects by default (curl, wget).
53+
redirect := sw.ResponseWriter.Header().Get("Location")
54+
if redirect != "" && code == http.StatusOK {
55+
code = http.StatusMovedPermanently
56+
}
57+
sw.ResponseWriter.WriteHeader(code)
58+
}
59+
4160
func newGatewayHandler(c GatewayConfig, api coreiface.CoreAPI) *gatewayHandler {
4261
i := &gatewayHandler{
4362
config: c,
@@ -366,6 +385,7 @@ func (i *gatewayHandler) serveFile(w http.ResponseWriter, req *http.Request, nam
366385
}
367386
w.Header().Set("Content-Type", ctype)
368387

388+
w = &statusResponseWriter{w}
369389
http.ServeContent(w, req, name, modtime, content)
370390
}
371391

0 commit comments

Comments
 (0)