Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CORS to the connectRPC server #146

Merged
merged 4 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 2 additions & 11 deletions api/v1/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,13 @@ func NodeToServiceNode(node *graph.Node) (*service.Node, error) {
return nil, err
}

dependencies, err := node.Parents.ToBase64()
if err != nil {
return nil, err
}
dependents, err := node.Children.ToBase64()
if err != nil {
return nil, err
}

return &service.Node{
Id: node.ID,
Name: node.Name,
Type: node.Type,
Metadata: data,
Dependencies: dependencies,
Dependents: dependents,
Dependencies: node.Children.ToArray(),
Dependents: node.Parents.ToArray(),
}, nil
}

Expand Down
4 changes: 2 additions & 2 deletions api/v1/service.proto
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ message Node {
uint32 id = 1;
string name = 2;
string type = 3;
string dependencies = 4;
string dependents = 5;
repeated uint32 dependencies = 4;
repeated uint32 dependents = 5;
bytes metadata = 6;
}

Expand Down
24 changes: 23 additions & 1 deletion cmd/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ import (
"syscall"
"time"

connectcors "connectrpc.com/cors"
service "github.com/bitbomdev/minefield/api/v1"
"github.com/bitbomdev/minefield/gen/api/v1/apiv1connect"
"github.com/bitbomdev/minefield/pkg/graph"
"github.com/bitbomdev/minefield/pkg/storages"
"github.com/rs/cors"
"github.com/spf13/cobra"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
Expand All @@ -28,6 +30,7 @@ type options struct {
StorageAddr string
StoragePath string
UseInMemory bool
CORS []string
}

const (
Expand All @@ -44,6 +47,12 @@ func (o *options) AddFlags(cmd *cobra.Command) {
cmd.Flags().StringVar(&o.StorageAddr, "storage-addr", "localhost:6379", "Address for redis storage backend")
cmd.Flags().StringVar(&o.StoragePath, "storage-path", "", "Path to the SQLite database file")
cmd.Flags().BoolVar(&o.UseInMemory, "use-in-memory", true, "Use in-memory SQLite database")
cmd.Flags().StringSliceVar(
&o.CORS,
"cors",
[]string{"http://localhost:8089"},
"Allowed origins for CORS (e.g., 'https://app.bitbom.dev')",
)
}

func (o *options) ProvideStorage() (graph.Storage, error) {
Expand Down Expand Up @@ -116,7 +125,7 @@ func (o *options) setupServer() (*http.Server, error) {

server := &http.Server{
Addr: serviceAddr,
Handler: h2c.NewHandler(mux, &http2.Server{}),
Handler: h2c.NewHandler(withCORS(mux, o), &http2.Server{}),
}

return server, nil
Expand Down Expand Up @@ -175,3 +184,16 @@ func NewServerCommand(storage graph.Storage, o *options) (*cobra.Command, error)
o.AddFlags(cmd)
return cmd, nil
}

// withCORS adds CORS support to a Connect HTTP handler.
func withCORS(h http.Handler, o *options) http.Handler {
middleware := cors.New(cors.Options{
AllowedOrigins: o.CORS,
AllowedMethods: connectcors.AllowedMethods(),
AllowedHeaders: connectcors.AllowedHeaders(),
ExposedHeaders: connectcors.ExposedHeaders(),
AllowCredentials: true,
MaxAge: 3600,
})
return middleware.Handler(h)
}
125 changes: 125 additions & 0 deletions cmd/server/server_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package server

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/bitbomdev/minefield/pkg/graph"
Expand Down Expand Up @@ -200,3 +202,126 @@ func TestOptions_PersistentPreRunE(t *testing.T) {
})
}
}

