diff --git a/api.go b/api.go index d1badc93..690d388f 100644 --- a/api.go +++ b/api.go @@ -7,6 +7,8 @@ import ( "io/ioutil" "net/http" + "github.com/TykTechnologies/tyk-identity-broker/initializer" + tykerror "github.com/TykTechnologies/tyk-identity-broker/error" "github.com/TykTechnologies/tyk-identity-broker/tap" @@ -83,7 +85,7 @@ func IsAuthenticated(h http.Handler) http.Handler { // ------ End Middleware methods ------- func HandleGetProfileList(w http.ResponseWriter, r *http.Request) { - profiles := AuthConfigStore.GetAll("") + profiles := initializer.AuthConfigStore.GetAll("") HandleAPIOK(profiles, "", 200, w, r) } @@ -92,7 +94,7 @@ func HandleGetProfile(w http.ResponseWriter, r *http.Request) { key := mux.Vars(r)["id"] thisProfile := tap.Profile{} - keyErr := AuthConfigStore.GetKey(key, thisProfile.OrgID, &thisProfile) + keyErr := initializer.AuthConfigStore.GetKey(key, thisProfile.OrgID, &thisProfile) if keyErr != nil { HandleAPIError(APILogTag, "Profile not found", keyErr, 404, w, r) return @@ -122,7 +124,7 @@ func HandleAddProfile(w http.ResponseWriter, r *http.Request) { return } - httpErr := tap.AddProfile(thisProfile, AuthConfigStore, GlobalDataLoader.Flush) + httpErr := tap.AddProfile(thisProfile, initializer.AuthConfigStore, GlobalDataLoader.Flush) if httpErr != nil { HandleAPIError(APILogTag, httpErr.Message, httpErr.Error, httpErr.Code, w, r) return @@ -147,7 +149,7 @@ func HandleUpdateProfile(w http.ResponseWriter, r *http.Request) { return } - updateErr := tap.UpdateProfile(key, thisProfile, AuthConfigStore, GlobalDataLoader.Flush) + updateErr := tap.UpdateProfile(key, thisProfile, initializer.AuthConfigStore, GlobalDataLoader.Flush) if updateErr != nil { HandleAPIError(APILogTag, updateErr.Message, updateErr.Error, updateErr.Code, w, r) return @@ -158,7 +160,7 @@ func HandleUpdateProfile(w http.ResponseWriter, r *http.Request) { func HandleDeleteProfile(w http.ResponseWriter, r *http.Request) { key := mux.Vars(r)["id"] - err := tap.DeleteProfile(key, "", AuthConfigStore, GlobalDataLoader.Flush) + err := tap.DeleteProfile(key, "", initializer.AuthConfigStore, GlobalDataLoader.Flush) if err != nil { HandleAPIError(APILogTag, err.Message, err.Error, err.Code, w, r) return diff --git a/http_handlers.go b/http_handlers.go index 6423f6e2..78d060b9 100644 --- a/http_handlers.go +++ b/http_handlers.go @@ -4,6 +4,8 @@ import ( "errors" "net/http" + "github.com/TykTechnologies/tyk-identity-broker/initializer" + "github.com/TykTechnologies/tyk-identity-broker/constants" "github.com/TykTechnologies/tyk-identity-broker/providers" @@ -33,7 +35,7 @@ func HandleAuth(w http.ResponseWriter, r *http.Request) { return } - thisIdentityProvider, thisProfile, err := providers.GetTapProfile(AuthConfigStore, IdentityKeyStore, thisId, TykAPIHandler) + thisIdentityProvider, thisProfile, err := providers.GetTapProfile(initializer.AuthConfigStore, initializer.IdentityKeyStore, thisId, TykAPIHandler) if err != nil { return } @@ -52,7 +54,7 @@ func HandleAuthCallback(w http.ResponseWriter, r *http.Request) { return } - thisIdentityProvider, thisProfile, err := providers.GetTapProfile(AuthConfigStore, IdentityKeyStore, thisId, TykAPIHandler) + thisIdentityProvider, thisProfile, err := providers.GetTapProfile(initializer.AuthConfigStore, initializer.IdentityKeyStore, thisId, TykAPIHandler) if err != nil { tykerrors.HandleError(constants.HandlerLogTag, err.Message, err.Error, err.Code, w, r) return @@ -72,7 +74,7 @@ func HandleMetadata(w http.ResponseWriter, r *http.Request) { return } - thisIdentityProvider, _, err := providers.GetTapProfile(AuthConfigStore, IdentityKeyStore, thisId, TykAPIHandler) + thisIdentityProvider, _, err := providers.GetTapProfile(initializer.AuthConfigStore, initializer.IdentityKeyStore, thisId, TykAPIHandler) if err != nil { tykerrors.HandleError(constants.HandlerLogTag, err.Message, err.Error, err.Code, w, r) return diff --git a/initializer/initializer.go b/initializer/initializer.go index 4526610a..79e7f4c9 100644 --- a/initializer/initializer.go +++ b/initializer/initializer.go @@ -1,9 +1,11 @@ package initializer import ( - "github.com/TykTechnologies/storage/persistent" + "errors" + temporal "github.com/TykTechnologies/storage/temporal/keyvalue" "github.com/TykTechnologies/tyk-identity-broker/backends" + tykerror "github.com/TykTechnologies/tyk-identity-broker/error" logger "github.com/TykTechnologies/tyk-identity-broker/log" "github.com/TykTechnologies/tyk-identity-broker/providers" @@ -16,11 +18,17 @@ import ( var log = logger.Get() var initializerLogger = log.WithField("prefix", "TIB INITIALIZER") +// IdentityKeyStore keeps a record of identities tied to tokens (if needed) +var IdentityKeyStore tap.AuthRegisterBackend + +// AuthConfigStore Is the back end we are storing our configuration files to +var AuthConfigStore tap.AuthRegisterBackend + // initBackend: Get our backend to use from configs files, new back-ends must be registered here func InitBackend(profileBackendConfiguration interface{}, identityBackendConfiguration interface{}) (tap.AuthRegisterBackend, tap.AuthRegisterBackend) { - AuthConfigStore := &backends.InMemoryBackend{} - IdentityKeyStore := &backends.RedisBackend{KeyPrefix: "identity-cache."} + AuthConfigStore = &backends.InMemoryBackend{} + IdentityKeyStore = &backends.RedisBackend{KeyPrefix: "identity-cache."} initializerLogger.Info("Initialising Profile Configuration Store") AuthConfigStore.Init(profileBackendConfiguration) @@ -31,16 +39,13 @@ func InitBackend(profileBackendConfiguration interface{}, identityBackendConfigu } // CreateBackendFromRedisConn: creates a redis backend from an existent redis Connection -func CreateBackendFromRedisConn(kv temporal.KeyValue, keyPrefix string) tap.AuthRegisterBackend { +func createBackendFromRedisConn(kv temporal.KeyValue, keyPrefix string) tap.AuthRegisterBackend { redisBackend := &backends.RedisBackend{KeyPrefix: keyPrefix} - - initializerLogger.Info("Initializing Identity Cache") redisBackend.SetDb(kv) - return redisBackend } -func SetLogger(newLogger *logrus.Logger) { +func setLogger(newLogger *logrus.Logger) { logger.SetLogger(newLogger) log = newLogger @@ -52,23 +57,48 @@ func SetCertManager(cm certs.CertificateManager) { providers.CertManager = cm } -func CreateInMemoryBackend() tap.AuthRegisterBackend { - inMemoryBackend := &backends.InMemoryBackend{} - var config interface{} - inMemoryBackend.Init(config) - return inMemoryBackend +func SetConfigHandler(backend tap.AuthRegisterBackend) { + tothic.SetParamsStoreHandler(backend) } -func CreateMongoBackend(store persistent.PersistentStorage) tap.AuthRegisterBackend { - mongoBackend := &backends.MongoBackend{ - Store: store, - Collection: tap.ProfilesCollectionName, - } - var config interface{} - mongoBackend.Init(config) - return mongoBackend +func setKVStorage(kv temporal.KeyValue) { + configHandler := createBackendFromRedisConn(kv, "tib-provider-config-") + + initializerLogger.Info("Initializing Config handler") + tothic.SetParamsStoreHandler(configHandler) + + initializerLogger.Info("Initializing Identity Cache") + IdentityKeyStore = createBackendFromRedisConn(kv, "identity-cache") } -func SetConfigHandler(backend tap.AuthRegisterBackend) { - tothic.SetParamsStoreHandler(backend) +type TIB struct { + Logger *logrus.Logger + KV temporal.KeyValue + CertManager certs.CertificateManager + CookieSecret string +} + +func (tib *TIB) Start() error { + if tib.Logger == nil { + tib.Logger = logrus.New() + } + setLogger(tib.Logger) + + if tib.KV == nil { + return errors.New("kv store cannot be nil") + } + setKVStorage(tib.KV) + + if tib.CertManager == nil { + return errors.New("certificate manager cannot be nil") + } + SetCertManager(tib.CertManager) + tothic.TothErrorHandler = tykerror.HandleError + if tib.CookieSecret != "" { + tothic.SetupSessionStore(tib.CookieSecret) + } else { + // then it will read it from env + tothic.SetupSessionStore() + } + return nil } diff --git a/initializer/initializer_test.go b/initializer/initializer_test.go deleted file mode 100644 index 856b8fc8..00000000 --- a/initializer/initializer_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package initializer - -import ( - "testing" - - temporal "github.com/TykTechnologies/storage/temporal/keyvalue" - "github.com/TykTechnologies/tyk-identity-broker/backends" - "github.com/stretchr/testify/assert" -) - -func TestCreateBackendFromRedisConn(t *testing.T) { - var kv temporal.KeyValue - keyPrefix := "test-prefix" - - // Call the function - result := CreateBackendFromRedisConn(kv, keyPrefix) - - // Assert that result is not nil - assert.NotNil(t, result) - redisBackend, ok := result.(*backends.RedisBackend) - assert.True(t, ok) - - // Assert that the KeyPrefix is correctly set - assert.Equal(t, keyPrefix, redisBackend.KeyPrefix) -} diff --git a/main.go b/main.go index ad3c56e7..84f075c6 100644 --- a/main.go +++ b/main.go @@ -14,18 +14,11 @@ import ( errors "github.com/TykTechnologies/tyk-identity-broker/error" logger "github.com/TykTechnologies/tyk-identity-broker/log" - "github.com/TykTechnologies/tyk-identity-broker/tap" "github.com/TykTechnologies/tyk-identity-broker/tothic" "github.com/TykTechnologies/tyk-identity-broker/tyk-api" "github.com/gorilla/mux" ) -// AuthConfigStore Is the back end we are storing our configuration files to -var AuthConfigStore tap.AuthRegisterBackend - -// IdentityKeyStore keeps a record of identities tied to tokens (if needed) -var IdentityKeyStore tap.AuthRegisterBackend - // config is the system-wide configuration var config configuration.Configuration @@ -48,7 +41,7 @@ func init() { flag.Parse() configuration.LoadConfig(confFile, &config) - AuthConfigStore, IdentityKeyStore = initializer.InitBackend(config.BackEnd.ProfileBackendSettings, config.BackEnd.IdentityBackendSettings) + initializer.InitBackend(config.BackEnd.ProfileBackendSettings, config.BackEnd.IdentityBackendSettings) configStore := &backends.RedisBackend{KeyPrefix: "tib-provider-config-"} configStore.Init(config.BackEnd.IdentityBackendSettings) @@ -69,7 +62,7 @@ func init() { if err != nil { return } - err = GlobalDataLoader.LoadIntoStore(AuthConfigStore) + err = GlobalDataLoader.LoadIntoStore(initializer.AuthConfigStore) if err != nil { mainLogger.Errorf("loading into store %v", err) return diff --git a/tothic/tothic.go b/tothic/tothic.go index 31a807c3..00b29fc1 100644 --- a/tothic/tothic.go +++ b/tothic/tothic.go @@ -49,9 +49,14 @@ func (p PathParam) MarshalBinary() ([]byte, error) { return json.Marshal(p) } -func SetupSessionStore() { - key := KeyFromEnv() - Store = sessions.NewCookieStore([]byte(key)) +func SetupSessionStore(secret ...string) { + var key []byte + if len(secret) > 0 && secret[0] != "" { + key = []byte(secret[0]) + } else { + key = []byte(KeyFromEnv()) + } + Store = sessions.NewCookieStore(key) } func KeyFromEnv() (key string) {