xref: /aosp_15_r20/external/tink/cc/integration/gcpkms/gcp_kms_client.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/integration/gcpkms/gcp_kms_client.h"
17 
18 #include <fstream>
19 #include <iostream>
20 #include <memory>
21 #include <sstream>
22 #include <string>
23 #include <utility>
24 
25 #include "grpcpp/channel.h"
26 #include "grpcpp/create_channel.h"
27 #include "grpcpp/security/credentials.h"
28 #include "absl/memory/memory.h"
29 #include "absl/status/status.h"
30 #include "absl/strings/match.h"
31 #include "absl/strings/str_cat.h"
32 #include "absl/strings/string_view.h"
33 #include "tink/integration/gcpkms/gcp_kms_aead.h"
34 #include "tink/kms_clients.h"
35 #include "tink/util/status.h"
36 #include "tink/util/statusor.h"
37 #include "tink/version.h"
38 
39 namespace crypto {
40 namespace tink {
41 namespace integration {
42 namespace gcpkms {
43 
44 namespace {
45 
46 using ::google::cloud::kms::v1::KeyManagementService;
47 
48 static constexpr absl::string_view kKeyUriPrefix = "gcp-kms://";
49 static constexpr absl::string_view kGcpKmsServer = "cloudkms.googleapis.com";
50 static constexpr absl::string_view kTinkUserAgentPrefix = "Tink/";
51 
ReadFile(absl::string_view filename)52 util::StatusOr<std::string> ReadFile(absl::string_view filename) {
53   std::ifstream input_stream;
54   input_stream.open(std::string(filename), std::ifstream::in);
55   if (!input_stream.is_open()) {
56     return util::Status(absl::StatusCode::kInvalidArgument,
57                         absl::StrCat("Error reading file ", filename));
58   }
59   std::stringstream input;
60   input << input_stream.rdbuf();
61   input_stream.close();
62   return input.str();
63 }
64 
GetCredentials(absl::string_view credentials_path)65 util::StatusOr<std::shared_ptr<grpc::ChannelCredentials>> GetCredentials(
66     absl::string_view credentials_path) {
67   if (credentials_path.empty()) {
68     std::shared_ptr<grpc::ChannelCredentials> creds =
69         grpc::GoogleDefaultCredentials();
70     if (creds == nullptr) {
71       return util::Status(absl::StatusCode::kInternal,
72                           "Could not read default credentials");
73     }
74     return creds;
75   }
76 
77   // Try reading credentials from a file.
78   util::StatusOr<std::string> json_creds_result = ReadFile(credentials_path);
79   if (!json_creds_result.ok()) {
80     return json_creds_result.status();
81   }
82   std::shared_ptr<grpc::CallCredentials> creds =
83       grpc::ServiceAccountJWTAccessCredentials(json_creds_result.value());
84   if (creds == nullptr) {
85     return util::Status(absl::StatusCode::kInvalidArgument,
86                         absl::StrCat("Could not load credentials from file ",
87                                      credentials_path));
88   }
89   // Creating "empty" 'channel_creds', to convert 'creds' to ChannelCredentials
90   // via CompositeChannelCredentials().
91   std::shared_ptr<grpc::ChannelCredentials> channel_creds =
92       grpc::SslCredentials(grpc::SslCredentialsOptions());
93   return grpc::CompositeChannelCredentials(channel_creds, creds);
94 }
95 
96 // Returns GCP KMS key name contained in `key_uri`. If `key_uri` does not refer
97 // to a GCP key, returns an error status.
GetKeyName(absl::string_view key_uri)98 util::StatusOr<std::string> GetKeyName(absl::string_view key_uri) {
99   if (!absl::StartsWithIgnoreCase(key_uri, kKeyUriPrefix)) {
100     return util::Status(absl::StatusCode::kInvalidArgument,
101                         absl::StrCat("The key URI ", key_uri,
102                                      " does not start with ", kKeyUriPrefix));
103   }
104   return std::string(key_uri.substr(kKeyUriPrefix.length()));
105 }
106 
107 }  // namespace
108 
New(absl::string_view key_uri,absl::string_view credentials_path)109 util::StatusOr<std::unique_ptr<GcpKmsClient>> GcpKmsClient::New(
110     absl::string_view key_uri, absl::string_view credentials_path) {
111   // Empty key name by default.
112   std::string key_name = "";
113   if (!key_uri.empty()) {
114     util::StatusOr<std::string> key_name_from_uri = GetKeyName(key_uri);
115     if (!key_name_from_uri.ok()) {
116       return key_name_from_uri.status();
117     }
118     key_name = key_name_from_uri.value();
119   }
120 
121   // Read credentials.
122   util::StatusOr<std::shared_ptr<grpc::ChannelCredentials>> creds_result =
123       GetCredentials(credentials_path);
124   if (!creds_result.ok()) {
125     return creds_result.status();
126   }
127 
128   // Create a KMS stub.
129   grpc::ChannelArguments args;
130   args.SetUserAgentPrefix(
131       absl::StrCat(kTinkUserAgentPrefix, Version::kTinkVersion, " CPP"));
132   std::shared_ptr<KeyManagementService::Stub> kms_stub =
133       KeyManagementService::NewStub(grpc::CreateCustomChannel(
134           std::string(kGcpKmsServer), creds_result.value(), args));
135   return absl::WrapUnique(new GcpKmsClient(key_name, std::move(kms_stub)));
136 }
137 
DoesSupport(absl::string_view key_uri) const138 bool GcpKmsClient::DoesSupport(absl::string_view key_uri) const {
139   util::StatusOr<std::string> key_name = GetKeyName(key_uri);
140   if (!key_name.ok()) {
141     return false;
142   }
143   return key_name_.empty() ? true : key_name_ == *key_name;
144 }
145 
GetAead(absl::string_view key_uri) const146 util::StatusOr<std::unique_ptr<Aead>> GcpKmsClient::GetAead(
147     absl::string_view key_uri) const {
148   util::StatusOr<std::string> key_name_from_key_uri = GetKeyName(key_uri);
149   // key_uri is invalid.
150   if (!key_name_from_key_uri.ok()) {
151     return key_name_from_key_uri.status();
152   }
153   // key_uri is valid, but if key_name_ is not empty key_name_from_key_uri must
154   // be equal to key_name_.
155   if (!key_name_.empty() && key_name_ != *key_name_from_key_uri) {
156     return util::Status(absl::StatusCode::kInvalidArgument,
157                         absl::StrCat("This client is bound to ", key_name_,
158                                      " and cannot use key ", key_uri));
159   }
160   return GcpKmsAead::New(*key_name_from_key_uri, kms_stub_);
161 }
162 
RegisterNewClient(absl::string_view key_uri,absl::string_view credentials_path)163 util::Status GcpKmsClient::RegisterNewClient(
164     absl::string_view key_uri, absl::string_view credentials_path) {
165   auto client_result = GcpKmsClient::New(key_uri, credentials_path);
166   if (!client_result.ok()) {
167     return client_result.status();
168   }
169   return KmsClients::Add(std::move(client_result.value()));
170 }
171 
172 }  // namespace gcpkms
173 }  // namespace integration
174 }  // namespace tink
175 }  // namespace crypto
176