func TestWithCORS(t *testing.T) {
// Define test cases
testCases := []struct {
name string
options options
requestOrigin string
expectedOrigin string
}{
{
name: "Allowed Origin",
options: options{
CORS: []string{"http://localhost:3000", "https://example.com"},
},
requestOrigin: "http://localhost:3000",
expectedOrigin: "http://localhost:3000",
},
{
name: "Disallowed Origin",
options: options{
CORS: []string{"http://localhost:3000", "https://example.com"},
},
requestOrigin: "http://malicious.com",
expectedOrigin: "",
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Create a dummy handler that writes a 200 OK status
dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})

// Wrap the dummy handler with CORS middleware
handler := withCORS(dummyHandler, &tc.options)

// Create a new HTTP request with the specified Origin header
req := httptest.NewRequest("GET", "http://localhost:8089/test", nil)
req.Header.Set("Origin", tc.requestOrigin)

// Create a ResponseRecorder to capture the response
rr := httptest.NewRecorder()

// Serve the HTTP request
handler.ServeHTTP(rr, req)

// Check the CORS headers
if tc.expectedOrigin != "" {
assert.Equal(t, tc.expectedOrigin, rr.Header().Get("Access-Control-Allow-Origin"), "Access-Control-Allow-Origin should match the allowed origin")
} else {
assert.Empty(t, rr.Header().Get("Access-Control-Allow-Origin"), "Access-Control-Allow-Origin should be empty for disallowed origins")
}

// Optionally, check other CORS headers if needed
if rr.Header().Get("Access-Control-Allow-Credentials") != "" {
assert.Equal(t, "true", rr.Header().Get("Access-Control-Allow-Credentials"), "Access-Control-Allow-Credentials should be true")
}
})
}
}

func TestNewServerCommand(t *testing.T) {
tests := []struct {
name string
storage graph.Storage
options *options
wantErr bool
wantCommand struct {
use string
short string
}
}{
{
name: "creates server command with valid storage and options",
storage: &mockStorage{},
options: &options{
concurrency: 10,
addr: "localhost:8089",
},
wantErr: false,
wantCommand: struct {
use string
short string
}{
use: "server",
short: "Start the minefield server for graph operations and queries",
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd, err := NewServerCommand(tt.storage, tt.options)

if tt.wantErr {
assert.Error(t, err)
assert.Nil(t, cmd)
return
}

assert.NoError(t, err)
assert.NotNil(t, cmd)
assert.Equal(t, tt.wantCommand.use, cmd.Use)
assert.Equal(t, tt.wantCommand.short, cmd.Short)
assert.True(t, cmd.DisableAutoGenTag)

// Verify storage is set correctly in options
assert.Equal(t, tt.storage, tt.options.storage)

// Verify flags are added
flags := cmd.Flags()

concurrencyFlag := flags.Lookup("concurrency")
assert.NotNil(t, concurrencyFlag)
assert.Equal(t, "10", concurrencyFlag.DefValue)

addrFlag := flags.Lookup("addr")
assert.NotNil(t, addrFlag)
assert.Equal(t, "localhost:8089", addrFlag.DefValue)
})
}
}
24 changes: 12 additions & 12 deletions gen/api/v1/service.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.23.1

require (
connectrpc.com/connect v1.17.0
connectrpc.com/cors v0.1.0
github.com/Masterminds/semver v1.5.0
github.com/RoaringBitmap/roaring v1.9.4
github.com/alecthomas/participle/v2 v2.1.1
Expand Down Expand Up @@ -47,6 +48,7 @@ require (
github.com/mattn/go-sqlite3 v1.14.24 // indirect
github.com/mschoch/smat v0.2.0 // indirect
github.com/onsi/gomega v1.30.0 // indirect
github.com/rs/cors v1.11.1
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spdx/tools-golang v0.5.5 // indirect
github.com/stretchr/objx v0.5.2 // indirect
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
connectrpc.com/connect v1.17.0 h1:W0ZqMhtVzn9Zhn2yATuUokDLO5N+gIuBWMOnsQrfmZk=
connectrpc.com/connect v1.17.0/go.mod h1:0292hj1rnx8oFrStN7cB4jjVBeqs+Yx5yDIC2prWDO8=
connectrpc.com/cors v0.1.0 h1:f3gTXJyDZPrDIZCQ567jxfD9PAIpopHiRDnJRt3QuOQ=
connectrpc.com/cors v0.1.0/go.mod h1:v8SJZCPfHtGH1zsm+Ttajpozd4cYIUryl4dFB6QEpfg=
github.com/CycloneDX/cyclonedx-go v0.9.1 h1:yffaWOZsv77oTJa/SdVZYdgAgFioCeycBUKkqS2qzQM=
github.com/CycloneDX/cyclonedx-go v0.9.1/go.mod h1:NE/EWvzELOFlG6+ljX/QeMlVt9VKcTwu8u0ccsACEsw=
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
Expand Down Expand Up @@ -82,6 +84,8 @@ github.com/protobom/protobom v0.5.0 h1:jJYqGpdHq99zwh0/n1SOPl1aickCBZdA8pHS9V/f+
github.com/protobom/protobom v0.5.0/go.mod h1:HL47tggz7SXYXgNm3WjQQrWB6iOirYnrATsXAEyTUkI=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
Expand Down
Loading