Skip to content

Commit

Permalink
feat: Implement host functionality
Browse files Browse the repository at this point in the history
Users can have the local server created by the assistant hosted on a public URL using ngrok by passing the `--host` flag or setting `host` to true in config.
  • Loading branch information
damilolaedwards committed Sep 23, 2024
1 parent 6f14ca7 commit a6db177
Show file tree
Hide file tree
Showing 7 changed files with 119 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ This will use the specified configuration file and spin up the session, fetching
**Flags:**
- `--config`: Path to the configuration file.
- `--port`: The port the local server will be served on.
- `--host`: Whether the local server will be hosted using ngrok (requires the NGROK_AUTHTOKEN env variable be set).
- `--slither-args`: Extra arguments to be passed to slither.
- `--onchain`: Specifies if the contract is an on-chain contract rather than a local project.
- `--address`: Address of the on-chain contract to be analyzed.
Expand All @@ -142,6 +144,7 @@ A sample `assistant.json` config file looks like this:
"excludePaths": [] // Paths that should be excluded when parsing the directory
}, // The directory that holds the test contracts
"port": 8080, // The port that the API will be running on
"host": false, // Whether the local server should be hosted using ngrok
"includeInterfaces": false, // Whether interfaces will be included in the slither output
"includeAbstract": false, // Whether abstract contracts will be included in the slither output
"includeLibraries": false, // Whether libraries will be included in the slither output,
Expand Down
59 changes: 57 additions & 2 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,26 @@ package api
import (
"assistant/config"
"assistant/logging"
"assistant/logging/colors"
"assistant/types"
"context"
"embed"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"

"golang.ngrok.com/ngrok"
ngrokConfig "golang.ngrok.com/ngrok/config"

"github.com/fsnotify/fsnotify"
"github.com/gorilla/mux"
"github.com/rs/zerolog"
Expand Down Expand Up @@ -77,6 +84,7 @@ func (api *API) Start(projectConfig *config.ProjectConfig) {

var listener net.Listener

// Set up local server
for i := 0; i < 10; i++ {
listener, err = net.Listen("tcp", port)
if err == nil {
Expand All @@ -89,11 +97,31 @@ func (api *API) Start(projectConfig *config.ProjectConfig) {

// Stop further execution if the server failed to start
if listener == nil {
logger.Error("Failed to start server: ", err)
logger.Error("Failed to start local server: ", err)
return
}

logger.Info("Server started on port ", port[1:])
var remoteUrl string

// Host server using ngrok if specified in config
if projectConfig.Host {
logger.Info("Hosting server using ngrok")
remoteUrl, err = startNgrok(projectConfig.Port)
if err != nil {
logger.Error(err)
return
}
}

// Log server details
logger.Info("Server started successfully\n")
logger.Info("Local: http://localhost" + port)

if remoteUrl != "" {
logger.Info("Remote: ", remoteUrl)
} else {
logger.Info("Remote: Use ", colors.Green, "--host", colors.White, " or the ", colors.Green, "host", colors.White, " config option to host the server (requires the NGROK_AUTHTOKEN env variable be set)")
}

// Create a channel to receive interrupt signals
sigChan := make(chan os.Signal, 1)
Expand Down Expand Up @@ -127,6 +155,33 @@ func (api *API) Start(projectConfig *config.ProjectConfig) {
}
}

// startNgrok starts a ngrok server listening to the server at port and returns the URL
func startNgrok(port int) (string, error) {
// Obtain ngrok auth token
ngrokAuthtoken := os.Getenv("NGROK_AUTHTOKEN")
if ngrokAuthtoken == "" {
return "", fmt.Errorf("NGROK_AUTHTOKEN environment variable is not set")
}

localServerUrl, err := url.Parse("http://localhost:" + strconv.Itoa(port))
if err != nil {
return "", fmt.Errorf("unable to parse local server URL: %v", err)
}

// Create ngrok listener
ctx := context.Background()
listener, err := ngrok.ListenAndForward(ctx,
localServerUrl,
ngrokConfig.HTTPEndpoint(ngrokConfig.WithRequestHeader("ngrok-skip-browser-warning", "true")),
ngrok.WithAuthtokenFromEnv(),
)
if err != nil {
return "", fmt.Errorf("failed to create ngrok listener: %v", err)
}

return listener.URL(), nil
}

func (api *API) attachRoutes(router *mux.Router) error {
return attachFrontendRoutes(router, api.contracts, api.targetContracts, api.projectName)
}
Expand Down
2 changes: 2 additions & 0 deletions api_keys.sample.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@
#export POLYGONSCAN_API_KEY=""
#export SNOWTRACE_API_KEY=""
#export FTMSCAN_API_KEY=""

#export NGROK_AUTHTOKEN=""
17 changes: 16 additions & 1 deletion cmd/start_flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ func addStartFlags() error {
// Prevent alphabetical sorting of usage message
startCmd.Flags().SortFlags = false

// Flags
startCmd.Flags().String("config", "", "path to config file")
startCmd.Flags().String("name", "", "project name")
startCmd.Flags().Int("port", 8080, "the port the server should run on")
startCmd.Flags().Bool("host", false, "whether the local server should be hosted using ngrok")
startCmd.Flags().String("slither-args", "{}", "arguments to be passed to slither")

// Onchain config flags
Expand All @@ -38,6 +39,20 @@ func updateProjectConfigWithStartFlags(cmd *cobra.Command, projectConfig *config
}
}

if cmd.Flags().Changed("port") {
projectConfig.Port, err = cmd.Flags().GetInt("port")
if err != nil {
return err
}
}

if cmd.Flags().Changed("host") {
projectConfig.Host, err = cmd.Flags().GetBool("host")
if err != nil {
return err
}
}

if cmd.Flags().Changed("slither-args") {
slitherArgs, err := cmd.Flags().GetString("slither-args")
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ type ProjectConfig struct {
// Port describes the port that the API will be running on
Port int `json:"port"`

// Host describes whether the API should be hosted using ngrok
Host bool `json:"host"`

// IncludeInterfaces describes whether interfaces will be included in the slither output
IncludeInterfaces bool `json:"includeInterfaces"`

Expand Down
12 changes: 12 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,25 @@ require (
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-stack/stack v1.8.1 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/inconshreveable/log15 v3.0.0-testing.3+incompatible // indirect
github.com/inconshreveable/log15/v3 v3.0.0-testing.5 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jpillora/backoff v1.0.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.ngrok.com/muxado/v2 v2.0.0 // indirect
golang.ngrok.com/ngrok v1.10.0 // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/term v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
26 changes: 26 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,25 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.22.0 h1:k6HsTZ0sTnROkhS//R0O+55JgM8C4Bx7ia+JlgcnOao=
github.com/go-playground/validator/v10 v10.22.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw=
github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/inconshreveable/log15 v3.0.0-testing.3+incompatible h1:zaX5fYT98jX5j4UhO/WbfY8T1HkgVrydiDMC9PWqGCo=
github.com/inconshreveable/log15 v3.0.0-testing.3+incompatible/go.mod h1:cOaXtrgN4ScfRrD9Bre7U1thNq5RtJ8ZoP4iXVGRj6o=
github.com/inconshreveable/log15/v3 v3.0.0-testing.5 h1:h4e0f3kjgg+RJBlKOabrohjHe47D3bbAB9BgMrc3DYA=
github.com/inconshreveable/log15/v3 v3.0.0-testing.5/go.mod h1:3GQg1SVrLoWGfRv/kAZMsdyU5cp8eFc1P3cw+Wwku94=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
Expand All @@ -54,17 +64,33 @@ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
golang.ngrok.com/muxado/v2 v2.0.0 h1:bu9eIDhRdYNtIXNnqat/HyMeHYOAbUH55ebD7gTvW6c=
golang.ngrok.com/muxado/v2 v2.0.0/go.mod h1:wzxJYX4xiAtmwumzL+QsukVwFRXmPNv86vB8RPpOxyM=
golang.ngrok.com/ngrok v1.10.0 h1:Pr7WK8/oDRO1jb/qoGsL3EgqrkOzoQ8vGLYhANoMf+M=
golang.ngrok.com/ngrok v1.10.0/go.mod h1:DrWT2BcTdcnHMsP/bHEIP/Ebs0pN5VVYDpbZ3bWrwY4=
golang.org/x/crypto v0.25.0 h1:ypSNr+bnYL2YhwoMt2zPxHFmbAN1KZs/njMG3hxUp30=
golang.org/x/crypto v0.25.0/go.mod h1:T+wALwcMOSE0kXgUAnPAHqTLW+XHgcELELW8VaDgm/M=
golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.22.0 h1:BbsgPEJULsl2fV/AT3v15Mjva5yXKQDyKf+TbDz7QJk=
golang.org/x/term v0.22.0/go.mod h1:F3qCibpT5AMpCRfhfT53vVJwhLtIVHhB9XDjfFvnMI4=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

0 comments on commit a6db177

Please sign in to comment.