func testTools(code int, body string) (*httptest.Server, *Hoverfly) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(code) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, body) })) // creating random buckets for everyone! bucket := GetRandomName(10) metaBucket := GetRandomName(10) requestCache := cache.NewBoltDBCache(TestDB, bucket) metaCache := cache.NewBoltDBCache(TestDB, metaBucket) cfg := InitSettings() // disabling auth for testing cfg.AuthEnabled = false dbClient := GetNewHoverfly(cfg, requestCache, metaCache, nil) tr := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL) }, } dbClient.HTTP = &http.Client{Transport: tr} return server, dbClient }
func TestGenerateToken(t *testing.T) { ab := backends.NewCacheBasedAuthBackend(cache.NewBoltDBCache(TestDB, []byte(backends.TokenBucketName)), cache.NewBoltDBCache(TestDB, []byte(backends.UserBucketName))) jwtBackend := InitJWTAuthenticationBackend(ab, []byte("verysecret"), 100) token, err := jwtBackend.GenerateToken("userUUIDhereVeryLong", "userx") expect(t, err, nil) expect(t, len(token) > 0, true) }
func TestGetNonExistingBucket(t *testing.T) { RegisterTestingT(t) cache := cache.NewBoltDBCache(TestDB, []byte("somebucket")) _, err := cache.Get([]byte("whatever")) Expect(err).ToNot(BeNil()) Expect(err).To(MatchError("Bucket \"somebucket\" not found!")) }
func TestGetNewHoverflyCheckConfig(t *testing.T) { RegisterTestingT(t) cfg := InitSettings() db := cache.GetDB("testing2.db") requestCache := cache.NewBoltDBCache(db, []byte("requestBucket")) metaCache := cache.NewBoltDBCache(db, []byte("metaBucket")) tokenCache := cache.NewBoltDBCache(db, []byte("tokenBucket")) userCache := cache.NewBoltDBCache(db, []byte("userBucket")) backend := backends.NewCacheBasedAuthBackend(tokenCache, userCache) dbClient := GetNewHoverfly(cfg, requestCache, metaCache, backend) Expect(dbClient.Cfg).To(Equal(cfg)) // deleting this database os.Remove("testing2.db") }
func TestNotBlacklisted(t *testing.T) { ab := backends.NewCacheBasedAuthBackend(cache.NewBoltDBCache(TestDB, []byte(backends.TokenBucketName)), cache.NewBoltDBCache(TestDB, []byte(backends.UserBucketName))) jwtBackend := InitJWTAuthenticationBackend(ab, []byte("verysecret"), 100) tokenString := "exampleTokenStringThatIsNotBlacklisted" blacklisted := jwtBackend.IsInBlacklist(tokenString) expect(t, blacklisted, false) }
func TestGetAllRequestNoBucket(t *testing.T) { RegisterTestingT(t) cache := cache.NewBoltDBCache(TestDB, []byte("somebucket")) cache.CurrentBucket = []byte("no_bucket_for_TestGetAllRequestNoBucket") _, err := cache.GetAllValues() // expecting nil since this would mean that records were wiped Expect(err).To(BeNil()) }
func testTools(code int, body string) (*httptest.Server, *Hoverfly) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(code) w.Header().Set("Content-Type", "application/json") fmt.Fprintln(w, body) })) tr := &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { return url.Parse(server.URL) }, } // creating random buckets for everyone! bucket := GetRandomName(10) metaBucket := GetRandomName(10) requestCache := cache.NewBoltDBCache(TestDB, bucket) metaCache := cache.NewBoltDBCache(TestDB, metaBucket) cfg := InitSettings() // disabling auth for testing cfg.AuthEnabled = false requestMatcher := matching.RequestMatcher{ RequestCache: requestCache, TemplateStore: matching.RequestTemplateStore{}, Webserver: &cfg.Webserver, } // preparing client dbClient := &Hoverfly{ HTTP: &http.Client{Transport: tr}, RequestCache: requestCache, Cfg: cfg, Counter: metrics.NewModeCounter([]string{SimulateMode, SynthesizeMode, ModifyMode, CaptureMode}), MetadataCache: metaCache, ResponseDelays: &models.ResponseDelayList{}, RequestMatcher: requestMatcher, } return server, dbClient }
func TestAuthenticateFail(t *testing.T) { ab := backends.NewCacheBasedAuthBackend(cache.NewBoltDBCache(TestDB, []byte(backends.TokenBucketName)), cache.NewBoltDBCache(TestDB, []byte(backends.UserBucketName))) jwtBackend := InitJWTAuthenticationBackend(ab, []byte("verysecret"), 100) user := &backends.User{ Username: "******", Password: "******", UUID: "uuid_here", IsAdmin: true} success := jwtBackend.Authenticate(user) expect(t, success, false) }
func TestLogout(t *testing.T) { ab := backends.NewCacheBasedAuthBackend(cache.NewBoltDBCache(TestDB, []byte(backends.TokenBucketName)), cache.NewBoltDBCache(TestDB, []byte(backends.UserBucketName))) jwtBackend := InitJWTAuthenticationBackend(ab, []byte("verysecret"), 100) tokenString := "exampletokenstring" token := jwt.New(jwt.SigningMethodHS512) err := jwtBackend.Logout(tokenString, token) expect(t, err, nil) // checking whether token is in blacklist blacklisted := jwtBackend.IsInBlacklist(tokenString) expect(t, blacklisted, true) }
func TestAuthenticate(t *testing.T) { ab := backends.NewCacheBasedAuthBackend(cache.NewBoltDBCache(TestDB, []byte(backends.TokenBucketName)), cache.NewBoltDBCache(TestDB, []byte(backends.UserBucketName))) username := "******" passw := "12345" ab.AddUser(username, passw, true) jwtBackend := InitJWTAuthenticationBackend(ab, []byte("verysecret"), 100) user := &backends.User{ Username: string(username), Password: string(passw), UUID: "uuid_here", IsAdmin: true} success := jwtBackend.Authenticate(user) expect(t, success, true) }
func main() { log.SetFormatter(&log.JSONFormatter{}) flag.Var(&importFlags, "import", "import from file or from URL (i.e. '-import my_service.json' or '-import http://mypage.com/service_x.json'") flag.Var(&destinationFlags, "dest", "specify which hosts to process (i.e. '-dest fooservice.org -dest barservice.org -dest catservice.org') - other hosts will be ignored will passthrough'") flag.Parse() if *version { fmt.Println(hoverflyVersion) os.Exit(0) } // getting settings cfg := hv.InitSettings() if *verbose { // Only log the warning severity or above. log.SetLevel(log.DebugLevel) } cfg.Verbose = *verbose if *dev { // making text pretty log.SetFormatter(&log.TextFormatter{}) } if *generateCA { tlsc, err := hvc.GenerateAndSave(*certName, *certOrg, 365*24*time.Hour) if err != nil { log.WithFields(log.Fields{ "error": err.Error(), }).Fatal("failed to generate certificate.") } goproxy.GoproxyCa = *tlsc } else if *cert != "" && *key != "" { tlsc, err := tls.LoadX509KeyPair(*cert, *key) if err != nil { log.Fatalf("Failed to load certifiate and key pair, got error: %s", err.Error()) } goproxy.GoproxyCa = tlsc } // overriding environment variables (proxy and admin ports) if *proxyPort != "" { cfg.ProxyPort = *proxyPort } if *adminPort != "" { cfg.AdminPort = *adminPort } // development settings cfg.Development = *dev // overriding default middleware setting cfg.Middleware = *middleware mode := getInitialMode(cfg) // setting mode cfg.SetMode(mode) // disabling authentication if no-auth for auth disabled env variable if *authEnabled { cfg.AuthEnabled = true } // disabling tls verification if flag or env variable is set to 'false' (defaults to true) if !cfg.TLSVerification || !*tlsVerification { cfg.TLSVerification = false log.Info("tls certificate verification is now turned off!") } if len(destinationFlags) > 0 { cfg.Destination = strings.Join(destinationFlags[:], "|") } else { // setting destination regexp cfg.Destination = *destination } var requestCache cache.Cache var metadataCache cache.Cache var tokenCache cache.Cache var userCache cache.Cache if *databasePath != "" { cfg.DatabasePath = *databasePath } if *database == boltBackend { log.Info("Creating bolt db backend...") db := cache.GetDB(cfg.DatabasePath) defer db.Close() requestCache = cache.NewBoltDBCache(db, []byte("requestsBucket")) metadataCache = cache.NewBoltDBCache(db, []byte("metadataBucket")) tokenCache = cache.NewBoltDBCache(db, []byte(backends.TokenBucketName)) userCache = cache.NewBoltDBCache(db, []byte(backends.UserBucketName)) } else if *database == inmemoryBackend { log.Info("Creating in memory map backend...") log.Warn("Turning off authentication...") cfg.AuthEnabled = false requestCache = cache.NewInMemoryCache() metadataCache = cache.NewInMemoryCache() tokenCache = cache.NewInMemoryCache() userCache = cache.NewInMemoryCache() } else { log.Fatalf("unknown database type chosen: %s", *database) } authBackend := backends.NewCacheBasedAuthBackend(tokenCache, userCache) hoverfly := hv.GetNewHoverfly(cfg, requestCache, metadataCache, authBackend) // if add new user supplied - adding it to database if *addNew { err := hoverfly.Authentication.AddUser(*addUser, *addPassword, *isAdmin) if err != nil { log.WithFields(log.Fields{ "error": err.Error(), "username": *addUser, }).Fatal("failed to add new user") } else { log.WithFields(log.Fields{ "username": *addUser, }).Info("user added successfuly") } return } if cfg.AuthEnabled { if os.Getenv(hv.HoverflyAdminUsernameEV) != "" && os.Getenv(hv.HoverflyAdminPasswordEV) != "" { hoverfly.Authentication.AddUser( os.Getenv(hv.HoverflyAdminUsernameEV), os.Getenv(hv.HoverflyAdminPasswordEV), true) } // checking if there are any users users, err := hoverfly.Authentication.GetAllUsers() if err != nil { log.WithFields(log.Fields{ "error": err, }).Fatal("got error while trying to get all users") } if len(users) < 1 { createSuperUser(hoverfly) } } // importing records if environment variable is set ev := os.Getenv(hv.HoverflyImportRecordsEV) if ev != "" { err := hoverfly.Import(ev) if err != nil { log.WithFields(log.Fields{ "error": err.Error(), "import": ev, }).Fatal("Environment variable for importing was set but failed to import this resource") } else { err = hoverfly.MetadataCache.Set([]byte("import_from_env_variable"), []byte(ev)) } } // importing stuff if len(importFlags) > 0 { for i, v := range importFlags { if v != "" { log.WithFields(log.Fields{ "import": v, }).Debug("Importing given resource") err := hoverfly.Import(v) if err != nil { log.WithFields(log.Fields{ "error": err.Error(), "import": v, }).Fatal("Failed to import given resource") } else { err = hoverfly.MetadataCache.Set([]byte(fmt.Sprintf("import_%d", i+1)), []byte(v)) } } } } // start metrics registry flush if *metrics { hoverfly.Counter.Init() } cfg.Webserver = *webserver err := hoverfly.StartProxy() if err != nil { log.WithFields(log.Fields{ "error": err.Error(), }).Fatal("failed to start proxy...") } // starting admin interface, this is blocking hoverfly.StartAdminInterface() }