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

feat: allow configuration of cors domains and credentials #159

Merged
merged 7 commits into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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: 12 additions & 1 deletion cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ const (
postgresMigrationsSourceFlag = "postgres-migrations-source"
fastlyServiceFlag = "fastly-service"
fastlyKeyFlag = "fastly-key"
corsAllowOriginsFlag = "cors-allow-origins"
corsAllowCredentialsFlag = "cors-allow-credentials"
)

func ginLogger(logger *logrus.Logger) gin.HandlerFunc {
Expand Down Expand Up @@ -82,6 +84,8 @@ func getGin(
trustedProxies []string,
logger *logrus.Logger,
debug bool,
corsAllowOrigins []string,
corsAllowCredentials bool,
) (*gin.Engine, error) {
if !debug {
gin.SetMode(gin.ReleaseMode)
Expand All @@ -107,7 +111,7 @@ func getGin(
middlewares = append(middlewares, fastly.New(fastlyService, viper.GetString(fastlyKeyFlag), logger))
}

return ctrl.SetupRouter(trustedProxies, apiRootPrefix, middlewares...) //nolint: wrapcheck
return ctrl.SetupRouter(trustedProxies, apiRootPrefix, corsAllowOrigins, corsAllowCredentials, middlewares...) //nolint: wrapcheck
}

func getMetadataStorage(endpoint string) *metadata.Hasura {
Expand Down Expand Up @@ -214,6 +218,11 @@ func init() {
addStringFlag(serveCmd.Flags(), fastlyServiceFlag, "", "Enable Fastly middleware and enable automated purges")
addStringFlag(serveCmd.Flags(), fastlyKeyFlag, "", "Fastly CDN Key to authenticate purges")
}

{
addStringArrayFlag(serveCmd.Flags(), corsAllowOriginsFlag, []string{"*"}, "CORS allow origins")
addBoolFlag(serveCmd.Flags(), corsAllowCredentialsFlag, false, "CORS allow credentials")
}
}

var serveCmd = &cobra.Command{
Expand Down Expand Up @@ -282,6 +291,8 @@ var serveCmd = &cobra.Command{
viper.GetStringSlice(trustedProxiesFlag),
logger,
viper.GetBool(debugFlag),
viper.GetStringSlice(corsAllowOriginsFlag),
viper.GetBool(corsAllowCredentialsFlag),
)
cobra.CheckErr(err)

Expand Down
19 changes: 14 additions & 5 deletions controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,11 @@ func New(
}

func (ctrl *Controller) SetupRouter(
trustedProxies []string, apiRootPrefix string, middleware ...gin.HandlerFunc,
trustedProxies []string,
apiRootPrefix string,
corsOrigins []string,
corsAllowCredentials bool,
middleware ...gin.HandlerFunc,
) (*gin.Engine, error) {
router := gin.New()
if err := router.SetTrustedProxies(trustedProxies); err != nil {
Expand All @@ -126,20 +130,25 @@ func (ctrl *Controller) SetupRouter(
router.Use(mw)
}

router.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
corsConfig := cors.Config{
AllowOrigins: corsOrigins,
AllowMethods: []string{"GET", "PUT", "POST", "HEAD", "DELETE"},
AllowHeaders: []string{
"Authorization", "Origin", "if-match", "if-none-match", "if-modified-since", "if-unmodified-since",
"x-hasura-admin-secret", "x-nhost-bucket-id", "x-nhost-file-name", "x-nhost-file-id",
"x-hasura-role",
},
// AllowWildcard: true,
ExposeHeaders: []string{
"Content-Length", "Content-Type", "Cache-Control", "ETag", "Last-Modified", "X-Error",
},
MaxAge: 12 * time.Hour, //nolint: gomnd
}))
}

if corsAllowCredentials {
corsConfig.AllowCredentials = true
}

router.Use(cors.New(corsConfig))

router.GET("/healthz", ctrl.Health)

Expand Down
2 changes: 1 addition & 1 deletion controller/delete_broken_metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func TestDeleteBrokenMetadata(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))
jhleao marked this conversation as resolved.
Show resolved Hide resolved

responseRecorder := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion controller/delete_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestDeleteFile(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion controller/delete_orphans_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func TestDeleteOrphans(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
3 changes: 2 additions & 1 deletion controller/get_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"

Expand Down Expand Up @@ -222,7 +223,7 @@ func (ctrl *Controller) getFileProcess(ctx *gin.Context) (*FileResponse, *APIErr

if response.statusCode == http.StatusOK {
// if we want to download files at some point prepend `attachment;` before filename
response.headers.Add("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, fileMetadata.Name))
response.headers.Add("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, url.QueryEscape(fileMetadata.Name)))
}

return response, nil
Expand Down
2 changes: 1 addition & 1 deletion controller/get_file_information_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func TestGetFileInfo(t *testing.T) {
logger,
)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion controller/get_file_presigned_url_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func TestGetFilePresignedURL(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion controller/get_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func TestGetFile(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion controller/list_broken_metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func TestListBrokenMetadata(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion controller/list_not_uploaded_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func TestListNotUploaded(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
2 changes: 1 addition & 1 deletion controller/list_orphans_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func TestListOrphans(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

responseRecorder := httptest.NewRecorder()

Expand Down
3 changes: 2 additions & 1 deletion controller/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -81,7 +82,7 @@ func (r *FileResponse) Write(ctx *gin.Context) {
ctx.Header("Etag", r.etag)

if r.body != nil && (r.statusCode == http.StatusOK || r.statusCode == http.StatusPartialContent) {
ctx.Writer.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, r.name))
ctx.Writer.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, url.QueryEscape(r.name)))

_, err := io.Copy(ctx.Writer, r.body)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion controller/update_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func TestUpdateFile(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

body, contentType := createUpdateMultiForm(t, file)

Expand Down
2 changes: 1 addition & 1 deletion controller/upload_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ func TestUploadFile(t *testing.T) {

ctrl := controller.New("http://asd", "/v1", "asdasd", metadataStorage, contentStorage, nil, logger)

router, _ := ctrl.SetupRouter(nil, "/v1", ginLogger(logger))
router, _ := ctrl.SetupRouter(nil, "/v1", []string{}, false, ginLogger(logger))

body, contentType := createMultiForm(t, files...)

Expand Down