1 // Copyright 2019 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 /////////////////////////////////////////////////////////////////////////////// 16 17 #ifndef TINK_KMS_CLIENTS_H_ 18 #define TINK_KMS_CLIENTS_H_ 19 20 #include <memory> 21 #include <utility> 22 #include <vector> 23 24 #include "absl/base/thread_annotations.h" 25 #include "absl/strings/string_view.h" 26 #include "absl/synchronization/mutex.h" 27 #include "tink/kms_client.h" 28 #include "tink/util/status.h" 29 #include "tink/util/statusor.h" 30 31 namespace crypto { 32 namespace tink { 33 34 // A container for KmsClient-objects that are needed by KeyManager-objects for 35 // primitives that use KMS-managed keys. 36 // 37 // This class consists exclusively of static methods that register and load 38 // KmsClient-objects. 39 class KmsClients { 40 public: 41 // Adds 'kms_client', which must be non-null, to the list 42 // of the list of known clients. Add(std::unique_ptr<KmsClient> kms_client)43 static crypto::tink::util::Status Add(std::unique_ptr<KmsClient> kms_client) { 44 return GlobalInstance().LocalAdd(std::move(kms_client)); 45 } 46 47 // Returns the first KmsClient that was added previously via Add(), 48 // and that does support 'key_uri', which must be non-empty. 49 // Retains the ownership of the returned KmsClient. 50 static crypto::tink::util::StatusOr<const KmsClient*> Get(absl::string_view key_uri)51 Get(absl::string_view key_uri) { 52 return GlobalInstance().LocalGet(key_uri); 53 } 54 55 private: KmsClients()56 KmsClients() {} 57 58 // Per-instance API, to be used by GlobalInstance(); 59 crypto::tink::util::Status 60 LocalAdd(std::unique_ptr<KmsClient> kms_client); 61 crypto::tink::util::StatusOr<const KmsClient*> 62 LocalGet(absl::string_view key_uri); 63 absl::Mutex clients_mutex_; 64 std::vector<std::unique_ptr<KmsClient>> clients_ 65 ABSL_GUARDED_BY(clients_mutex_); 66 67 static KmsClients& GlobalInstance(); 68 }; 69 70 } // namespace tink 71 } // namespace crypto 72 73 #endif // TINK_KMS_CLIENTS_H_ 74