xref: /aosp_15_r20/external/tink/cc/core/kms_clients.cc (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
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 #include "tink/kms_clients.h"
17 
18 #include <memory>
19 #include <string>
20 #include <utility>
21 #include <vector>
22 
23 #include "absl/status/status.h"
24 #include "absl/strings/string_view.h"
25 #include "absl/synchronization/mutex.h"
26 #include "tink/kms_client.h"
27 #include "tink/util/errors.h"
28 #include "tink/util/status.h"
29 #include "tink/util/statusor.h"
30 
31 namespace crypto {
32 namespace tink {
33 
34 using crypto::tink::util::Status;
35 using crypto::tink::util::StatusOr;
36 
37 // static
GlobalInstance()38 KmsClients& KmsClients::GlobalInstance() {
39   static KmsClients* instance = new KmsClients();
40   return *instance;
41 }
42 
LocalAdd(std::unique_ptr<KmsClient> kms_client)43 Status KmsClients::LocalAdd(std::unique_ptr<KmsClient> kms_client) {
44   if (kms_client == nullptr) {
45     return Status(absl::StatusCode::kInvalidArgument,
46                   "kms_client must be non-null.");
47   }
48   absl::MutexLock lock(&clients_mutex_);
49   clients_.push_back(std::move(kms_client));
50   return util::OkStatus();
51 }
52 
LocalGet(absl::string_view key_uri)53 StatusOr<const KmsClient*> KmsClients::LocalGet(absl::string_view key_uri) {
54   if (key_uri.empty()) {
55     return Status(absl::StatusCode::kInvalidArgument,
56                   "key_uri must be non-empty.");
57   }
58   absl::MutexLock lock(&clients_mutex_);
59   for (const auto& client : clients_) {
60     if (client->DoesSupport(key_uri)) return client.get();
61   }
62   return ToStatusF(absl::StatusCode::kNotFound,
63                    "no KmsClient found for key '%s'.",
64                    std::string(key_uri).c_str());
65 }
66 
67 }  // namespace tink
68 }  // namespace crypto
69