Skip to content

Commit

Permalink
Backport #5671: Add a Flag for CORS (#6853)
Browse files Browse the repository at this point in the history
This adds the --unsafe-cors flag functionality.

From: #5671
Co-authored-by: Marko <[email protected]>
  • Loading branch information
ethanfrey and tac0turtle authored Jul 27, 2020
1 parent 7b931e2 commit 302487c
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 34 deletions.
2 changes: 2 additions & 0 deletions client/flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ const (
FlagKeyringBackend = "keyring-backend"
FlagPage = "page"
FlagLimit = "limit"
FlagUnsafeCORS = "unsafe-cors"
)

// LineBreak can be included in a command list to provide a blank line
Expand Down Expand Up @@ -141,6 +142,7 @@ func RegisterRestServerFlags(cmd *cobra.Command) *cobra.Command {
cmd.Flags().Uint(FlagMaxOpenConnections, 1000, "The number of maximum open connections")
cmd.Flags().Uint(FlagRPCReadTimeout, 10, "The RPC read timeout (in seconds)")
cmd.Flags().Uint(FlagRPCWriteTimeout, 10, "The RPC write timeout (in seconds)")
cmd.Flags().Bool(FlagUnsafeCORS, false, "Allows CORS requests from all domains. For development purposes only, use it at your own risk.")

return cmd
}
Expand Down
11 changes: 9 additions & 2 deletions client/lcd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"os"
"time"

"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -46,7 +47,7 @@ func NewRestServer(cdc *codec.Codec) *RestServer {
}

// Start starts the rest server
func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTimeout uint) (err error) {
func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTimeout uint, cors bool) (err error) {
server.TrapSignal(func() {
err := rs.listener.Close()
rs.log.Error("error closing listener", "err", err)
Expand All @@ -68,7 +69,12 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi
),
)

return tmrpcserver.Serve(rs.listener, rs.Mux, rs.log, cfg)
var h http.Handler = rs.Mux
if cors {
h = handlers.CORS()(h)
}

return tmrpcserver.Serve(rs.listener, h, rs.log, cfg)
}

// ServeCommand will start the application REST service as a blocking process. It
Expand All @@ -90,6 +96,7 @@ func ServeCommand(cdc *codec.Codec, registerRoutesFn func(*RestServer)) *cobra.C
viper.GetInt(flags.FlagMaxOpenConnections),
uint(viper.GetInt(flags.FlagRPCReadTimeout)),
uint(viper.GetInt(flags.FlagRPCWriteTimeout)),
viper.GetBool(flags.FlagUnsafeCORS),
)

return err
Expand Down
33 changes: 22 additions & 11 deletions docs/interfaces/rest.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ synopsis: "This document describes how to create a REST interface for an SDK **a

## Prerequisites {hide}

* [Query Lifecycle](./query-lifecycle.md) {prereq}
* [Application CLI](./cli.md) {prereq}
- [Query Lifecycle](./query-lifecycle.md) {prereq}
- [Application CLI](./cli.md) {prereq}

## Application REST Interface
## Application REST Interface

