Esempio n. 1
0
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)
}
Esempio n. 2
0
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)
}
Esempio n. 3
0
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)
}
Esempio n. 4
0
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)
}
Esempio n. 5
0
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)
}
Esempio n. 6
0
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")
}
Esempio n. 7
0
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()
}