github.com/Ingenico-ePayments/connect-sdk-go@v0.0.0-20240318153750-1f8cd329b9c9/webhooks/InMemorySecretKeyStore.go (about) 1 package webhooks 2 3 import ( 4 "errors" 5 "strings" 6 "sync" 7 ) 8 9 var ( 10 // ErrInvalidKey occurs when the keyID is empty 11 ErrInvalidKey = errors.New("invalid keyID") 12 // ErrInvalidSecret occurs when the given secretKey is empty 13 ErrInvalidSecret = errors.New("invalid secret") 14 ) 15 16 // InMemorySecretKeyStore is an in-memory secret key store. 17 // This implementation can be used in applications where secret keys can be specified at application startup. 18 // Thread-safe. 19 type InMemorySecretKeyStore struct{} 20 21 var keyStoreMap = map[string]string{} 22 var keyStoreLock = sync.RWMutex{} 23 var keyStore = &InMemorySecretKeyStore{} 24 25 // GetSecretKey returns the secretKey associated with the given keyID 26 // 27 // Can return any of the following errors: 28 // SecretKeyNotAvailableError if there is no secretKey with the given keyID 29 func (ks *InMemorySecretKeyStore) GetSecretKey(keyID string) (string, error) { 30 keyStoreLock.RLock() 31 defer keyStoreLock.RUnlock() 32 33 value, exists := keyStoreMap[keyID] 34 35 if !exists { 36 ske, _ := NewSecretKeyNotAvailableError(keyID) 37 38 return "", ske 39 } 40 41 return value, nil 42 } 43 44 // StoreSecretKey stores the given keyID, secretKey pair 45 // 46 // Can return any of the following errors: 47 // ErrInvalidKey if the keyID is empty 48 // ErrInvalidSecret if the secretKey is empty 49 func (ks *InMemorySecretKeyStore) StoreSecretKey(keyID, secretKey string) error { 50 if strings.TrimSpace(keyID) == "" { 51 return ErrInvalidKey 52 } 53 if strings.TrimSpace(secretKey) == "" { 54 return ErrInvalidSecret 55 } 56 57 keyStoreLock.Lock() 58 defer keyStoreLock.Unlock() 59 60 keyStoreMap[keyID] = secretKey 61 62 return nil 63 } 64 65 // RemoveSecretKey removes the given keyID and it's associated secretKey 66 func (ks *InMemorySecretKeyStore) RemoveSecretKey(keyID string) { 67 keyStoreLock.Lock() 68 defer keyStoreLock.Unlock() 69 70 delete(keyStoreMap, keyID) 71 } 72 73 // Clear empties the key store 74 func (ks *InMemorySecretKeyStore) Clear() { 75 keyStoreLock.Lock() 76 defer keyStoreLock.Unlock() 77 78 keyStoreMap = map[string]string{} 79 } 80 81 // NewInMemorySecretKeyStore returns the singleton instance of the InMemorySecretKeyStore 82 func NewInMemorySecretKeyStore() (*InMemorySecretKeyStore, error) { 83 return keyStore, nil 84 }