From d25a2d0de2df4c30095febf8c7e9218cd2f5b87c Mon Sep 17 00:00:00 2001 From: Tsachi Herman <24438559+tsachiherman@users.noreply.github.com> Date: Fri, 8 Sep 2023 14:09:31 -0400 Subject: [PATCH 1/2] restore CORS support. (#943) --- cmd/soroban-rpc/internal/jsonrpc.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/cmd/soroban-rpc/internal/jsonrpc.go b/cmd/soroban-rpc/internal/jsonrpc.go index 4c6747316..b56c255c2 100644 --- a/cmd/soroban-rpc/internal/jsonrpc.go +++ b/cmd/soroban-rpc/internal/jsonrpc.go @@ -13,6 +13,7 @@ import ( "github.com/creachadair/jrpc2/jhttp" "github.com/go-chi/chi/middleware" "github.com/prometheus/client_golang/prometheus" + "github.com/rs/cors" "github.com/stellar/go/support/log" "github.com/stellar/soroban-tools/cmd/soroban-rpc/internal/config" @@ -277,9 +278,15 @@ func NewJSONRPCHandler(cfg *config.Config, params HandlerParams) Handler { // Limit request sizes to 10MB handler = http.MaxBytesHandler(handler, 1024*1024*10) + corsMiddleware := cors.New(cors.Options{ + AllowedOrigins: []string{"*"}, + AllowedHeaders: []string{"*"}, + AllowedMethods: []string{"GET", "PUT", "POST", "PATCH", "DELETE", "HEAD", "OPTIONS"}, + }) + return Handler{ bridge: bridge, logger: params.Logger, - Handler: handler, + Handler: corsMiddleware.Handler(handler), } } From 60e95399a2b2d98a03f49045540625bc71b7a1f2 Mon Sep 17 00:00:00 2001 From: Tsachi Herman <24438559+tsachiherman@users.noreply.github.com> Date: Fri, 8 Sep 2023 15:31:32 -0400 Subject: [PATCH 2/2] add CORS test (#944) --- cmd/soroban-rpc/internal/test/cors_test.go | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 cmd/soroban-rpc/internal/test/cors_test.go diff --git a/cmd/soroban-rpc/internal/test/cors_test.go b/cmd/soroban-rpc/internal/test/cors_test.go new file mode 100644 index 000000000..2e0cdb3eb --- /dev/null +++ b/cmd/soroban-rpc/internal/test/cors_test.go @@ -0,0 +1,32 @@ +package test + +import ( + "bytes" + "io" + "net/http" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestCORS ensures that we receive the correct CORS headers as a response to an HTTP request. +// Specifically, when we include an Origin header in the request, a soroban-rpc should response +// with a corresponding Access-Control-Allow-Origin. +func TestCORS(t *testing.T) { + test := NewTest(t) + + request, err := http.NewRequest("POST", test.sorobanRPCURL(), bytes.NewBufferString("{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"getHealth\"}")) + require.NoError(t, err) + request.Header.Set("Content-Type", "application/json") + origin := "testorigin.com" + request.Header.Set("Origin", origin) + + var client http.Client + response, err := client.Do(request) + require.NoError(t, err) + _, err = io.ReadAll(response.Body) + require.NoError(t, err) + + accessControl := response.Header.Get("Access-Control-Allow-Origin") + require.Equal(t, origin, accessControl) +}