Building the REST Interface for an application is done by [aggregating REST Routes](#registering-routes) defined in the application's modules. This interface is served by a REST Server [REST server](#rest-server), which route requests and output responses in the application itself. The SDK comes with its own REST Server by default. To enable it, the `rest.ServeCommand` command needs to be added as a subcommand of the `rootCmd` in the `main()` function of the [CLI interface](./cli.md):

Expand All @@ -24,27 +24,27 @@ Users will then be able to use the application CLI to start a new REST server, a
appcli rest-server --chain-id <chainID> --trust-node
```

Note that if `trust-node` is set to `false`, the REST server will verify the query proof against the merkle root (contained in the block header).
Note that if `trust-node` is set to `false`, the REST server will verify the query proof against the merkle root (contained in the block header).

## REST Server

A REST Server is used to receive and route HTTP Requests, obtain the results from the application, and return a response to the user. The REST Server defined by the SDK `rest` package contains the following:

* **Router:** A router for HTTP requests. A new router can be instantiated for an application and used to match routes based on path, request method, headers, etc. The SDK uses the [Gorilla Mux Router](https://github.com/gorilla/mux).
* **CLIContext:** A [`CLIContext`](./query-lifecycle.md#clicontext) created for a user interaction.
* **Keybase:** A [Keybase](../basics/accounts.md#keybase) is a key manager.
* **Logger:** A logger from Tendermint `Log`, a log package structured around key-value pairs that allows logging level to be set differently for different keys. The logger takes `Debug()`, `Info()`, and `Error()`s.
* **Listener:** A [listener](https://golang.org/pkg/net/#Listener) from the net package.
- **Router:** A router for HTTP requests. A new router can be instantiated for an application and used to match routes based on path, request method, headers, etc. The SDK uses the [Gorilla Mux Router](https://github.com/gorilla/mux).
- **CLIContext:** A [`CLIContext`](./query-lifecycle.md#clicontext) created for a user interaction.
- **Keybase:** A [Keybase](../basics/accounts.md#keybase) is a key manager.
- **Logger:** A logger from Tendermint `Log`, a log package structured around key-value pairs that allows logging level to be set differently for different keys. The logger takes `Debug()`, `Info()`, and `Error()`s.
- **Listener:** A [listener](https://golang.org/pkg/net/#Listener) from the net package.

Of the five, the only attribute that application developers need interact with is the `router`: they need to add routes to it so that the REST server can properly handle queries. See the next section for more information on registering routes.
Of the five, the only attribute that application developers need interact with is the `router`: they need to add routes to it so that the REST server can properly handle queries. See the next section for more information on registering routes.

In order to enable the REST Server in an SDK application, the `rest.ServeCommand` needs to be added to the application's command-line interface. See the [above section](#application-rest-interface) for more information.

## Registering Routes

To include routes for each module in an application, the CLI must have some kind of function to register routes in its REST Server. This function is called `RegisterRoutes()`, and is utilized by the `ServeCommand` and must include routes for each of the application's modules. Since each module used by an SDK application implements a [`RegisterRESTRoutes`](../building-modules/module-interfaces.md#rest) function, application developers simply use the [Module Manager](../building-modules/module-manager.md) to call this function for each module (this is done in the [application's constructor](../basics/app-anatomy.md#constructor-function)).

At the bare minimum, a `RegisterRoutes()` function should use the SDK client package `RegisterRoutes()` function to be able to route RPC calls, and instruct the application Module Manager to call `RegisterRESTRoutes()` for all of its modules. This is done in the `main.go` file of the CLI (typically located in `./cmd/appcli/main.go`).
At the bare minimum, a `RegisterRoutes()` function should use the SDK client package `RegisterRoutes()` function to be able to route RPC calls, and instruct the application Module Manager to call `RegisterRESTRoutes()` for all of its modules. This is done in the `main.go` file of the CLI (typically located in `./cmd/appcli/main.go`).

```go
func registerRoutes(rs *rest.RestServer) {
Expand All @@ -58,3 +58,14 @@ This function is specific to the application and passed in to the `ServeCommand`
```go
rootCmd.AddCommand(rest.ServeCommand(cdc, registerRoutes))
```

## Cross-Origin Resource Sharing (CORS)

[CORS policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) are not enabled by default to help with security. If you would like to use the rest-server in a public environment we recommend you provide a reverse proxy, this can be done with [nginx](https://www.nginx.com/). For testing and development purposes there is an `unsafe_cors` flag that can be passed to the cmd to enable accepting cors from everyone.

```sh
gaiacli rest-server --chain-id=test \
--laddr=tcp://localhost:1317 \
--node tcp://localhost:26657 \
--trust-node=true --unsafe-cors
```
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ require (
github.com/cosmos/ledger-cosmos-go v0.11.1
github.com/gogo/protobuf v1.3.1
github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129
github.com/gorilla/mux v1.7.3
github.com/gorilla/handlers v1.4.2
github.com/gorilla/mux v1.7.4
github.com/hashicorp/golang-lru v0.5.4
github.com/mattn/go-isatty v0.0.12
github.com/pelletier/go-toml v1.6.0
Expand Down
Loading

0 comments on commit 302487c

Please sign in to comment.