├── version.go ├── commands ├── exportpkg │ ├── api_test.json │ ├── api_test.go │ └── api.go ├── api │ ├── base_test.go │ ├── validate_test.go │ ├── base.go │ ├── valid_api.json │ └── validate.go ├── remote │ ├── base.go │ └── base_test.go ├── importpkg │ ├── api.go │ ├── api_test.json │ └── api_test.go └── bundle │ ├── bundle_test.go │ └── main.go ├── utils ├── nested_test.json ├── helpers.go ├── helpers_test.go ├── files.go └── files_test.go ├── main.go ├── .gitignore ├── example.conf.json ├── cmd ├── bundle.go ├── remote.go ├── build.go ├── root.go ├── import.go ├── export.go ├── test.go ├── api.go └── create.go ├── .travis.yml ├── db ├── repository_test.go └── repository.go ├── request ├── request.go ├── request_helpers.go ├── request_helpers_test.go └── request_test.go ├── ci-test.sh ├── README.md └── LICENSE.md /version.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | var VERSION string = "v0.1" 4 | -------------------------------------------------------------------------------- /commands/exportpkg/api_test.json: -------------------------------------------------------------------------------- 1 | {"Status":"Error","Message":"Not authorised","Meta":null} 2 | -------------------------------------------------------------------------------- /utils/nested_test.json: -------------------------------------------------------------------------------- 1 | { 2 | "This": "is a", 3 | "test": { 4 | "this": "is a", 5 | "nest": "See?" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/TykTechnologies/tyk-cli/cmd" 4 | 5 | func main() { 6 | cmd.Execute() 7 | } 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | main 2 | tyk-cli 3 | mykey.pem 4 | bundle.zip 5 | output 6 | mymiddleware.py 7 | manifest.json 8 | mypubkey 9 | *.cov 10 | .DS_Store 11 | *.db 12 | -------------------------------------------------------------------------------- /commands/exportpkg/api_test.go: -------------------------------------------------------------------------------- 1 | package exportpkg 2 | 3 | /* 4 | import ( 5 | "testing" 6 | ) 7 | 8 | func TestAPIs(t *testing.T) { 9 | args := []string{"12345", "http://localhost", "3000", "./api_test.json"} 10 | APIs(args) 11 | }*/ 12 | -------------------------------------------------------------------------------- /example.conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "remotes": [ 3 | { 4 | "alias": "default", 5 | "url": "http://localhost:3000", 6 | "organisation_name": "Default Org", 7 | "org_id": "12345678901234567890", 8 | "auth_token": "1234567890abcdef" 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /commands/api/base_test.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | /* 4 | TODO 5 | func TestCreate(t *testing.T) { 6 | apiId := "1234567890abcdef" 7 | API := New("api_name") 8 | API.Create() 9 | api, err := API.Find(apiId) 10 | if err != nil { 11 | log.Println(err) 12 | } 13 | if api == nil { 14 | t.Fatal(`Error: API was not created`) 15 | } 16 | }*/ 17 | -------------------------------------------------------------------------------- /commands/remote/base.go: -------------------------------------------------------------------------------- 1 | package remote 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | ) 7 | 8 | func List(w io.Writer, conf []interface{}, verbose bool) { 9 | for _, remote := range conf { 10 | remote := remote.(map[string]interface{}) 11 | if verbose { 12 | fmt.Fprintf(w, "%v - %v\n", remote["alias"], remote["url"]) 13 | } else { 14 | fmt.Fprintf(w, "%v\n", remote["alias"]) 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /cmd/bundle.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | ) 6 | 7 | // bundleCmd represents the bundle command 8 | var bundleCmd = &cobra.Command{ 9 | Use: "bundle", 10 | Short: "Manage plugin bundles", 11 | Long: `This module lets you manage Tyk plugin bundles.`, 12 | Run: func(cmd *cobra.Command, args []string) { 13 | cmd.Usage() 14 | }, 15 | } 16 | 17 | func init() { 18 | RootCmd.AddCommand(bundleCmd) 19 | } 20 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | sudo: false 3 | 4 | notifications: 5 | on_success: never 6 | on_failure: always 7 | 8 | matrix: 9 | include: 10 | - go: 1.7.x 11 | - go: 1.8.x 12 | env: LATEST_GO=true 13 | 14 | install: 15 | - go get golang.org/x/tools/cover 16 | - go get -u golang.org/x/tools/cmd/goimports github.com/{wadey/gocovmerge,mattn/goveralls} 17 | - go get -d -v ./... 18 | - go build -v ./... 19 | 20 | script: 21 | - ./ci-test.sh 22 | - if [[ $LATEST_GO ]]; then goveralls -coverprofile=<(gocovmerge *.cov); fi 23 | -------------------------------------------------------------------------------- /utils/helpers.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | ) 7 | 8 | // SingleOrListIntf function converts map[string]interface{} objects into an interface slice 9 | func MapToIntfSlice(fileMap map[string]interface{}, key string) []interface{} { 10 | var interfaceSlice []interface{} 11 | if fileMap[key] == nil { 12 | interfaceSlice = append(interfaceSlice, fileMap) 13 | } else { 14 | interfaceSlice = fileMap[key].([]interface{}) 15 | } 16 | return interfaceSlice 17 | } 18 | 19 | // Print a message to an io.Writer 20 | func PrintMessage(w io.Writer, message string) { 21 | fmt.Fprintln(w, message) 22 | } 23 | -------------------------------------------------------------------------------- /cmd/remote.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/spf13/cobra" 7 | 8 | "github.com/TykTechnologies/tyk-cli/commands/remote" 9 | "github.com/TykTechnologies/tyk-cli/utils" 10 | ) 11 | 12 | var verbose bool 13 | var remoteCmd = &cobra.Command{ 14 | Use: "remote", 15 | Short: "Select a remote", 16 | Run: func(cmd *cobra.Command, args []string) { 17 | conf := utils.ParseJSONFile("example.conf.json")["remotes"].([]interface{}) 18 | remote.List(os.Stdout, conf, verbose) 19 | }, 20 | } 21 | 22 | func init() { 23 | RootCmd.AddCommand(remoteCmd) 24 | remoteCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "List available remotes and URLs") 25 | } 26 | -------------------------------------------------------------------------------- /db/repository_test.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestOpenDB(t *testing.T) { 8 | bdb, err := OpenDB("test.db", 0666, false) 9 | if err != nil { 10 | t.Fatal(err) 11 | } else if bdb == nil { 12 | t.Fatal("expected db") 13 | } 14 | 15 | if bdb.IsReadOnly() { 16 | bdb.Close() 17 | t.Fatal("expected db to be writable") 18 | } 19 | 20 | if err = bdb.Close(); err != nil { 21 | t.Fatal(err) 22 | } 23 | } 24 | 25 | func TestOpenDBIfReadOnly(t *testing.T) { 26 | bdb, err := OpenDB("test.db", 0666, true) 27 | if err != nil { 28 | t.Fatal(err) 29 | } else if bdb == nil { 30 | t.Fatal("expected db") 31 | } 32 | 33 | if !bdb.IsReadOnly() { 34 | bdb.Close() 35 | t.Fatal("expected db to be read-only") 36 | } 37 | if err = bdb.Close(); err != nil { 38 | t.Fatal(err) 39 | } 40 | } 41 | 42 | // TODO 43 | //func TestAddRecord(t *testing.T){} 44 | -------------------------------------------------------------------------------- /cmd/build.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/spf13/cobra" 7 | 8 | "github.com/TykTechnologies/tyk-cli/commands/bundle" 9 | ) 10 | 11 | var buildOutput, key string 12 | var skipSigning bool 13 | 14 | var buildCmd = &cobra.Command{ 15 | Use: "build", 16 | Short: "Builds a plugin bundle", 17 | Long: `This command will create a bundle, it will take a manifest file and its specified files as input.`, 18 | Run: func(cmd *cobra.Command, args []string) { 19 | err := bundle.Bundle("build", buildOutput, key, &skipSigning) 20 | if err != nil { 21 | fmt.Println("Error:", err) 22 | } 23 | }, 24 | } 25 | 26 | func init() { 27 | bundleCmd.AddCommand(buildCmd) 28 | 29 | buildCmd.PersistentFlags().StringVarP(&buildOutput, "output", "o", "", "Output file") 30 | buildCmd.PersistentFlags().StringVarP(&key, "key", "k", "", "Key for bundle signature") 31 | buildCmd.PersistentFlags().BoolVarP(&skipSigning, "skip-signing", "y", false, "Skip bundle signing") 32 | } 33 | -------------------------------------------------------------------------------- /cmd/root.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/spf13/cobra" 8 | "github.com/spf13/viper" 9 | ) 10 | 11 | var cfgFile string 12 | 13 | // RootCmd represents the base command when called without any subcommands 14 | var RootCmd = &cobra.Command{ 15 | Use: "tyk-cli", 16 | Short: "Tyk CLI utility.", 17 | Long: `Tyk CLI utility.`, 18 | } 19 | 20 | // Execute adds all child commands to the root command sets flags appropriately. 21 | func Execute() { 22 | if err := RootCmd.Execute(); err != nil { 23 | fmt.Println(err) 24 | os.Exit(-1) 25 | } 26 | } 27 | 28 | func init() { 29 | cobra.OnInitialize(initConfig) 30 | } 31 | 32 | func initConfig() { 33 | if cfgFile != "" { 34 | viper.SetConfigFile(cfgFile) 35 | } 36 | 37 | viper.SetConfigName(".tyk-cli") 38 | viper.AddConfigPath("$HOME") 39 | viper.AutomaticEnv() 40 | 41 | if err := viper.ReadInConfig(); err == nil { 42 | fmt.Println("Using config file:", viper.ConfigFileUsed()) 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /request/request.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "net/http" 7 | "time" 8 | ) 9 | 10 | // Request struct used to set parameters for a HTTP request object 11 | type Request struct { 12 | Authorisation string 13 | Domain string 14 | Port string 15 | Client *http.Client 16 | } 17 | 18 | // New function used initialise HTTP request objects 19 | func New(auth, dom, prt string) *Request { 20 | return &Request{auth, checkDomain(dom), prt, 21 | &http.Client{Timeout: 10 * time.Second}} 22 | } 23 | 24 | // FullRequest function is used to generate a HTTP request with headers 25 | func (request *Request) FullRequest(requestType string, path string, payload []byte) (*http.Request, error) { 26 | url := fmt.Sprintf("%s:%s%s", request.Domain, request.Port, path) 27 | req, err := http.NewRequest(requestType, url, bytes.NewBuffer(payload)) 28 | req.Header.Add("Content-Type", "application/json") 29 | req.Header.Add("Authorization", request.Authorisation) 30 | 31 | return req, err 32 | } 33 | -------------------------------------------------------------------------------- /cmd/import.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | 6 | "github.com/TykTechnologies/tyk-cli/commands/importpkg" 7 | ) 8 | 9 | var input string 10 | 11 | var importCmd = &cobra.Command{ 12 | Use: "import", 13 | Short: "Import API definitions", 14 | Long: `This module lets you import previously exported API definitions from a JSON file.`, 15 | Run: func(cmd *cobra.Command, args []string) { 16 | args = []string{key, domain, port, input} 17 | importType := map[string]func([]string){ 18 | "api": importpkg.APIs, 19 | } 20 | importType[cmd.Parent().Name()](args) 21 | }, 22 | } 23 | 24 | func init() { 25 | apiCmd.AddCommand(importCmd) 26 | 27 | importCmd.Flags().StringVarP(&key, "key", "k", "", "Secret Key for the Dashboard API") 28 | importCmd.Flags().StringVarP(&domain, "domain", "d", "", "Domain name for your Dashboard") 29 | importCmd.Flags().StringVarP(&port, "port", "p", "", "Port number for your Dashboard") 30 | importCmd.Flags().StringVarP(&input, "input", "i", "", "Input file name for your JSON string") 31 | } 32 | -------------------------------------------------------------------------------- /ci-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | MATRIX=( 6 | "" 7 | ) 8 | 9 | show() { 10 | echo "$@" >&2 11 | eval "$@" 12 | } 13 | 14 | fatal() { 15 | echo "$@" >&2 16 | exit 1 17 | } 18 | 19 | PKGS="$(go list ./... | grep -v /vendor/)" 20 | 21 | i=0 22 | 23 | for pkg in $PKGS; do 24 | for opts in "${MATRIX[@]}"; do 25 | show go test -timeout 30s -v -coverprofile=test-$i.cov $opts $pkg \ 26 | || fatal "go test errored" 27 | let i++ || true 28 | done 29 | done 30 | 31 | if [[ ! $LATEST_GO ]]; then 32 | echo "Skipping linting and coverage report" 33 | exit 0 34 | fi 35 | 36 | for opts in "${MATRIX[@]}"; do 37 | show go vet -v $opts $PKGS || fatal "go vet errored" 38 | done 39 | 40 | GOFILES=$(find * -name '*.go' -not -path 'vendor/*') 41 | 42 | FMT_FILES="$(gofmt -s -l $GOFILES)" 43 | if [[ -n $FMT_FILES ]]; then 44 | fatal "Run 'gofmt -s -w' on these files:\n$FMT_FILES" 45 | fi 46 | 47 | IMP_FILES="$(goimports -local github.com/TykTechnologies -l $GOFILES)" 48 | if [[ -n $IMP_FILES ]]; then 49 | fatal "Run 'goimports -local github.com/TykTechnologies -w' on these files:\n$IMP_FILES" 50 | fi 51 | -------------------------------------------------------------------------------- /cmd/export.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "github.com/spf13/cobra" 5 | 6 | "github.com/TykTechnologies/tyk-cli/commands/exportpkg" 7 | ) 8 | 9 | var domain, port, output, id string 10 | 11 | var exportCmd = &cobra.Command{ 12 | Use: "export", 13 | Short: "Export API definitions", 14 | Long: `This module lets you export API definitions and output to a JSON file`, 15 | Run: func(cmd *cobra.Command, args []string) { 16 | args = []string{id, key, domain, port, output} 17 | exportType := map[string]func([]string){ 18 | "api": exportpkg.APIs, 19 | } 20 | exportType[cmd.Parent().Name()](args) 21 | }, 22 | } 23 | 24 | func init() { 25 | apiCmd.AddCommand(exportCmd) 26 | 27 | exportCmd.Flags().StringVarP(&id, "id", "i", "", "API ID") 28 | exportCmd.Flags().StringVarP(&key, "key", "k", "", "Secret Key for the Dashboard API") 29 | exportCmd.Flags().StringVarP(&domain, "domain", "d", "", "Domain name for your Dashboard") 30 | exportCmd.Flags().StringVarP(&port, "port", "p", "", "Port number for your Dashboard") 31 | exportCmd.Flags().StringVarP(&output, "output", "o", "", "Output file name for your JSON string") 32 | } 33 | -------------------------------------------------------------------------------- /commands/importpkg/api.go: -------------------------------------------------------------------------------- 1 | package importpkg 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "log" 7 | "os" 8 | 9 | "github.com/TykTechnologies/tyk-cli/request" 10 | "github.com/TykTechnologies/tyk-cli/utils" 11 | ) 12 | 13 | // Apis is a public function for importing APIs 14 | func APIs(args []string) { 15 | if len(args) == 4 { 16 | call := request.New(args[0], args[1], args[2]) 17 | inputFile := args[3] 18 | fileMap := utils.ParseJSONFile(inputFile) 19 | apis := utils.MapToIntfSlice(fileMap, "apis") 20 | generateAPIDef(apis, call) 21 | } 22 | } 23 | 24 | func generateAPIDef(apis []interface{}, call *request.Request) { 25 | var definition map[string]interface{} 26 | for i := range apis { 27 | definition = map[string]interface{}{ 28 | "api_definition": apis[i].(map[string]interface{})["api_definition"], 29 | } 30 | postAPI(definition, "/api/apis", call) 31 | } 32 | } 33 | 34 | func postAPI(definition map[string]interface{}, path string, call *request.Request) { 35 | api, err := json.Marshal(definition) 36 | if err != nil { 37 | log.Println(err) 38 | } 39 | req, err := call.FullRequest("POST", path, api) 40 | resp, err := call.Client.Do(req) 41 | if err != nil { 42 | fmt.Println(err) 43 | return 44 | } 45 | os.Stdout.Write(request.OutputResponse(resp)) 46 | } 47 | -------------------------------------------------------------------------------- /commands/remote/base_test.go: -------------------------------------------------------------------------------- 1 | package remote 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | ) 7 | 8 | var remotes []interface{} = []interface{}{ 9 | map[string]interface{}{ 10 | "alias": "default", 11 | "url": "http://localhost:3000", 12 | "organisation_name": "Default Org", 13 | "org_id": "12345678901234567890", 14 | "auth_token": "1234567890abcdef", 15 | }, 16 | map[string]interface{}{ 17 | "alias": "catChannel", 18 | "url": "http://localhost:3333", 19 | "organisation_name": "cat Org", 20 | "org_id": "12345678901234567891", 21 | "auth_token": "1234567890abcdef", 22 | }, 23 | } 24 | 25 | func TestList(t *testing.T) { 26 | var buf bytes.Buffer 27 | List(&buf, remotes, false) 28 | result := buf.String() 29 | expectedResult := "default\ncatChannel\n" 30 | if result != expectedResult { 31 | t.Fatalf("Error - expected %v, got %v", expectedResult, result) 32 | } 33 | } 34 | 35 | func TestListVerbose(t *testing.T) { 36 | var buf bytes.Buffer 37 | List(&buf, remotes, true) 38 | result := buf.String() 39 | expectedResult := "default - http://localhost:3000\ncatChannel - http://localhost:3333\n" 40 | if result != expectedResult { 41 | t.Fatalf("Error - expected %v, got %v", expectedResult, result) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /request/request_helpers.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "io" 7 | "log" 8 | "net/http" 9 | "os" 10 | "regexp" 11 | 12 | "github.com/TykTechnologies/tyk-cli/utils" 13 | ) 14 | 15 | // Generate JSON string from io.ReadClosers like the http.Response Body 16 | func GenerateJSON(reader io.ReadCloser) string { 17 | buf := new(bytes.Buffer) 18 | buf.ReadFrom(reader) 19 | return buf.String() 20 | } 21 | 22 | // CheckDomain function checks the format of the domain that is input 23 | func checkDomain(inputString string) string { 24 | if !isProtocolPresent(inputString) { 25 | utils.PrintMessage(os.Stdout, "Please add a protocol to your domain") 26 | os.Exit(-1) 27 | } 28 | return inputString 29 | } 30 | 31 | func isProtocolPresent(arg string) bool { 32 | matched, _ := regexp.MatchString("(http|https)://", arg) 33 | return matched 34 | } 35 | 36 | // OutputResponse function outputs the body of a response to stdout 37 | func OutputResponse(resp *http.Response) []byte { 38 | defer resp.Body.Close() 39 | var respBody map[string]interface{} 40 | err := json.NewDecoder(resp.Body).Decode(&respBody) 41 | if err != nil { 42 | log.Println(err) 43 | } 44 | output, err := json.MarshalIndent(respBody, "", " ") 45 | if err != nil { 46 | log.Fatal(err) 47 | } 48 | return append(output, '\n') 49 | } 50 | -------------------------------------------------------------------------------- /utils/helpers_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "reflect" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | func TestMapToIntfSlice(t *testing.T) { 11 | expectedResult := []interface{}{ 12 | map[string]interface{}{ 13 | "id": 1, 14 | "name": "Lucrezia Purrgia", 15 | }, 16 | map[string]interface{}{ 17 | "id": 2, 18 | "name": "Snowball", 19 | }, 20 | } 21 | petshop := map[string]interface{}{ 22 | "cats": expectedResult, 23 | "dogs": "n/a", 24 | } 25 | result := MapToIntfSlice(petshop, "cats") 26 | if !reflect.DeepEqual(result, expectedResult) { 27 | t.Fatalf("Expected %v, got %v", expectedResult, result) 28 | } 29 | } 30 | 31 | func TestMapToIntfSliceSingle(t *testing.T) { 32 | cat := map[string]interface{}{ 33 | "id": 1, 34 | "name": "Lucrezia Purrgia", 35 | } 36 | expectedResult := []interface{}{cat} 37 | result := MapToIntfSlice(cat, "cats") 38 | if !reflect.DeepEqual(result, expectedResult) { 39 | t.Fatalf("Expected %v, got %v", expectedResult, result) 40 | } 41 | } 42 | 43 | func TestPrintMessage(t *testing.T) { 44 | var resultBuffer bytes.Buffer 45 | message := "Cats" 46 | PrintMessage(&resultBuffer, message) 47 | expectedResult := strings.TrimSpace(message) 48 | result := strings.TrimSpace(resultBuffer.String()) 49 | if result != expectedResult { 50 | t.Fatalf("Expected: %v, got: %v", expectedResult, result) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /commands/exportpkg/api.go: -------------------------------------------------------------------------------- 1 | package exportpkg 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/http" 7 | "os" 8 | 9 | "github.com/TykTechnologies/tyk-cli/request" 10 | "github.com/TykTechnologies/tyk-cli/utils" 11 | ) 12 | 13 | // Apis is a public function for exporting APIs to a specified JSON file 14 | func APIs(args []string) { 15 | var ( 16 | err error 17 | req *http.Request 18 | call *request.Request 19 | ) 20 | switch len(args) { 21 | case 4: 22 | call = request.New(args[0], args[1], args[2]) 23 | req, err = call.FullRequest("GET", "/api/apis", nil) 24 | case 5: 25 | call = request.New(args[1], args[2], args[3]) 26 | path := fmt.Sprintf("/api/apis/%s", args[0]) 27 | req, err = call.FullRequest("GET", path, nil) 28 | } 29 | if err != nil { 30 | log.Fatal(err) 31 | } 32 | resp, err := call.Client.Do(req) 33 | if err != nil { 34 | log.Println(err) 35 | } 36 | if resp.StatusCode != 200 { 37 | fmt.Println(resp.Status) 38 | os.Exit(-1) 39 | } 40 | outputFile := args[4] 41 | if err != nil { 42 | log.Println(err) 43 | } 44 | exportResponse(resp, outputFile) 45 | } 46 | 47 | func exportResponse(resp *http.Response, file string) { 48 | defer resp.Body.Close() 49 | jsonString := request.GenerateJSON(resp.Body) 50 | absPath := utils.HandleFilePath(file) 51 | f, err := os.Create(absPath) 52 | if err != nil { 53 | return 54 | } 55 | defer f.Close() 56 | f.WriteString(jsonString) 57 | } 58 | -------------------------------------------------------------------------------- /utils/files.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "log" 8 | "os" 9 | "path/filepath" 10 | "strings" 11 | ) 12 | 13 | // ParseJSONFile function converts the contents of a JSON file into a nested map 14 | func ParseJSONFile(inputFile string) map[string]interface{} { 15 | var m map[string]interface{} 16 | file, err := ioutil.ReadFile(HandleFilePath(inputFile)) 17 | if err != nil { 18 | log.Fatal("JSON file not found") 19 | } 20 | if err := json.Unmarshal(file, &m); err != nil { 21 | log.Fatalf("File error: %v\n", err) 22 | } 23 | return m 24 | } 25 | 26 | // HandleFilePath function handles special characters in file paths 27 | func HandleFilePath(file string) string { 28 | homepath := fmt.Sprintf("%s/", os.Getenv("HOME")) 29 | replacer := strings.NewReplacer("~/", homepath) 30 | filtered := replacer.Replace(file) 31 | abs, _ := filepath.Abs(filtered) 32 | return abs 33 | } 34 | 35 | // MkdirPFile will create a file in a parent directory if file/directory 36 | // doesn't already exist 37 | func MkdirPFile(filePath string) { 38 | if _, err := os.Stat(filePath); os.IsNotExist(err) && filePath != "" { 39 | dir := filepath.Dir(filePath) 40 | if len(dir) > 1 { 41 | err = os.MkdirAll(dir, os.ModePerm) 42 | if err != nil { 43 | log.Fatal(err) 44 | } 45 | } 46 | 47 | _, err = os.Create(filePath) 48 | if err != nil { 49 | log.Fatal(err) 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /commands/api/validate_test.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/TykTechnologies/tyk-cli/utils" 7 | ) 8 | 9 | type ValidJSONTest struct { 10 | input map[string]interface{} 11 | output bool 12 | } 13 | 14 | func TestIsValidJSON(t *testing.T) { 15 | validAPI := utils.ParseJSONFile("valid_api.json") 16 | onlyAPIDef := validAPI["api_definition"].(map[string]interface{}) 17 | missingAPIDef := validAPI 18 | delete(missingAPIDef, "api_definition") 19 | 20 | tests := []ValidJSONTest{ 21 | {utils.ParseJSONFile("valid_api.json"), true}, 22 | {onlyAPIDef, false}, 23 | {missingAPIDef, false}, 24 | {nil, false}, 25 | } 26 | for _, test := range tests { 27 | result := isValidJSON(test.input) 28 | if result != test.output { 29 | t.Fatalf(`Unexpected return value. Expected: "%v", got : "%v"`, test.output, result) 30 | } 31 | } 32 | } 33 | 34 | type ValidPathTest struct { 35 | input string 36 | output string 37 | } 38 | 39 | func TestHandleValidationPath(t *testing.T) { 40 | tests := []ValidPathTest{ 41 | {"Object->Key[api_definition].Value->String", "[api_definition]"}, 42 | {"Object->Key[api_definition].Value->Object->Key[org_id].Value->String", "[api_definition][org_id]"}, 43 | {"Object->Key[api_definition].Value->Object->Key[org_id].Value->Number", "[api_definition][org_id]"}, 44 | {"Object->Key[api_definition].Value->Object->Key[org].Value->Object->Key[id].Value->Number", "[api_definition][org][id]"}, 45 | {"", ""}, 46 | } 47 | for _, test := range tests { 48 | result := handleValidationPath(test.input) 49 | if result != test.output { 50 | t.Fatalf(`Unexpected return value. Expected: "%v", got : "%v"`, test.output, result) 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tyk-cli 2 | 3 | Tyk CLI utility. 4 | 5 | [![Build Status](https://travis-ci.org/TykTechnologies/tyk-cli.svg?branch=master)](https://travis-ci.org/TykTechnologies/tyk-cli) 6 | [![Coverage Status](https://coveralls.io/repos/github/TykTechnologies/tyk-cli/badge.svg?branch=master)](https://coveralls.io/github/TykTechnologies/tyk-cli?branch=master) 7 | 8 | **Note:** Starting on Tyk Gateway v2.8, the bundle command is included as part of the gateway binary so it's no longer required to install `tyk-cli` as a separate tool, see [here](https://tyk.io/docs/plugins/rich-plugins/plugin-bundles/#getting-the-bundler-tool) for more details. 9 | 10 | ## Install 11 | 12 | go get -u github.com/TykTechnologies/tyk-cli 13 | 14 | ## Available modules 15 | 16 | ### Bundle 17 | 18 | This module provides useful commands for working with custom middleware bundles. The most basic command is `build`: 19 | 20 | Assuming you're on a directory that contains your required bundle files and a **bundle manifest**, you could run: 21 | 22 | tyk-cli bundle build -output bundle-latest.zip 23 | 24 | If no `-output` flag is present, the bundle will be stored as `bundle.zip` in the current working directory. 25 | 26 | The bundle will contain a `manifest.json` with the computed checksum and signature. 27 | 28 | By default, the bundles are signed, if no private key is specified, the program will prompt for a confirmation. If you need to force this behavior you may use the `-y` flag: 29 | 30 | tyk-cli bundle build -output bundle-latest.zip -y 31 | 32 | If you follow the standard behavior and need to sign your bundles, provide the path to your private key using the `-key` flag: 33 | 34 | tyk-cli bundle build -output bundle-latest.zip -key mykey.pem 35 | 36 | ## Docs 37 | 38 | For more information about rich plugins, check the documentation [here](https://tyk.io/tyk-documentation/customise-tyk/plugins/). 39 | 40 | ## License 41 | 42 | Tyk is released under the MPL v2.0 please see the [LICENSE.md](LICENSE.md) file for a full version of the license. 43 | -------------------------------------------------------------------------------- /cmd/test.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "os" 5 | "text/template" 6 | 7 | "github.com/spf13/cobra" 8 | 9 | "github.com/TykTechnologies/tyk-cli/commands/api" 10 | ) 11 | 12 | var testCmd = &cobra.Command{ 13 | Use: "test", 14 | Short: "Validate API definitions", 15 | Long: `This is a subcommand of the 'api' command and can be used to test the validaity of an API.`, 16 | Run: func(cmd *cobra.Command, args []string) { 17 | id := args[0] 18 | api.Validate(id) 19 | }, 20 | } 21 | 22 | func contains(args []string, item string) bool { 23 | for _, arg := range args { 24 | if arg == item { 25 | return true 26 | } 27 | } 28 | return false 29 | } 30 | 31 | func init() { 32 | apiCmd.AddCommand(testCmd) 33 | } 34 | 35 | func testUsage(cmd *cobra.Command) { 36 | cobra.AddTemplateFuncs(template.FuncMap{ 37 | "add": func(i int, j int) int { 38 | return i + j 39 | }, 40 | "parent": func() string { 41 | return os.Args[1] 42 | }, 43 | }) 44 | cmd.SetUsageTemplate(`Usage:{{if .Runnable}} 45 | tyk-cli {{ parent }} [ID] test {{end}}{{if gt .Aliases 0}} 46 | Aliases: 47 | {{.NameAndAliases}} 48 | {{end}}{{if .HasExample}} 49 | Examples: 50 | {{ .Example }}{{end}}{{if .HasAvailableSubCommands}} 51 | Available Subcommands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}{{ if (eq .Name "test") }} 52 | [ID] {{rpad .Name .NamePadding }} {{.Short}}{{ else }} 53 | {{rpad .Name (add .NamePadding 5) }} {{.Short}}{{end}}{{end}}{{end}} 54 | {{ end }}{{if .HasAvailableLocalFlags}} 55 | Flags: 56 | {{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}} 57 | Global Flags: 58 | {{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}} 59 | Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} 60 | {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} 61 | Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} 62 | `) 63 | cmd.Usage() 64 | } 65 | -------------------------------------------------------------------------------- /commands/api/base.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "strings" 7 | 8 | "github.com/boltdb/bolt" 9 | uuid "github.com/satori/go.uuid" 10 | 11 | "github.com/TykTechnologies/tyk-cli/db" 12 | "github.com/TykTechnologies/tyk/apidef" 13 | ) 14 | 15 | type APIDef struct { 16 | id string 17 | name string 18 | item db.Item 19 | APIModel APIModel 20 | APIDefinition apidef.APIDefinition 21 | } 22 | 23 | type APIModel struct { 24 | schemaPath string 25 | } 26 | 27 | func (api *APIDef) setAPIDefinition() { 28 | api.APIDefinition.APIID = api.Id() 29 | api.APIDefinition.Name = api.Name() 30 | } 31 | 32 | func New(name string) *APIDef { 33 | api := APIDef{} 34 | id, _ := uuid.NewV4() 35 | api.id = strings.Replace(id.String(), "-", "", -1) 36 | api.name = name 37 | return &api 38 | } 39 | 40 | func (api *APIDef) Id() string { 41 | return api.id 42 | } 43 | 44 | func (api *APIDef) Name() string { 45 | return api.name 46 | } 47 | 48 | func (api *APIDef) BucketName() string { 49 | return "apis" 50 | } 51 | 52 | func (api *APIDef) Group() string { 53 | return "API" 54 | } 55 | 56 | func (api *APIDef) RecordData() interface{} { 57 | api.setAPIDefinition() 58 | type rec struct { 59 | APIModel APIModel `json:"api_model"` 60 | APIDefinition apidef.APIDefinition `json:"api_definition"` 61 | } 62 | return rec{api.APIModel, api.APIDefinition} 63 | } 64 | 65 | // Create is a public function for creating staged APIs 66 | func (api *APIDef) Create(bdb *bolt.DB) error { 67 | return bdb.Update(func(tx *bolt.Tx) error { 68 | return db.AddRecord(tx, api) 69 | }) 70 | } 71 | 72 | // Find is a public function for finding staged APIs 73 | func (apis *APIDef) Find(bdb *bolt.DB, id string) (interface{}, error) { 74 | var item interface{} 75 | err := bdb.View(func(tx *bolt.Tx) error { 76 | collection := tx.Bucket([]byte(apis.BucketName())) 77 | member := collection.Get([]byte(id)) 78 | return json.Unmarshal(member, &item) 79 | }) 80 | if item == nil { 81 | return nil, fmt.Errorf("API not found") 82 | } 83 | return item, err 84 | } 85 | -------------------------------------------------------------------------------- /db/repository.go: -------------------------------------------------------------------------------- 1 | package db 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | "os" 7 | "path/filepath" 8 | 9 | "github.com/boltdb/bolt" 10 | 11 | "github.com/TykTechnologies/tyk-cli/utils" 12 | ) 13 | 14 | type Item struct { 15 | id string 16 | name string 17 | } 18 | 19 | // Record interface for all objects in the DB 20 | type Record interface { 21 | Id() string 22 | Name() string 23 | BucketName() string 24 | Group() string 25 | RecordData() interface{} 26 | Create(bdb *bolt.DB) error 27 | Find(bdb *bolt.DB, id string) (interface{}, error) 28 | } 29 | 30 | func (item *Item) Id() string { 31 | return item.id 32 | } 33 | 34 | func (item *Item) Name() string { 35 | return item.name 36 | } 37 | 38 | func (item *Item) BucketName() string { 39 | return "items" 40 | } 41 | 42 | func (item *Item) Group() string { 43 | return "Item" 44 | } 45 | 46 | func (item *Item) RecordData() interface{} { 47 | return item 48 | } 49 | 50 | func (item *Item) Create(bdb *bolt.DB) error { 51 | log.Fatal("Please implement me") 52 | return nil 53 | } 54 | 55 | // Find is a public function for finding staged APIs 56 | func (item *Item) Find(bdb *bolt.DB, id string) (interface{}, error) { 57 | log.Fatal("Please implement me") 58 | return nil, nil 59 | } 60 | 61 | // OpenDB is a public function used to open the Database 62 | func OpenDB(filename string, permission os.FileMode, readOnly bool) (*bolt.DB, error) { 63 | dbFile := filepath.Join( 64 | os.Getenv("GOPATH"), 65 | "src", 66 | "github.com", 67 | "TykTechnologies", 68 | "tyk-cli", 69 | "db", 70 | filename, 71 | ) 72 | utils.MkdirPFile(dbFile) 73 | options := &bolt.Options{ReadOnly: readOnly} 74 | 75 | bdb, err := bolt.Open(dbFile, permission, options) 76 | return bdb, err 77 | } 78 | 79 | // AddRecord function adds records to BoltDB 80 | func AddRecord(tx *bolt.Tx, r Record) error { 81 | collection, err := tx.CreateBucketIfNotExists([]byte(r.BucketName())) 82 | if err != nil { 83 | log.Fatal(err) 84 | } 85 | member, err := json.Marshal(r.RecordData()) 86 | if err != nil { 87 | log.Fatal(err) 88 | } 89 | return collection.Put([]byte(r.Id()), member) 90 | } 91 | -------------------------------------------------------------------------------- /utils/files_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "os/exec" 7 | "path/filepath" 8 | "reflect" 9 | "testing" 10 | ) 11 | 12 | func TestParseJSONFile(t *testing.T) { 13 | expectedResult := map[string]interface{}{ 14 | "This": "is a", 15 | "test": map[string]interface{}{ 16 | "this": "is a", "nest": "See?", 17 | }, 18 | } 19 | result := ParseJSONFile("./nested_test.json") 20 | if !reflect.DeepEqual(result, expectedResult) { 21 | t.Fatalf("Expected %v, got %v", expectedResult, result) 22 | } 23 | } 24 | 25 | func TestParseJSONFileOutputNotFoundError(t *testing.T) { 26 | expectedResult := "JSON file not found" 27 | if os.Getenv("ERRS") == "1" { 28 | ParseJSONFile("./json_not_found.json") 29 | return 30 | } 31 | cmd := exec.Command(os.Args[0], "-test.run=TestParseJSONFileOutputNotFoundError") 32 | cmd.Env = append(os.Environ(), "ERRS=1") 33 | err := cmd.Run() 34 | if e, ok := err.(*exec.ExitError); ok && !e.Success() { 35 | return 36 | } else { 37 | t.Fatalf("Expected error: %v", expectedResult) 38 | } 39 | } 40 | 41 | func TestHandleFilePathReturnsPath(t *testing.T) { 42 | expectedResult := "/home/boomy/Documents/goStuff" 43 | result := HandleFilePath("/home/boomy/Documents/goStuff") 44 | if result != expectedResult { 45 | t.Fatalf("Expected %s, got %s", expectedResult, result) 46 | } 47 | } 48 | 49 | func TestHandleFilePathConvertsTilde(t *testing.T) { 50 | expectedResult := fmt.Sprintf("%s/Documents/goStuff", os.Getenv("HOME")) 51 | result := HandleFilePath("~/Documents/goStuff") 52 | if result != expectedResult { 53 | t.Fatalf("Expected %s, got %s", expectedResult, result) 54 | } 55 | } 56 | 57 | func TestMkdirPFile(t *testing.T) { 58 | newFiles := []string{ 59 | "someFolder/someFile.txt", 60 | "someFolder/someFile2.txt", 61 | "some/folder/some/file.txt", 62 | "file.txt", 63 | } 64 | for _, file := range newFiles { 65 | MkdirPFile(file) 66 | if _, err := os.Stat(file); os.IsNotExist(err) { 67 | t.Fatalf("Expected to find '%s', instead file not found", file) 68 | } 69 | os.Remove(file) 70 | parent := file 71 | for len(filepath.Dir(parent)) > 1 { 72 | parent = filepath.Dir(parent) 73 | } 74 | os.RemoveAll(parent) 75 | } 76 | } 77 | 78 | func TestMkdirPFileWithNotInput(t *testing.T) { 79 | MkdirPFile("") 80 | if _, err := os.Stat(""); !os.IsNotExist(err) { 81 | t.Fatalf("Expected file not found, got %s", err) 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /cmd/api.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "text/template" 7 | 8 | "github.com/spf13/cobra" 9 | ) 10 | 11 | var apiCmd = &cobra.Command{ 12 | Use: "api", 13 | Short: "Manage API definitions", 14 | Long: `This module lets you manage API definitions using the Dashboard API.`, 15 | Run: func(cmd *cobra.Command, args []string) { 16 | apiUsage(cmd, true) 17 | args = os.Args[2:] 18 | if len(args) < 1 { 19 | fmt.Errorf("need to specify api id or subcommand") 20 | apiUsage(cmd, false) 21 | return 22 | } 23 | apiId := args[0] 24 | if len(args) == 1 { 25 | fmt.Printf("selected api %s, please add subcommand\n", apiId) 26 | apiUsage(cmd, true) 27 | return 28 | } 29 | subCmd := args[1] 30 | switch subCmd { 31 | case "test": 32 | testCmd.Run(testCmd, []string{apiId}) 33 | default: 34 | fmt.Errorf("unknown api subcommand: %s", args[0]) 35 | } 36 | }, 37 | } 38 | 39 | func apiUsage(cmd *cobra.Command, isSubCmd bool) { 40 | if isSubCmd { 41 | cmd.ResetCommands() 42 | } 43 | cobra.AddTemplateFuncs(template.FuncMap{ 44 | "add": func(i int, j int) int { 45 | return i + j 46 | }, 47 | }) 48 | cmd.AddCommand(testCmd) 49 | cmd.SetUsageTemplate(`Usage:{{if .Runnable}} 50 | {{ .CommandPath}} [ID] [command]{{end}}{{if gt .Aliases 0}} 51 | Aliases: 52 | {{.NameAndAliases}} 53 | {{end}}{{if .HasExample}} 54 | Examples: 55 | {{ .Example }}{{end}}{{if .HasAvailableSubCommands}} 56 | Available Subcommands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}{{ if (eq .Name "test") }} 57 | [ID] {{rpad .Name .NamePadding }} {{.Short}}{{ else }} 58 | {{rpad .Name (add .NamePadding 5) }} {{.Short}}{{end}}{{end}}{{end}} 59 | {{ end }}{{if .HasAvailableLocalFlags}} 60 | Flags: 61 | {{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}} 62 | Global Flags: 63 | {{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}} 64 | Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} 65 | {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} 66 | Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} 67 | `) 68 | cmd.Usage() 69 | } 70 | 71 | func init() { 72 | if contains(os.Args, "test") && (contains(os.Args, "--help") || contains(os.Args, "-h")) { 73 | RootCmd.AddCommand(testCmd) 74 | testUsage(testCmd) 75 | os.Exit(-1) 76 | } else { 77 | RootCmd.AddCommand(apiCmd) 78 | apiCmd.AddCommand(testCmd) 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /cmd/create.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "os" 7 | "text/template" 8 | 9 | "github.com/spf13/cobra" 10 | 11 | "github.com/TykTechnologies/tyk-cli/commands/api" 12 | "github.com/TykTechnologies/tyk-cli/db" 13 | ) 14 | 15 | var createCmd = &cobra.Command{ 16 | Use: "create", 17 | Short: "Create new APIs.", 18 | Long: `Create new APIs.`, 19 | Run: func(cmd *cobra.Command, args []string) { 20 | args = os.Args[2:] 21 | switch len(args) { 22 | case 1: 23 | subCmdUsage(cmd, args) 24 | case 2: 25 | if args[0] == "api" { 26 | bdb, err := db.OpenDB("bolt.db", 0600, false) 27 | if err != nil { 28 | log.Fatal(err) 29 | } 30 | defer bdb.Close() 31 | name := args[1] 32 | newAPI := api.New(name) 33 | newAPI.Create(bdb) 34 | fmt.Printf("%v %v created ID %v\n", newAPI.Group(), newAPI.Name(), newAPI.Id()) 35 | } 36 | default: 37 | createAPIUsage(cmd) 38 | } 39 | }, 40 | } 41 | 42 | func subCmdUsage(cmd *cobra.Command, args []string) { 43 | switch args[0] { 44 | case "api": 45 | createAPIUsage(cmd) 46 | default: 47 | log.Println("Please implement me") 48 | } 49 | } 50 | 51 | func createAPIUsage(cmd *cobra.Command) { 52 | cobra.AddTemplateFuncs(template.FuncMap{ 53 | "add": func(i int, j int) int { 54 | return i + j 55 | }, 56 | }) 57 | cmd.SetUsageTemplate(`Usage:{{if .Runnable}} 58 | {{ .CommandPath }} api [name] {{end}}{{if gt .Aliases 0}} 59 | Aliases: 60 | {{.NameAndAliases}} 61 | {{end}}{{if .HasExample}} 62 | Examples: 63 | {{ .Example }}{{end}}{{if .HasAvailableSubCommands}} 64 | Available Subcommands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}{{ if (eq .Name "test") }} 65 | [ID] {{rpad .Name .NamePadding }} {{.Short}}{{ else }} 66 | {{rpad .Name (add .NamePadding 5) }} {{.Short}}{{end}}{{end}}{{end}} 67 | {{ end }}{{if .HasAvailableLocalFlags}} 68 | Flags: 69 | {{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}} 70 | Global Flags: 71 | {{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}} 72 | Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} 73 | {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} 74 | Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} 75 | `) 76 | cmd.Usage() 77 | } 78 | 79 | func init() { 80 | if contains(os.Args, "--help") || contains(os.Args, "-h") { 81 | createAPIUsage(createCmd) 82 | } 83 | RootCmd.AddCommand(createCmd) 84 | } 85 | -------------------------------------------------------------------------------- /commands/api/valid_api.json: -------------------------------------------------------------------------------- 1 | {"api_model":{},"api_definition":{"id":"58c2e3f60185df02ad04f418","name":"API2","slug":"api2","api_id":"2713b7afaca54fe45917d401dca5e176","org_id":"58beb1ed29129501c6a9e0bb","use_keyless":false,"use_oauth2":false,"use_openid":false,"openid_options":{"providers":[],"segregate_by_client":false},"oauth_meta":{"allowed_access_types":[],"allowed_authorize_types":[],"auth_login_redirect":""},"auth":{"use_param":false,"param_name":"","use_cookie":false,"cookie_name":"","auth_header_name":"Authorization"},"use_basic_auth":false,"enable_jwt":false,"use_standard_auth":true,"enable_coprocess_auth":false,"jwt_signing_method":"","jwt_source":"","jwt_identity_base_field":"","jwt_client_base_field":"","jwt_policy_field_name":"","notifications":{"shared_secret":"","oauth_on_keychange_url":""},"enable_signature_checking":false,"hmac_allowed_clock_skew":-1,"base_identity_provided_by":"","definition":{"location":"header","key":"x-api-version"},"version_data":{"not_versioned":true,"versions":{"Default":{"name":"Default","expires":"","paths":{"ignored":[],"white_list":[],"black_list":[]},"use_extended_paths":true,"extended_paths":{},"global_headers":{},"global_headers_remove":[],"global_size_limit":0,"override_target":""}}},"uptime_tests":{"check_list":[],"config":{"expire_utime_after":0,"service_discovery":{"use_discovery_service":false,"query_endpoint":"","use_nested_query":false,"parent_data_path":"","data_path":"","port_data_path":"","target_path":"","use_target_list":false,"cache_timeout":60,"endpoint_returns_list":false},"recheck_wait":0}},"proxy":{"preserve_host_header":false,"listen_path":"/api2/","target_url":"http://httpbin.org/","strip_listen_path":true,"enable_load_balancing":false,"target_list":[],"check_host_against_uptime_tests":false,"service_discovery":{"use_discovery_service":false,"query_endpoint":"","use_nested_query":false,"parent_data_path":"","data_path":"hostname","port_data_path":"port","target_path":"/api-slug","use_target_list":false,"cache_timeout":60,"endpoint_returns_list":false}},"disable_rate_limit":false,"disable_quota":false,"custom_middleware":{"pre":[],"post":[],"post_key_auth":[],"auth_check":{"name":"","path":"","require_session":false},"response":[],"driver":"","id_extractor":{"extract_from":"","extract_with":"","extractor_config":{}}},"custom_middleware_bundle":"","cache_options":{"cache_timeout":60,"enable_cache":true,"cache_all_safe_requests":false,"cache_response_codes":[],"enable_upstream_cache_control":false},"session_lifetime":0,"active":true,"auth_provider":{"name":"","storage_engine":"","meta":{}},"session_provider":{"name":"","storage_engine":"","meta":null},"event_handlers":{"events":{}},"enable_batch_request_support":false,"enable_ip_whitelisting":false,"allowed_ips":[],"dont_set_quota_on_create":false,"expire_analytics_after":0,"response_processors":[],"CORS":{"enable":false,"allowed_origins":[],"allowed_methods":[],"allowed_headers":[],"exposed_headers":[],"allow_credentials":false,"max_age":24,"options_passthrough":false,"debug":false},"domain":"","do_not_track":false,"tags":[],"enable_context_vars":false},"hook_references":[],"is_site":false,"sort_by":0} -------------------------------------------------------------------------------- /commands/importpkg/api_test.json: -------------------------------------------------------------------------------- 1 | {"api_model":{},"api_definition":{"id":"58c2e3f60185df02ad04f418","name":"API2","slug":"api2","api_id":"2713b7afaca54fe45917d401dca5e176","org_id":"58beb1ed29129501c6a9e0bb","use_keyless":false,"use_oauth2":false,"use_openid":false,"openid_options":{"providers":[],"segregate_by_client":false},"oauth_meta":{"allowed_access_types":[],"allowed_authorize_types":[],"auth_login_redirect":""},"auth":{"use_param":false,"param_name":"","use_cookie":false,"cookie_name":"","auth_header_name":"Authorization"},"use_basic_auth":false,"enable_jwt":false,"use_standard_auth":true,"enable_coprocess_auth":false,"jwt_signing_method":"","jwt_source":"","jwt_identity_base_field":"","jwt_client_base_field":"","jwt_policy_field_name":"","notifications":{"shared_secret":"","oauth_on_keychange_url":""},"enable_signature_checking":false,"hmac_allowed_clock_skew":-1,"base_identity_provided_by":"","definition":{"location":"header","key":"x-api-version"},"version_data":{"not_versioned":true,"versions":{"Default":{"name":"Default","expires":"","paths":{"ignored":[],"white_list":[],"black_list":[]},"use_extended_paths":true,"extended_paths":{},"global_headers":{},"global_headers_remove":[],"global_size_limit":0,"override_target":""}}},"uptime_tests":{"check_list":[],"config":{"expire_utime_after":0,"service_discovery":{"use_discovery_service":false,"query_endpoint":"","use_nested_query":false,"parent_data_path":"","data_path":"","port_data_path":"","target_path":"","use_target_list":false,"cache_timeout":60,"endpoint_returns_list":false},"recheck_wait":0}},"proxy":{"preserve_host_header":false,"listen_path":"/api2/","target_url":"http://httpbin.org/","strip_listen_path":true,"enable_load_balancing":false,"target_list":[],"check_host_against_uptime_tests":false,"service_discovery":{"use_discovery_service":false,"query_endpoint":"","use_nested_query":false,"parent_data_path":"","data_path":"hostname","port_data_path":"port","target_path":"/api-slug","use_target_list":false,"cache_timeout":60,"endpoint_returns_list":false}},"disable_rate_limit":false,"disable_quota":false,"custom_middleware":{"pre":[],"post":[],"post_key_auth":[],"auth_check":{"name":"","path":"","require_session":false},"response":[],"driver":"","id_extractor":{"extract_from":"","extract_with":"","extractor_config":{}}},"custom_middleware_bundle":"","cache_options":{"cache_timeout":60,"enable_cache":true,"cache_all_safe_requests":false,"cache_response_codes":[],"enable_upstream_cache_control":false},"session_lifetime":0,"active":true,"auth_provider":{"name":"","storage_engine":"","meta":{}},"session_provider":{"name":"","storage_engine":"","meta":null},"event_handlers":{"events":{}},"enable_batch_request_support":false,"enable_ip_whitelisting":false,"allowed_ips":[],"dont_set_quota_on_create":false,"expire_analytics_after":0,"response_processors":[],"CORS":{"enable":false,"allowed_origins":[],"allowed_methods":[],"allowed_headers":[],"exposed_headers":[],"allow_credentials":false,"max_age":24,"options_passthrough":false,"debug":false},"domain":"","do_not_track":false,"tags":[],"enable_context_vars":false},"hook_references":[],"is_site":false,"sort_by":0} -------------------------------------------------------------------------------- /request/request_helpers_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "net/http" 7 | "net/http/httptest" 8 | "os" 9 | "os/exec" 10 | "testing" 11 | 12 | "github.com/TykTechnologies/tyk-cli/utils" 13 | ) 14 | 15 | var newApiResponse = `{ 16 | "Status": "OK" 17 | "Message": "API created" 18 | "Meta": "58c6cdeb0185df02ad04f43b" 19 | }` 20 | 21 | func TestGenerateJSON(t *testing.T) { 22 | req, err := http.NewRequest("GET", "http://localhost:3000/api/apis", nil) 23 | if err != nil { 24 | t.Fatalf("Got error: %v", err) 25 | } 26 | recorder := httptest.NewRecorder() 27 | handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 28 | w.WriteHeader(http.StatusOK) 29 | w.Write([]byte(newApiResponse)) 30 | }) 31 | handler.ServeHTTP(recorder, req) 32 | expectedResult := newApiResponse 33 | result := GenerateJSON(recorder.Result().Body) 34 | if result != expectedResult { 35 | t.Errorf( 36 | "Handler returned unexpected response.\nGot:\n\t%v\nExpected:\n\t%v", 37 | result, expectedResult, 38 | ) 39 | } 40 | } 41 | 42 | func TestCheckDomain(t *testing.T) { 43 | expectedResult := "http://www.example.com" 44 | result := checkDomain("http://www.example.com") 45 | if result != expectedResult { 46 | t.Fatalf("Expected %s, got %s", expectedResult, result) 47 | } 48 | } 49 | 50 | func TestCheckDomainErrorsWithBadInput(t *testing.T) { 51 | if os.Getenv("ERRS") == "1" { 52 | checkDomain("www.example.com") 53 | return 54 | } 55 | cmd := exec.Command(os.Args[0], "-test.run=TestCheckDomainErrorsWithBadInput") 56 | cmd.Env = append(os.Environ(), "ERRS=1") 57 | err := cmd.Run() 58 | if e, ok := err.(*exec.ExitError); ok && !e.Success() { 59 | return 60 | } else { 61 | t.Fatalf("test ran with err %v, want exit status 1", err) 62 | } 63 | } 64 | 65 | func TestPrintMessage(t *testing.T) { 66 | var result, expectedResult bytes.Buffer 67 | message := "Print me" 68 | utils.PrintMessage(&result, message) 69 | fmt.Fprint(&expectedResult, message) 70 | for i := range expectedResult.String() { 71 | if expectedResult.String()[i] != result.String()[i] { 72 | t.Fatalf("Expected %v, got %v", expectedResult, result) 73 | } 74 | } 75 | } 76 | 77 | func TestIsProtocolPresentOutputsTrueIfPresent(t *testing.T) { 78 | expectedResult := true 79 | result := isProtocolPresent("http://www.example.com") 80 | if result != expectedResult { 81 | t.Fatalf("Expected %v, got %v", expectedResult, result) 82 | } 83 | } 84 | 85 | func TestIsProtocolPresentOutputsFalseIfMissing(t *testing.T) { 86 | expectedResult := false 87 | result := isProtocolPresent("/www.example.com") 88 | if result != expectedResult { 89 | t.Fatalf("Expected %v, got %v", expectedResult, result) 90 | } 91 | } 92 | 93 | func TestOutputResponse(t *testing.T) { 94 | req, err := http.NewRequest("GET", "https://httpbin.org/ip", nil) 95 | if err != nil { 96 | t.Fatalf("Got error: %v", err) 97 | } 98 | expectedResponse := `{ 99 | "origin": "5.153.234.114" 100 | } 101 | ` 102 | recorder := httptest.NewRecorder() 103 | handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 104 | w.WriteHeader(http.StatusOK) 105 | w.Write([]byte(expectedResponse)) 106 | }) 107 | handler.ServeHTTP(recorder, req) 108 | result := string(OutputResponse(recorder.Result())) 109 | if result != expectedResponse { 110 | t.Errorf( 111 | "Handler returned unexpected response.\nGot:\n%v\nExpected:\n%v", 112 | result, 113 | expectedResponse, 114 | ) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /commands/importpkg/api_test.go: -------------------------------------------------------------------------------- 1 | package importpkg 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "net/http" 8 | "net/http/httptest" 9 | "os" 10 | "testing" 11 | 12 | "github.com/TykTechnologies/tyk-cli/request" 13 | "github.com/TykTechnologies/tyk-cli/utils" 14 | ) 15 | 16 | var apiBody = `{ 17 | "api_model": {}, 18 | "api_definition": { 19 | "id": "54b53e47eba6db5c70000002", 20 | "name": "Nitrous Test", 21 | "api_id": "39d2c98be05c424371c600bd8b3e2242", 22 | "org_id": "54b53d3aeba6db5c35000002", 23 | "use_keyless": false, 24 | "use_oauth2": false, 25 | "oauth_meta": { 26 | "allowed_access_types": [], 27 | "allowed_authorize_types": [ 28 | "token" 29 | ], 30 | "auth_login_redirect": "" 31 | }, 32 | "auth": { 33 | "auth_header_name": "authorization" 34 | }, 35 | "use_basic_auth": false, 36 | "notifications": { 37 | "shared_secret": "", 38 | "oauth_on_keychange_url": "" 39 | }, 40 | "enable_signature_checking": false, 41 | "definition": { 42 | "location": "header", 43 | "key": "" 44 | }, 45 | "version_data": { 46 | "not_versioned": true, 47 | "versions": { 48 | "Default": { 49 | "name": "Default", 50 | "expires": "", 51 | "paths": { 52 | "ignored": [], 53 | "white_list": [], 54 | "black_list": [] 55 | }, 56 | "use_extended_paths": false, 57 | "extended_paths": { 58 | "ignored": [], 59 | "white_list": [], 60 | "black_list": [] 61 | } 62 | } 63 | } 64 | }, 65 | "proxy": { 66 | "listen_path": "/39d2c98be05c424371c600bd8b3e2242/", 67 | "target_url": "http://tyk.io", 68 | "strip_listen_path": true 69 | }, 70 | "custom_middleware": { 71 | "pre": null, 72 | "post": null 73 | }, 74 | "session_lifetime": 0, 75 | "active": true, 76 | "auth_provider": { 77 | "name": "", 78 | "storage_engine": "", 79 | "meta": null 80 | }, 81 | "session_provider": { 82 | "name": "", 83 | "storage_engine": "", 84 | "meta": null 85 | }, 86 | "event_handlers": { 87 | "events": {} 88 | }, 89 | "enable_batch_request_support": false, 90 | "enable_ip_whitelisting": false, 91 | "allowed_ips": [], 92 | "expire_analytics_after": 0 93 | }, 94 | "hook_references": [] 95 | }` 96 | 97 | var newApiResponse = `{ 98 | "Status": "OK" 99 | "Message": "API Created" 100 | "Meta": "5812" 101 | }` 102 | 103 | func TestPostAPI(t *testing.T) { 104 | req, err := http.NewRequest("POST", "http://localhost:3000/api/apis", bytes.NewBuffer([]byte(apiBody))) 105 | if err != nil { 106 | t.Fatalf("Got error: %v", err) 107 | } 108 | expectedResponse := newApiResponse 109 | recorder := httptest.NewRecorder() 110 | handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 111 | w.WriteHeader(http.StatusOK) 112 | w.Write([]byte(newApiResponse)) 113 | }) 114 | handler.ServeHTTP(recorder, req) 115 | 116 | call := request.New("12345", "http://localhost", "3000") 117 | var apiObj interface{} 118 | err = json.Unmarshal([]byte(apiBody), &apiObj) 119 | if err != nil { 120 | fmt.Printf("File error: %v\n", err) 121 | os.Exit(1) 122 | } 123 | postAPI(apiObj.(map[string]interface{}), "/api/apis", call) 124 | if recorder.Body.String() != expectedResponse { 125 | t.Errorf( 126 | "Handler returned unexpected response.\nGot:\n\t%v\nExpected:\n\t%v", 127 | recorder.Body.String(), 128 | expectedResponse, 129 | ) 130 | } 131 | } 132 | 133 | func TestGenereateAPIDef(t *testing.T) { 134 | call := request.New("12345", "http://localhost", "3000") 135 | var apiObj interface{} 136 | err := json.Unmarshal([]byte(apiBody), &apiObj) 137 | if err != nil { 138 | fmt.Printf("File error: %v\n", err) 139 | os.Exit(1) 140 | } 141 | apis := utils.MapToIntfSlice(apiObj.(map[string]interface{}), "apis") 142 | generateAPIDef(apis, call) 143 | } 144 | 145 | func TestAPIs(t *testing.T) { 146 | args := []string{"12345", "http://localhost", "3000", "./api_test.json"} 147 | APIs(args) 148 | } 149 | -------------------------------------------------------------------------------- /commands/bundle/bundle_test.go: -------------------------------------------------------------------------------- 1 | package bundle 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "os" 7 | "testing" 8 | 9 | "github.com/TykTechnologies/tyk/apidef" 10 | ) 11 | 12 | const ( 13 | testManifestName = "./manifest.json" 14 | testPerm = 0755 15 | testBundleName = "./bundle.zip" 16 | testBundleAltName = "./mybundle.zip" 17 | testDummyFilename = "./mymiddleware.py" 18 | ) 19 | 20 | var ( 21 | force bool 22 | err error 23 | ) 24 | 25 | func TestBundleUnknownCommand(t *testing.T) { 26 | force = true 27 | err = Bundle("unknown", "", "", &force) 28 | if err == nil { 29 | t.Fatal("Must return an error when the command doesn't exist.") 30 | } 31 | } 32 | 33 | func TestBundleBuildWithoutManifest(t *testing.T) { 34 | force = true 35 | err = Bundle("build", "", "", &force) 36 | if err == nil { 37 | t.Fatal("The manifest file doesn't exist, the build command should return an error.") 38 | } 39 | } 40 | 41 | func TestBundleBuildWithInvalidManifest(t *testing.T) { 42 | force = true 43 | noManifest := []byte("") 44 | ioutil.WriteFile(testManifestName, noManifest, testPerm) 45 | err = Bundle("build", "", "", &force) 46 | if err == nil { 47 | t.Fatal("When the manifest is invalid, the build command should return an error.") 48 | } 49 | deleteFiles([]string{testManifestName}) 50 | } 51 | 52 | func TestBundleBuildWithEmptyManifest(t *testing.T) { 53 | force = true 54 | emptyManifest := []byte("{}") 55 | ioutil.WriteFile(testManifestName, emptyManifest, testPerm) 56 | err = Bundle("build", "", "", &force) 57 | if err == nil { 58 | t.Fatal("The manifest doesn't have any hooks, the build command should return an error.") 59 | } 60 | deleteFiles([]string{testManifestName}) 61 | } 62 | 63 | func TestBundleValidateManifestWithEmptyFile(t *testing.T) { 64 | var manifest apidef.BundleManifest 65 | err = BundleValidateManifest(&manifest) 66 | if err == nil { 67 | t.Fatal("The manifest is empty (no hooks defined), the validation step should return an error.") 68 | } 69 | } 70 | 71 | func TestBundleValidateManifestWithNonExistentFile(t *testing.T) { 72 | manifest := apidef.BundleManifest{ 73 | FileList: []string{"nonexistentfile"}, 74 | } 75 | err = BundleValidateManifest(&manifest) 76 | if err == nil { 77 | t.Fatal("The manifest file references a nonexistent file, the validation step should return an error.") 78 | } 79 | } 80 | 81 | func TestBundleValidateManifestWithNoDriver(t *testing.T) { 82 | manifest := apidef.BundleManifest{ 83 | CustomMiddleware: apidef.MiddlewareSection{ 84 | Pre: []apidef.MiddlewareDefinition{ 85 | {}, 86 | }, 87 | }, 88 | } 89 | err = BundleValidateManifest(&manifest) 90 | if err == nil { 91 | t.Fatal("The validation step must return an error when no driver is specified.") 92 | } 93 | } 94 | 95 | func TestBundleValidateManifestMinimalFileValidation(t *testing.T) { 96 | manifest := validManifest() 97 | err = BundleValidateManifest(&manifest) 98 | if err != nil { 99 | t.Fatal("A minimal manifest should be valid.") 100 | } 101 | } 102 | 103 | func TestBundleBasicBuild(t *testing.T) { 104 | force = true 105 | testManifest := validManifest() 106 | testManifestData, err := json.Marshal(&testManifest) 107 | if err != nil { 108 | t.Fatalf("Couldn't marshal the test manifest.") 109 | } 110 | ioutil.WriteFile(testManifestName, testManifestData, testPerm) 111 | err = Bundle("build", testBundleName, "", &force) 112 | _, err = os.Stat(testBundleName) 113 | if err != nil { 114 | t.Fatalf("The file wasn't created.\nERROR=%v", err) 115 | } 116 | deleteFiles([]string{testBundleName, testManifestName, testDummyFilename}) 117 | } 118 | 119 | func TestBundleBasicBuildAlternateOutputName(t *testing.T) { 120 | force = true 121 | testManifest := validManifest() 122 | ioutil.WriteFile(testDummyFilename, []byte(""), testPerm) 123 | testManifestData, err := json.Marshal(&testManifest) 124 | if err != nil { 125 | t.Fatalf("Couldn't marshal the test manifest.") 126 | } 127 | ioutil.WriteFile(testManifestName, testManifestData, testPerm) 128 | err = Bundle("build", testBundleAltName, "", &force) 129 | _, err = os.Stat(testBundleAltName) 130 | if err != nil { 131 | t.Fatal("An alt output name was specified, but the file wasn't found.") 132 | } 133 | deleteFiles([]string{testBundleAltName, testManifestName, testDummyFilename}) 134 | } 135 | 136 | func validManifest() apidef.BundleManifest { 137 | return apidef.BundleManifest{ 138 | CustomMiddleware: apidef.MiddlewareSection{ 139 | Pre: []apidef.MiddlewareDefinition{ 140 | { 141 | Name: "mymiddleware", 142 | Path: "./mymiddleware.py", 143 | }, 144 | }, 145 | Driver: apidef.OttoDriver, 146 | }, 147 | } 148 | } 149 | 150 | func deleteFiles(files []string) { 151 | for i := range files { 152 | os.Remove(files[i]) 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /request/request_test.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/http/httptest" 7 | "testing" 8 | ) 9 | 10 | var responseBody = `{ 11 | "apis": [ 12 | { 13 | "api_model": {}, 14 | "api_definition": { 15 | "id": "54b53e47eba6db5c70000002", 16 | "name": "Nitrous Test", 17 | "api_id": "39d2c98be05c424371c600bd8b3e2242", 18 | "org_id": "54b53d3aeba6db5c35000002", 19 | "use_keyless": false, 20 | "use_oauth2": false, 21 | "oauth_meta": { 22 | "allowed_access_types": [], 23 | "allowed_authorize_types": [ 24 | "token" 25 | ], 26 | "auth_login_redirect": "" 27 | }, 28 | "auth": { 29 | "auth_header_name": "authorization" 30 | }, 31 | "use_basic_auth": false, 32 | "notifications": { 33 | "shared_secret": "", 34 | "oauth_on_keychange_url": "" 35 | }, 36 | "enable_signature_checking": false, 37 | "definition": { 38 | "location": "header", 39 | "key": "" 40 | }, 41 | "version_data": { 42 | "not_versioned": true, 43 | "versions": { 44 | "Default": { 45 | "name": "Default", 46 | "expires": "", 47 | "paths": { 48 | "ignored": [], 49 | "white_list": [], 50 | "black_list": [] 51 | }, 52 | "use_extended_paths": false, 53 | "extended_paths": { 54 | "ignored": [], 55 | "white_list": [], 56 | "black_list": [] 57 | } 58 | } 59 | } 60 | }, 61 | "proxy": { 62 | "listen_path": "/39d2c98be05c424371c600bd8b3e2242/", 63 | "target_url": "http://tyk.io", 64 | "strip_listen_path": true 65 | }, 66 | "custom_middleware": { 67 | "pre": null, 68 | "post": null 69 | }, 70 | "session_lifetime": 0, 71 | "active": true, 72 | "auth_provider": { 73 | "name": "", 74 | "storage_engine": "", 75 | "meta": null 76 | }, 77 | "session_provider": { 78 | "name": "", 79 | "storage_engine": "", 80 | "meta": null 81 | }, 82 | "event_handlers": { 83 | "events": {} 84 | }, 85 | "enable_batch_request_support": false, 86 | "enable_ip_whitelisting": false, 87 | "allowed_ips": [], 88 | "expire_analytics_after": 0 89 | }, 90 | "hook_references": [] 91 | } 92 | ], 93 | "pages": 0 94 | }` 95 | 96 | func requestHandler(w http.ResponseWriter, r *http.Request) { 97 | w.WriteHeader(http.StatusOK) 98 | w.Header().Set("Authorization", r.Header["Authorization"][0]) 99 | w.Header().Set("Content-Type", r.Header["Content-Type"][0]) 100 | w.Write([]byte(responseBody)) 101 | } 102 | 103 | func TestFullRequest(t *testing.T) { 104 | request := New("12345", "http://localhost", "3000") 105 | req, err := request.FullRequest("GET", "/api/apis", nil) 106 | if err != nil { 107 | t.Fatalf("Got error: %v", err) 108 | } 109 | recorder := httptest.NewRecorder() 110 | handler := http.HandlerFunc(requestHandler) 111 | handler.ServeHTTP(recorder, req) 112 | 113 | if status := recorder.Code; status != http.StatusOK { 114 | t.Errorf( 115 | "handler returned wrong status code: got %v want %v", 116 | status, http.StatusOK, 117 | ) 118 | } 119 | 120 | if recorder.Body.String() != responseBody { 121 | t.Errorf( 122 | "handler returned unexpected body.\nGot:\n\t%v\nExpected:\n\t%v", 123 | recorder.Body.String(), 124 | responseBody, 125 | ) 126 | } 127 | } 128 | 129 | func TestFullRequestAuthorisation(t *testing.T) { 130 | request := New("12345", "http://localhost", "3000") 131 | req, err := request.FullRequest("GET", "/api/apis", nil) 132 | if err != nil { 133 | t.Fatalf("Got error: %v", err) 134 | } 135 | recorder := httptest.NewRecorder() 136 | handler := http.HandlerFunc(requestHandler) 137 | handler.ServeHTTP(recorder, req) 138 | if recorder.Header().Get("Authorization") != request.Authorisation { 139 | t.Errorf( 140 | "Handler returned unexpected header.\nGot:\n\t%v\nExpected:\n\t%v", 141 | recorder.Header().Get("Authorization"), 142 | request.Authorisation, 143 | ) 144 | } 145 | } 146 | 147 | func TestFullRequestContentType(t *testing.T) { 148 | request := New("12345", "http://localhost", "3000") 149 | req, err := request.FullRequest("GET", "/api/apis", nil) 150 | if err != nil { 151 | t.Fatalf("Got error: %v", err) 152 | } 153 | recorder := httptest.NewRecorder() 154 | handler := http.HandlerFunc(requestHandler) 155 | handler.ServeHTTP(recorder, req) 156 | expectedContentType := "application/json" 157 | if recorder.Header().Get("Content-Type") != expectedContentType { 158 | t.Errorf( 159 | "Handler returned unexpected header.\nGot:\n\t%v\nExpected:\n\t%v", 160 | recorder.Header().Get("Content-Type"), 161 | expectedContentType, 162 | ) 163 | } 164 | } 165 | 166 | func TestFullRequestCorrectUrl(t *testing.T) { 167 | request := New("12345", "http://www.example.com", "3000") 168 | res, err := request.FullRequest("GET", "/api/apis", nil) 169 | if err != nil { 170 | t.Fatalf("Got error: %v", err) 171 | } 172 | expectedURL := fmt.Sprintf("%s:%s/api/apis", request.Domain, request.Port) 173 | if expectedURL != res.URL.String() { 174 | t.Errorf( 175 | "Handler returned unexpected URL.\nGot:\n\t%v\nExpected:\n\t%v", 176 | expectedURL, 177 | res.URL, 178 | ) 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /commands/bundle/main.go: -------------------------------------------------------------------------------- 1 | package bundle 2 | 3 | import ( 4 | "archive/zip" 5 | "bufio" 6 | "bytes" 7 | "crypto/md5" 8 | "encoding/base64" 9 | "encoding/json" 10 | "errors" 11 | "fmt" 12 | "io/ioutil" 13 | "os" 14 | 15 | "github.com/TykTechnologies/goverify" 16 | "github.com/TykTechnologies/tyk/apidef" 17 | ) 18 | 19 | var ( 20 | bundleOutput, privKey string 21 | forceInsecure *bool 22 | ) 23 | 24 | const defaultBundleOutput = "./bundle.zip" 25 | 26 | func init() { 27 | } 28 | 29 | // Bundle will handle the bundle command calls. 30 | func Bundle(command string, thisBundleOutput string, thisPrivKey string, thisForceInsecure *bool) (err error) { 31 | bundleOutput = thisBundleOutput 32 | privKey = thisPrivKey 33 | forceInsecure = thisForceInsecure 34 | 35 | switch command { 36 | case "build": 37 | manifestPath := "./manifest.json" 38 | if _, err = os.Stat(manifestPath); err == nil { 39 | var manifestData []byte 40 | manifestData, err = ioutil.ReadFile(manifestPath) 41 | 42 | var manifest apidef.BundleManifest 43 | err = json.Unmarshal(manifestData, &manifest) 44 | 45 | if err != nil { 46 | fmt.Println("Couldn't parse manifest file!") 47 | break 48 | } 49 | 50 | err = BundleValidateManifest(&manifest) 51 | 52 | if err != nil { 53 | break 54 | } 55 | 56 | // The manifest is valid, we should do the checksum and sign step at this point. 57 | bundleBuild(&manifest) 58 | 59 | } else { 60 | err = errors.New("Manifest file doesn't exist.") 61 | } 62 | default: 63 | err = errors.New("Invalid command.") 64 | } 65 | return err 66 | } 67 | 68 | // BundleValidateManifest will validate the manifest file before building a bundle. 69 | func BundleValidateManifest(manifest *apidef.BundleManifest) (err error) { 70 | // Validate manifest file list: 71 | for _, file := range manifest.FileList { 72 | if _, statErr := os.Stat(file); statErr != nil { 73 | err = errors.New("Referencing a nonexistent file: " + file) 74 | break 75 | } 76 | } 77 | 78 | // The file list references a nonexistent file: 79 | if err != nil { 80 | return err 81 | } 82 | 83 | // The custom middleware block must specify at least one hook: 84 | definedHooks := len(manifest.CustomMiddleware.Pre) + len(manifest.CustomMiddleware.Post) + len(manifest.CustomMiddleware.PostKeyAuth) 85 | 86 | // We should count the auth check middleware (single), if it's present: 87 | if manifest.CustomMiddleware.AuthCheck.Name != "" { 88 | definedHooks++ 89 | } 90 | 91 | if definedHooks == 0 { 92 | err = errors.New("No hooks defined!") 93 | return err 94 | } 95 | 96 | // The custom middleware block must specify a driver: 97 | if manifest.CustomMiddleware.Driver == "" { 98 | err = errors.New("No driver specified!") 99 | return err 100 | } 101 | 102 | return err 103 | } 104 | 105 | // bundleBuild will build and generate a bundle file. 106 | func bundleBuild(manifest *apidef.BundleManifest) (err error) { 107 | var useSignature bool 108 | 109 | if bundleOutput == "" { 110 | fmt.Println("No output specified, using bundle.zip") 111 | bundleOutput = defaultBundleOutput 112 | } 113 | 114 | if privKey != "" { 115 | fmt.Println("The bundle will be signed.") 116 | useSignature = true 117 | } 118 | 119 | var bundleData bytes.Buffer 120 | 121 | for _, file := range manifest.FileList { 122 | data, err := ioutil.ReadFile(file) 123 | if err != nil { 124 | fmt.Println("*** Error: ", err) 125 | return err 126 | } 127 | 128 | bundleData.Write(data) 129 | } 130 | 131 | // Update the manifest file: 132 | manifest.Checksum = fmt.Sprintf("%x", md5.Sum(bundleData.Bytes())) 133 | 134 | // If a private key is specified, sign the data: 135 | if useSignature { 136 | signer, err := goverify.LoadPrivateKeyFromFile(privKey) 137 | if err != nil { 138 | // Error: Couldn't read the private key 139 | return err 140 | } 141 | signed, err := signer.Sign(bundleData.Bytes()) 142 | if err != nil { 143 | // Error: Couldn't sign the data. 144 | return err 145 | } 146 | 147 | manifest.Signature = base64.StdEncoding.EncodeToString(signed) 148 | } else if !*forceInsecure { 149 | fmt.Print("The bundle will be unsigned, type \"y\" to confirm: ") 150 | reader := bufio.NewReader(os.Stdin) 151 | text, _ := reader.ReadString('\n') 152 | if text != "y\n" { 153 | fmt.Println("Aborting") 154 | os.Exit(1) 155 | } 156 | } 157 | 158 | newManifestData, err := json.Marshal(&manifest) 159 | 160 | // Write the bundle file: 161 | buf := new(bytes.Buffer) 162 | bundleWriter := zip.NewWriter(buf) 163 | 164 | for _, file := range manifest.FileList { 165 | outputFile, err := bundleWriter.Create(file) 166 | if err != nil { 167 | return err 168 | } 169 | data, err := ioutil.ReadFile(file) 170 | if err != nil { 171 | return err 172 | } 173 | 174 | if _, err = outputFile.Write(data); err != nil { 175 | return err 176 | } 177 | } 178 | 179 | // Write manifest file: 180 | newManifest, err := bundleWriter.Create("manifest.json") 181 | _, err = newManifest.Write(newManifestData) 182 | 183 | bundleWriter.Close() 184 | return ioutil.WriteFile(bundleOutput, buf.Bytes(), 0755) 185 | } 186 | -------------------------------------------------------------------------------- /commands/api/validate.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "strings" 7 | 8 | v "github.com/gima/govalid/v1" 9 | 10 | "github.com/TykTechnologies/tyk-cli/db" 11 | ) 12 | 13 | // Validate is a public function for validating APIs 14 | func Validate(id string) { 15 | apis := New("validate") 16 | bdb, err := db.OpenDB("bolt.db", 0666, true) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer bdb.Close() 21 | api, err := apis.Find(bdb, id) 22 | if err != nil { 23 | log.Fatal(err) 24 | } 25 | intfAPI := api.(map[string]interface{}) 26 | isValidJSON(intfAPI) 27 | } 28 | 29 | //func isValidJSON(input io.Reader) bool { 30 | func isValidJSON(input map[string]interface{}) bool { 31 | var isValid bool 32 | schema := v.Object( 33 | v.ObjKV("api_model", v.Object()), 34 | v.ObjKV("api_definition", v.Object( 35 | //v.ObjKV("id", v.String(v.StrRegExp("[0-9a-fA-F]+"))), 36 | v.ObjKV("name", v.String(v.StrMin(2))), 37 | v.ObjKV("api_id", v.String(v.StrRegExp("[0-9a-fA-F]+"))), 38 | v.ObjKV("org_id", v.String(v.StrRegExp("[0-9a-fA-F]+"))), 39 | v.ObjKV("use_keyless", v.Boolean()), 40 | v.ObjKV("use_oauth2", v.Boolean()), 41 | v.ObjKV("oauth_meta", v.Object( 42 | v.ObjKV("allowed_access_types", v.Array()), 43 | v.ObjKV("allowed_authorize_types", v.Array( 44 | v.ArrEach(v.String()), 45 | )), 46 | v.ObjKV("auth_login_redirect", v.String()), 47 | )), 48 | v.ObjKV("auth", v.Object( 49 | v.ObjKV("auth_header_name", v.String()), 50 | )), 51 | v.ObjKV("use_basic_auth", v.Boolean()), 52 | v.ObjKV("notifications", v.Object( 53 | v.ObjKV("shared_secret", v.String()), 54 | v.ObjKV("oauth_on_keychange_url", v.String()), 55 | )), 56 | v.ObjKV("enable_signature_checking", v.Boolean()), 57 | v.ObjKV("definition", v.Object( 58 | v.ObjKV("location", v.String()), 59 | v.ObjKV("key", v.String()), 60 | )), 61 | v.ObjKV("version_data", v.Object( 62 | v.ObjKV("not_versioned", v.Boolean()), 63 | v.ObjKV("versions", v.Object( 64 | v.ObjKV("Default", v.Object( 65 | v.ObjKV("name", v.String()), 66 | v.ObjKV("expires", v.String()), 67 | v.ObjKV("paths", v.Object( 68 | v.ObjKV("ignored", v.Array()), 69 | v.ObjKV("white_list", v.Array()), 70 | v.ObjKV("black_list", v.Array()), 71 | )), 72 | v.ObjKV("use_extended_paths", v.Boolean()), 73 | v.ObjKV("extended_paths", v.Optional( 74 | v.Object( 75 | v.ObjKV("ignored", v.Optional(v.Array( 76 | v.ArrEach( 77 | v.Object( 78 | v.ObjKV("path", v.String()), 79 | v.ObjKV("method_actions", v.Object( 80 | v.ObjKV(v.String(), v.Object( 81 | v.ObjKV("action", v.String()), 82 | v.ObjKV("code", v.Number()), 83 | v.ObjKV("data", v.String()), 84 | v.ObjKV("headers", v.Object()), 85 | )), 86 | )), 87 | ), 88 | ), 89 | v.ArrEach( 90 | v.Object( 91 | v.ObjKV("path", v.String()), 92 | v.ObjKV("method_actions", v.Object( 93 | v.ObjKV(v.String(), v.Object( 94 | v.ObjKV("action", v.String()), 95 | v.ObjKV("code", v.Number()), 96 | v.ObjKV("data", v.Object( 97 | v.ObjKV(v.String(), v.String()), 98 | )), 99 | v.ObjKV("headers", v.Object( 100 | v.ObjKV(v.String(), v.String()), 101 | )), 102 | )), 103 | )), 104 | ), 105 | ), 106 | ))), 107 | v.ObjKV("white_list", v.Optional(v.Array())), 108 | v.ObjKV("black_list", v.Optional(v.Array())), 109 | ), 110 | )), 111 | )), 112 | )), 113 | )), 114 | v.ObjKV("proxy", v.Object( 115 | v.ObjKV("listen_path", v.String(v.StrRegExp("^/[A-Za-z0-9-_]+/$"))), 116 | v.ObjKV("target_url", v.String(v.StrRegExp("^http(?s)://[A-Za-z0-9-_]+.[A-Za-z0-9-_]+?(/)$"))), 117 | v.ObjKV("strip_listen_path", v.Boolean()), 118 | )), 119 | v.ObjKV("custom_middleware", v.Object( 120 | v.ObjKV("pre", v.Array()), 121 | v.ObjKV("post", v.Array()), 122 | )), 123 | v.ObjKV("session_lifetime", v.Number()), 124 | v.ObjKV("active", v.Boolean()), 125 | v.ObjKV("auth_provider", v.Object( 126 | v.ObjKV("name", v.Optional(v.String())), 127 | v.ObjKV("storage_engine", v.Optional(v.String())), 128 | v.ObjKV("meta", v.Or(v.Nil(), v.Object())), 129 | )), 130 | v.ObjKV("session_provider", v.Object( 131 | v.ObjKV("name", v.Optional(v.String())), 132 | v.ObjKV("storage_engine", v.Optional(v.String())), 133 | v.ObjKV("meta", v.Or(v.Nil(), v.Object())), 134 | )), 135 | v.ObjKV("event_handlers", v.Object( 136 | v.ObjKV("events", v.Optional( 137 | v.Object( 138 | v.ObjKV("QuotaExceeded", v.Optional( 139 | v.Array( 140 | v.ArrEach( 141 | v.Object( 142 | v.ObjKV("handler_name", v.String()), 143 | v.ObjKV("handler_meta", v.Object( 144 | v.ObjKV("_id", v.String(v.StrRegExp("[0-9a-fA-F]+"))), 145 | v.ObjKV("event_timeout", v.Number()), 146 | v.ObjKV("header_map", v.Object( 147 | v.ObjKV( 148 | v.String(), v.String(), 149 | ), 150 | )), 151 | v.ObjKV("method", v.String(v.StrRegExp("[A-Z]+"))), 152 | v.ObjKV("name", v.String()), 153 | v.ObjKV("org_id", v.String(v.StrRegExp("[0-9a-fA-F]+"))), 154 | v.ObjKV("target_path", v.String(v.StrRegExp("^http(?s)://w+.[a-zA-Z]+(?.[a-zA-Z]+)/w+$"))), 155 | v.ObjKV("template_path", v.Optional(v.String())), 156 | )), 157 | ), 158 | ), 159 | ), 160 | )), 161 | ), 162 | )), 163 | )), 164 | v.ObjKV("enable_batch_request_support", v.Boolean()), 165 | v.ObjKV("enable_ip_whitelisting", v.Boolean()), 166 | v.ObjKV("allowed_ips", v.Array( 167 | v.ArrEach( 168 | v.String(v.StrRegExp("^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$")), 169 | ), 170 | )), 171 | v.ObjKV("expire_analytics_after", v.Number()), 172 | )), 173 | v.ObjKV("hook_references", v.Array( 174 | v.ArrEach( 175 | v.Object( 176 | v.ObjKV("event_name", v.String()), 177 | v.ObjKV("event_timeout", v.Number()), 178 | v.ObjKV("hook", v.Object( 179 | v.ObjKV("api_model", v.Object()), 180 | v.ObjKV("id", v.String(v.StrRegExp("[0-9a-fA-F]+"))), 181 | v.ObjKV("org_id", v.String(v.StrRegExp("[0-9a-fA-F]+"))), 182 | v.ObjKV("name", v.String()), 183 | v.ObjKV("method", v.String(v.StrRegExp("[A-Z]+"))), 184 | v.ObjKV("target_path", v.String(v.StrRegExp("^http(?s)://w+.[a-zA-Z]+(?.[a-zA-Z]+)/w+$"))), 185 | v.ObjKV("template_path", v.String()), 186 | v.ObjKV("header_map", v.Object( 187 | v.ObjKV(v.String(), v.String()), 188 | )), 189 | v.ObjKV("event_timeout", v.Number()), 190 | )), 191 | ), 192 | ), 193 | )), 194 | ) 195 | if path, err := schema.Validate(input); err == nil { 196 | log.Print("Validation passed.") 197 | isValid = true 198 | } else { 199 | pathStr := handleValidationPath(path) 200 | log.Printf("Validation: Error\nRequired { option %s }\n%s", pathStr, err) 201 | isValid = false 202 | } 203 | return isValid 204 | } 205 | 206 | func handleValidationPath(path string) string { 207 | errStr := fmt.Sprintf("%v", path) 208 | valSplit := strings.Split(errStr, ".Value->") 209 | valJoin := strings.Join(valSplit[0:len(valSplit)-1], "") 210 | objKRepl := strings.Replace(valJoin, "Object->Key", "", -1) 211 | return objKRepl 212 | } 213 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # Mozilla Public License Version 2.0 2 | 3 | ## 1. Definitions 4 | 5 | ### 1.1. “Contributor” 6 | means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 7 | 8 | ### 1.2. “Contributor Version” 9 | means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 10 | 11 | ### 1.3. “Contribution” 12 | means Covered Software of a particular Contributor. 13 | 14 | ### 1.4. “Covered Software” 15 | means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 16 | 17 | ### 1.5. “Incompatible With Secondary Licenses” 18 | means 19 | 20 | * a. that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or 21 | * b. that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 22 | 23 | ### 1.6. “Executable Form” 24 | means any form of the work other than Source Code Form. 25 | 26 | ### 1.7. “Larger Work” 27 | means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 28 | 29 | ### 1.8. “License” 30 | means this document. 31 | 32 | ### 1.9. “Licensable” 33 | means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 34 | 35 | ### 1.10. “Modifications” 36 | means any of the following: 37 | 38 | * a. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or 39 | * b. any new file in Source Code Form that contains any Covered Software. 40 | 41 | ### 1.11. “Patent Claims” of a Contributor 42 | means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 43 | 44 | ### 1.12. “Secondary License” 45 | means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 46 | 47 | ### 1.13. “Source Code Form” 48 | means the form of the work preferred for making modifications. 49 | 50 | ### 1.14. “You” (or “Your”) 51 | means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 52 | 53 | ## 2. License Grants and Conditions 54 | 55 | ### 2.1. Grants 56 | 57 | Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: 58 | 59 | * a. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and 60 | * b. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 61 | 62 | ### 2.2. Effective Date 63 | 64 | The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 65 | 66 | ### 2.3. Limitations on Grant Scope 67 | 68 | The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: 69 | 70 | * a. for any code that a Contributor has removed from Covered Software; or 71 | * b. for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or 72 | * c. under Patent Claims infringed by Covered Software in the absence of its Contributions. 73 | 74 | This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 75 | 76 | ### 2.4. Subsequent Licenses 77 | 78 | No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 79 | 80 | ### 2.5. Representation 81 | 82 | Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 83 | 84 | ### 2.6. Fair Use 85 | 86 | This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 87 | 88 | ### 2.7. Conditions 89 | 90 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 91 | 92 | 93 | ## 3. Responsibilities 94 | 95 | ### 3.1. Distribution of Source Form 96 | 97 | All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 98 | 99 | ### 3.2. Distribution of Executable Form 100 | 101 | If You distribute Covered Software in Executable Form then: 102 | 103 | * a. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and 104 | 105 | * b. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 106 | 107 | ### 3.3. Distribution of a Larger Work 108 | 109 | You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 110 | 111 | ### 3.4. Notices 112 | 113 | You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 114 | 115 | ### 3.5. Application of Additional Terms 116 | 117 | You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 118 | 119 | 120 | ## 4. Inability to Comply Due to Statute or Regulation 121 | 122 | If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 123 | 124 | 125 | ## 5. Termination 126 | 127 | 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 128 | 129 | 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 130 | 131 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. 132 | 133 | 134 | ## 6. Disclaimer of Warranty 135 | 136 | **Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.** 137 | 138 | 139 | ## 7. Limitation of Liability 140 | 141 | **Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.** 142 | 143 | 144 | ## 8. Litigation 145 | 146 | Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 147 | 148 | 149 | ## 9. Miscellaneous 150 | 151 | This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 152 | 153 | 154 | ## 10. Versions of the License 155 | 156 | ### 10.1. New Versions 157 | 158 | Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 159 | 160 | ### 10.2. Effect of New Versions 161 | 162 | You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 163 | 164 | ### 10.3. Modified Versions 165 | 166 | If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 167 | 168 | ### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses 169 | 170 | If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. 171 | 172 | 173 | ## Exhibit A - Source Code Form License Notice 174 | 175 | > This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. 176 | 177 | If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. 178 | 179 | You may add additional accurate notices of copyright ownership. 180 | 181 | 182 | ## Exhibit B - “Incompatible With Secondary Licenses” Notice 183 | 184 | > This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. --------------------------------------------------------------------------------