From 0ba8d3e81638f14ccf3348fe0bb1beb57bfcab54 Mon Sep 17 00:00:00 2001 From: LexLuthr Date: Thu, 20 Jul 2023 17:00:57 +0400 Subject: [PATCH 1/4] add corshandler to IPFS gateway --- cmd/booster-http/gateway_handler.go | 10 ++++++---- gql/server.go | 7 ++++--- {gql => lib/corshandler}/cors.go | 10 +++++----- 3 files changed, 15 insertions(+), 12 deletions(-) rename {gql => lib/corshandler}/cors.go (68%) diff --git a/cmd/booster-http/gateway_handler.go b/cmd/booster-http/gateway_handler.go index f15663e5f..5a9522874 100644 --- a/cmd/booster-http/gateway_handler.go +++ b/cmd/booster-http/gateway_handler.go @@ -6,6 +6,7 @@ import ( "net/http" "strings" + "github.com/filecoin-project/boost/lib/corshandler" "github.com/ipfs/boxo/gateway" ) @@ -24,10 +25,11 @@ func newGatewayHandler(gw *gateway.BlocksBackend, supportedFormats []string) htt } return &gatewayHandler{ - gwh: gateway.NewHandler(gateway.Config{ - Headers: headers, - DeserializedResponses: true, - }, gw), + gwh: &corshandler.CorsHandler{ + Sub: gateway.NewHandler(gateway.Config{ + Headers: headers, + DeserializedResponses: true, + }, gw)}, supportedFormats: fmtsMap, } } diff --git a/gql/server.go b/gql/server.go index b0d2360e4..3b11a400d 100644 --- a/gql/server.go +++ b/gql/server.go @@ -12,6 +12,7 @@ import ( "sync" "time" + "github.com/filecoin-project/boost/lib/corshandler" "github.com/filecoin-project/boost/node/config" "github.com/filecoin-project/boost/react" "github.com/graph-gophers/graphql-go" @@ -31,7 +32,7 @@ type Server struct { } func NewServer(cfg *config.Boost, resolver *resolver, bstore BlockGetter) *Server { - webCfg := &corsHandler{sub: &webConfigServer{ + webCfg := &corshandler.CorsHandler{Sub: &webConfigServer{ cfg: webConfig{ Ipni: webConfigIpni{ IndexerHost: cfg.IndexProvider.WebHost, @@ -91,8 +92,8 @@ func (s *Server) Start(ctx context.Context) error { listenAddr := fmt.Sprintf("%s:%d", bindAddress, port) s.srv = &http.Server{Addr: listenAddr, Handler: mux} fmt.Printf("Graphql server listening on %s\n", listenAddr) - mux.Handle("/graphql/subscription", &corsHandler{wsHandler}) - mux.Handle("/graphql/query", &corsHandler{queryHandler}) + mux.Handle("/graphql/subscription", &corshandler.CorsHandler{Sub: wsHandler}) + mux.Handle("/graphql/query", &corshandler.CorsHandler{Sub: queryHandler}) s.wg.Add(1) go func() { diff --git a/gql/cors.go b/lib/corshandler/cors.go similarity index 68% rename from gql/cors.go rename to lib/corshandler/cors.go index 6a20e8220..798e5ffb0 100644 --- a/gql/cors.go +++ b/lib/corshandler/cors.go @@ -1,13 +1,13 @@ -package gql +package corshandler import "net/http" // Sets CORS headers to allow all -type corsHandler struct { - sub http.Handler +type CorsHandler struct { + Sub http.Handler } -func (h *corsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { +func (h *CorsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT") w.Header().Set("Access-Control-Allow-Headers", "*") @@ -16,5 +16,5 @@ func (h *corsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } - h.sub.ServeHTTP(w, r) + h.Sub.ServeHTTP(w, r) } From 57fd5dde6445e4eb8d3865d82e1ecc39ea68857a Mon Sep 17 00:00:00 2001 From: LexLuthr Date: Mon, 24 Jul 2023 15:50:35 +0400 Subject: [PATCH 2/4] use cors lib --- cmd/booster-http/gateway_handler.go | 10 ++++------ cmd/booster-http/http_test.go | 15 ++++++++++++--- cmd/booster-http/server.go | 16 +++++++++++++--- gql/server.go | 20 ++++++++++++++------ lib/corshandler/cors.go | 20 -------------------- 5 files changed, 43 insertions(+), 38 deletions(-) delete mode 100644 lib/corshandler/cors.go diff --git a/cmd/booster-http/gateway_handler.go b/cmd/booster-http/gateway_handler.go index 5a9522874..f15663e5f 100644 --- a/cmd/booster-http/gateway_handler.go +++ b/cmd/booster-http/gateway_handler.go @@ -6,7 +6,6 @@ import ( "net/http" "strings" - "github.com/filecoin-project/boost/lib/corshandler" "github.com/ipfs/boxo/gateway" ) @@ -25,11 +24,10 @@ func newGatewayHandler(gw *gateway.BlocksBackend, supportedFormats []string) htt } return &gatewayHandler{ - gwh: &corshandler.CorsHandler{ - Sub: gateway.NewHandler(gateway.Config{ - Headers: headers, - DeserializedResponses: true, - }, gw)}, + gwh: gateway.NewHandler(gateway.Config{ + Headers: headers, + DeserializedResponses: true, + }, gw), supportedFormats: fmtsMap, } } diff --git a/cmd/booster-http/http_test.go b/cmd/booster-http/http_test.go index 3fe058ef9..4234e9c7d 100644 --- a/cmd/booster-http/http_test.go +++ b/cmd/booster-http/http_test.go @@ -27,10 +27,19 @@ func TestNewHttpServer(t *testing.T) { require.NoError(t, err) waitServerUp(t, 7777) - // Check that server is responding with 200 status code - resp, err := http.Get("http://localhost:7777/") + // Create a request with Cors header + req, err := http.NewRequest("GET", "http://localhost:7777/", nil) + require.NoError(t, err) + req.Header.Add("Origin", "test") + client := new(http.Client) + response, err := client.Do(req) require.NoError(t, err) - require.Equal(t, 200, resp.StatusCode) + + // Check that server is responding with 200 status code + require.Equal(t, 200, response.StatusCode) + + // Check for Cors header + require.Equal(t, "*", response.Header.Get("Access-Control-Allow-Origin")) // Stop the server err = httpServer.Stop() diff --git a/cmd/booster-http/server.go b/cmd/booster-http/server.go index 560345a5d..2c6344424 100644 --- a/cmd/booster-http/server.go +++ b/cmd/booster-http/server.go @@ -21,11 +21,12 @@ import ( "github.com/filecoin-project/go-state-types/abi" "github.com/hashicorp/go-multierror" "github.com/ipfs/boxo/blockservice" - blockstore "github.com/ipfs/boxo/blockstore" - offline "github.com/ipfs/boxo/exchange/offline" + "github.com/ipfs/boxo/blockstore" + "github.com/ipfs/boxo/exchange/offline" "github.com/ipfs/boxo/gateway" "github.com/ipfs/go-cid" "github.com/ipfs/go-datastore" + "github.com/rs/cors" "go.opencensus.io/stats" ) @@ -82,8 +83,17 @@ func (s *HttpServer) ipfsBasePath() string { return s.path + "/ipfs/" } +func newCors() *cors.Cors { + options := cors.Options{ + AllowedHeaders: []string{"*"}, + } + c := cors.New(options) + return c +} + func (s *HttpServer) Start(ctx context.Context) error { s.ctx, s.cancel = context.WithCancel(ctx) + c := newCors() handler := http.NewServeMux() if s.opts.ServePieces { @@ -105,7 +115,7 @@ func (s *HttpServer) Start(ctx context.Context) error { handler.Handle("/metrics", metrics.Exporter("booster_http")) // metrics s.server = &http.Server{ Addr: fmt.Sprintf("%s:%d", s.listenAddr, s.port), - Handler: handler, + Handler: c.Handler(handler), // This context will be the parent of the context associated with all // incoming requests BaseContext: func(listener net.Listener) context.Context { diff --git a/gql/server.go b/gql/server.go index 3b11a400d..2f281c9d7 100644 --- a/gql/server.go +++ b/gql/server.go @@ -12,13 +12,13 @@ import ( "sync" "time" - "github.com/filecoin-project/boost/lib/corshandler" "github.com/filecoin-project/boost/node/config" "github.com/filecoin-project/boost/react" "github.com/graph-gophers/graphql-go" "github.com/graph-gophers/graphql-go/relay" "github.com/graph-gophers/graphql-transport-ws/graphqlws" logging "github.com/ipfs/go-log/v2" + "github.com/rs/cors" ) var log = logging.Logger("gql") @@ -32,13 +32,14 @@ type Server struct { } func NewServer(cfg *config.Boost, resolver *resolver, bstore BlockGetter) *Server { - webCfg := &corshandler.CorsHandler{Sub: &webConfigServer{ + c := cors.Default() + webCfg := c.Handler(&webConfigServer{ cfg: webConfig{ Ipni: webConfigIpni{ IndexerHost: cfg.IndexProvider.WebHost, }, }, - }} + }) return &Server{resolver: resolver, bstore: bstore, cfgHandler: webCfg} } @@ -50,6 +51,13 @@ func (s *Server) Start(ctx context.Context) error { // Serve React app mux := http.NewServeMux() + + // Get new cors + options := cors.Options{ + AllowedHeaders: []string{"*"}, + } + c := cors.New(options) + err := s.serveReactApp(mux) if err != nil { return err @@ -90,10 +98,10 @@ func (s *Server) Start(ctx context.Context) error { wsHandler := graphqlws.NewHandlerFunc(schema, queryHandler, wsOpts...) listenAddr := fmt.Sprintf("%s:%d", bindAddress, port) - s.srv = &http.Server{Addr: listenAddr, Handler: mux} + s.srv = &http.Server{Addr: listenAddr, Handler: c.Handler(mux)} fmt.Printf("Graphql server listening on %s\n", listenAddr) - mux.Handle("/graphql/subscription", &corshandler.CorsHandler{Sub: wsHandler}) - mux.Handle("/graphql/query", &corshandler.CorsHandler{Sub: queryHandler}) + mux.Handle("/graphql/subscription", wsHandler) + mux.Handle("/graphql/query", queryHandler) s.wg.Add(1) go func() { diff --git a/lib/corshandler/cors.go b/lib/corshandler/cors.go deleted file mode 100644 index 798e5ffb0..000000000 --- a/lib/corshandler/cors.go +++ /dev/null @@ -1,20 +0,0 @@ -package corshandler - -import "net/http" - -// Sets CORS headers to allow all -type CorsHandler struct { - Sub http.Handler -} - -func (h *CorsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Access-Control-Allow-Origin", "*") - w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT") - w.Header().Set("Access-Control-Allow-Headers", "*") - if r.Method == "OPTIONS" { - _, _ = w.Write([]byte("OK")) - return - } - - h.Sub.ServeHTTP(w, r) -} From f552ac2cad379d123b727f2d05baf1f696768924 Mon Sep 17 00:00:00 2001 From: LexLuthr Date: Mon, 24 Jul 2023 15:55:42 +0400 Subject: [PATCH 3/4] go mod tidy --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index ced65b012..8c64bc09c 100644 --- a/go.mod +++ b/go.mod @@ -287,7 +287,7 @@ require ( github.com/prometheus/procfs v0.9.0 // indirect github.com/prometheus/statsd_exporter v0.22.7 // indirect github.com/rivo/uniseg v0.2.0 // indirect - github.com/rs/cors v1.7.0 // indirect + github.com/rs/cors v1.7.0 github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect github.com/sirupsen/logrus v1.9.0 // indirect From 4f8de8b432a5b33eb82dd4529aa23d372f92d98a Mon Sep 17 00:00:00 2001 From: LexLuthr Date: Mon, 24 Jul 2023 16:08:17 +0400 Subject: [PATCH 4/4] refactor test, remove extra cors --- cmd/booster-http/http_test.go | 8 +++++--- gql/server.go | 5 ++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/cmd/booster-http/http_test.go b/cmd/booster-http/http_test.go index 4234e9c7d..b47ed821a 100644 --- a/cmd/booster-http/http_test.go +++ b/cmd/booster-http/http_test.go @@ -27,6 +27,11 @@ func TestNewHttpServer(t *testing.T) { require.NoError(t, err) waitServerUp(t, 7777) + // Check that server is responding with 200 status code + resp, err := http.Get("http://localhost:7777/") + require.NoError(t, err) + require.Equal(t, 200, resp.StatusCode) + // Create a request with Cors header req, err := http.NewRequest("GET", "http://localhost:7777/", nil) require.NoError(t, err) @@ -35,9 +40,6 @@ func TestNewHttpServer(t *testing.T) { response, err := client.Do(req) require.NoError(t, err) - // Check that server is responding with 200 status code - require.Equal(t, 200, response.StatusCode) - // Check for Cors header require.Equal(t, "*", response.Header.Get("Access-Control-Allow-Origin")) diff --git a/gql/server.go b/gql/server.go index 2f281c9d7..1dbd79256 100644 --- a/gql/server.go +++ b/gql/server.go @@ -32,14 +32,13 @@ type Server struct { } func NewServer(cfg *config.Boost, resolver *resolver, bstore BlockGetter) *Server { - c := cors.Default() - webCfg := c.Handler(&webConfigServer{ + webCfg := &webConfigServer{ cfg: webConfig{ Ipni: webConfigIpni{ IndexerHost: cfg.IndexProvider.WebHost, }, }, - }) + } return &Server{resolver: resolver, bstore: bstore, cfgHandler: webCfg} }