1 // Copyright 2017 Google Inc.
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 #include "tink/internal/registry_impl.h"
18
19 #include <stdint.h>
20
21 #include <memory>
22 #include <sstream>
23 #include <string>
24 #include <thread> // NOLINT(build/c++11)
25 #include <typeinfo>
26 #include <utility>
27
28 #include "gmock/gmock.h"
29 #include "gtest/gtest.h"
30 #include "absl/memory/memory.h"
31 #include "absl/status/status.h"
32 #include "absl/status/statusor.h"
33 #include "absl/strings/string_view.h"
34 #include "openssl/crypto.h"
35 #include "tink/aead.h"
36 #include "tink/aead/aead_wrapper.h"
37 #include "tink/aead/aes_gcm_key_manager.h"
38 #include "tink/core/key_manager_impl.h"
39 #include "tink/core/key_type_manager.h"
40 #include "tink/core/private_key_manager_impl.h"
41 #include "tink/core/private_key_type_manager.h"
42 #include "tink/core/template_util.h"
43 #include "tink/hybrid/ecies_aead_hkdf_private_key_manager.h"
44 #include "tink/hybrid/ecies_aead_hkdf_public_key_manager.h"
45 #include "tink/hybrid_decrypt.h"
46 #include "tink/input_stream.h"
47 #include "tink/internal/fips_utils.h"
48 #include "tink/key_manager.h"
49 #include "tink/mac.h"
50 #include "tink/monitoring/monitoring_client_mocks.h"
51 #include "tink/primitive_set.h"
52 #include "tink/primitive_wrapper.h"
53 #include "tink/registry.h"
54 #include "tink/subtle/aes_gcm_boringssl.h"
55 #include "tink/subtle/random.h"
56 #include "tink/util/input_stream_util.h"
57 #include "tink/util/istream_input_stream.h"
58 #include "tink/util/protobuf_helper.h"
59 #include "tink/util/secret_data.h"
60 #include "tink/util/status.h"
61 #include "tink/util/statusor.h"
62 #include "tink/util/test_matchers.h"
63 #include "tink/util/test_util.h"
64 #include "proto/aes_ctr_hmac_aead.pb.h"
65 #include "proto/aes_gcm.pb.h"
66 #include "proto/common.pb.h"
67 #include "proto/ecdsa.pb.h"
68 #include "proto/ecies_aead_hkdf.pb.h"
69 #include "proto/tink.pb.h"
70
71 namespace crypto {
72 namespace tink {
73 namespace internal {
74
75 namespace {
76
77 using ::crypto::tink::test::AddLegacyKey;
78 using ::crypto::tink::test::AddRawKey;
79 using ::crypto::tink::test::AddTinkKey;
80 using ::crypto::tink::test::DummyAead;
81 using ::crypto::tink::test::IsOk;
82 using ::crypto::tink::test::StatusIs;
83 using ::crypto::tink::util::Status;
84 using ::google::crypto::tink::AesCtrHmacAeadKey;
85 using ::google::crypto::tink::AesGcmKey;
86 using ::google::crypto::tink::AesGcmKeyFormat;
87 using ::google::crypto::tink::EcdsaKeyFormat;
88 using ::google::crypto::tink::EcdsaPrivateKey;
89 using ::google::crypto::tink::EcdsaPublicKey;
90 using ::google::crypto::tink::EcdsaSignatureEncoding;
91 using ::google::crypto::tink::EcPointFormat;
92 using ::google::crypto::tink::EllipticCurveType;
93 using ::google::crypto::tink::HashType;
94 using ::google::crypto::tink::KeyData;
95 using ::google::crypto::tink::Keyset;
96 using ::google::crypto::tink::KeysetInfo;
97 using ::google::crypto::tink::KeyStatusType;
98 using ::google::crypto::tink::KeyTemplate;
99 using ::google::crypto::tink::OutputPrefixType;
100 using ::portable_proto::MessageLite;
101 using ::testing::Eq;
102 using ::testing::HasSubstr;
103 using ::testing::IsNull;
104 using ::testing::Not;
105 using ::testing::SizeIs;
106
107 class RegistryTest : public ::testing::Test {
108 protected:
SetUp()109 void SetUp() override { Registry::Reset(); }
110
TearDown()111 void TearDown() override {
112 // Reset is needed here to ensure Mock objects get deleted and do not leak.
113 Registry::Reset();
114 }
115 };
116
117 class TestKeyFactory : public KeyFactory {
118 public:
TestKeyFactory(const std::string & key_type)119 explicit TestKeyFactory(const std::string& key_type) : key_type_(key_type) {}
120
NewKey(const MessageLite & key_format) const121 util::StatusOr<std::unique_ptr<portable_proto::MessageLite>> NewKey(
122 const MessageLite& key_format) const override {
123 return util::Status(absl::StatusCode::kUnknown,
124 "TestKeyFactory cannot produce a key");
125 }
126
NewKey(absl::string_view serialized_key_format) const127 util::StatusOr<std::unique_ptr<portable_proto::MessageLite>> NewKey(
128 absl::string_view serialized_key_format) const override {
129 return util::Status(absl::StatusCode::kUnknown,
130 "TestKeyFactory cannot produce a key");
131 }
132
NewKeyData(absl::string_view serialized_key_format) const133 util::StatusOr<std::unique_ptr<KeyData>> NewKeyData(
134 absl::string_view serialized_key_format) const override {
135 auto key_data = absl::make_unique<KeyData>();
136 key_data->set_type_url(key_type_);
137 key_data->set_value(std::string(serialized_key_format));
138 return std::move(key_data);
139 }
140
141 private:
142 std::string key_type_;
143 };
144
145 class TestAeadKeyManager : public KeyManager<Aead> {
146 public:
TestAeadKeyManager(const std::string & key_type)147 explicit TestAeadKeyManager(const std::string& key_type)
148 : key_type_(key_type), key_factory_(key_type) {}
149
GetPrimitive(const KeyData & key) const150 util::StatusOr<std::unique_ptr<Aead>> GetPrimitive(
151 const KeyData& key) const override {
152 std::unique_ptr<Aead> aead(new DummyAead(key_type_));
153 return std::move(aead);
154 }
155
GetPrimitive(const MessageLite & key) const156 util::StatusOr<std::unique_ptr<Aead>> GetPrimitive(
157 const MessageLite& key) const override {
158 return util::Status(absl::StatusCode::kUnknown,
159 "TestKeyFactory cannot construct an aead");
160 }
161
get_version() const162 uint32_t get_version() const override { return 0; }
163
get_key_type() const164 const std::string& get_key_type() const override { return key_type_; }
165
get_key_factory() const166 const KeyFactory& get_key_factory() const override { return key_factory_; }
167
168 private:
169 std::string key_type_;
170 TestKeyFactory key_factory_;
171 };
172
173 // A class for testing. We will construct objects from an aead key, so that we
174 // can check that a keymanager can handle multiple primitives. It is really
175 // insecure, as it does nothing except provide access to the key.
176 class AeadVariant {
177 public:
AeadVariant(std::string s)178 explicit AeadVariant(std::string s) : s_(s) {}
179
get()180 std::string get() { return s_; }
181
182 private:
183 std::string s_;
184 };
185
186 class ExampleKeyTypeManager : public KeyTypeManager<AesGcmKey, AesGcmKeyFormat,
187 List<Aead, AeadVariant>> {
188 public:
189 class AeadFactory : public PrimitiveFactory<Aead> {
190 public:
Create(const AesGcmKey & key) const191 crypto::tink::util::StatusOr<std::unique_ptr<Aead>> Create(
192 const AesGcmKey& key) const override {
193 // Ignore the key and returned one with a fixed size for this test.
194 return {subtle::AesGcmBoringSsl::New(
195 util::SecretDataFromStringView(key.key_value()))};
196 }
197 };
198
199 class AeadVariantFactory : public PrimitiveFactory<AeadVariant> {
200 public:
Create(const AesGcmKey & key) const201 crypto::tink::util::StatusOr<std::unique_ptr<AeadVariant>> Create(
202 const AesGcmKey& key) const override {
203 return absl::make_unique<AeadVariant>(key.key_value());
204 }
205 };
206
ExampleKeyTypeManager()207 ExampleKeyTypeManager()
208 : KeyTypeManager(absl::make_unique<AeadFactory>(),
209 absl::make_unique<AeadVariantFactory>()) {}
210
key_material_type() const211 google::crypto::tink::KeyData::KeyMaterialType key_material_type()
212 const override {
213 return google::crypto::tink::KeyData::SYMMETRIC;
214 }
215
get_version() const216 uint32_t get_version() const override { return kVersion; }
217
get_key_type() const218 const std::string& get_key_type() const override { return kKeyType; }
219
ValidateKey(const AesGcmKey & key) const220 crypto::tink::util::Status ValidateKey(const AesGcmKey& key) const override {
221 return util::OkStatus();
222 }
223
ValidateKeyFormat(const AesGcmKeyFormat & key_format) const224 crypto::tink::util::Status ValidateKeyFormat(
225 const AesGcmKeyFormat& key_format) const override {
226 return util::OkStatus();
227 }
228
CreateKey(const AesGcmKeyFormat & key_format) const229 crypto::tink::util::StatusOr<AesGcmKey> CreateKey(
230 const AesGcmKeyFormat& key_format) const override {
231 AesGcmKey result;
232 result.set_key_value(subtle::Random::GetRandomBytes(key_format.key_size()));
233 return result;
234 }
235
DeriveKey(const AesGcmKeyFormat & key_format,InputStream * input_stream) const236 crypto::tink::util::StatusOr<AesGcmKey> DeriveKey(
237 const AesGcmKeyFormat& key_format,
238 InputStream* input_stream) const override {
239 // Note: in an actual key type manager we need to do more work, e.g., test
240 // that the generated key is long enough.
241 crypto::tink::util::StatusOr<std::string> randomness =
242 ReadBytesFromStream(key_format.key_size(), input_stream);
243 if (!randomness.status().ok()) {
244 return randomness.status();
245 }
246 AesGcmKey key;
247 key.set_key_value(randomness.value());
248 return key;
249 }
250
251 MOCK_METHOD(FipsCompatibility, FipsStatus, (), (const, override));
252
253 private:
254 static constexpr int kVersion = 0;
255 const std::string kKeyType =
256 "type.googleapis.com/google.crypto.tink.AesGcmKey";
257 };
258
259 template <typename P, typename Q = P>
260 class TestWrapper : public PrimitiveWrapper<P, Q> {
261 public:
262 TestWrapper() = default;
Wrap(std::unique_ptr<PrimitiveSet<P>> primitive_set) const263 crypto::tink::util::StatusOr<std::unique_ptr<Q>> Wrap(
264 std::unique_ptr<PrimitiveSet<P>> primitive_set) const override {
265 return util::Status(absl::StatusCode::kUnimplemented,
266 "This is a test wrapper.");
267 }
268 };
269
270 class AeadVariantWrapper : public PrimitiveWrapper<AeadVariant, AeadVariant> {
271 public:
Wrap(std::unique_ptr<PrimitiveSet<AeadVariant>> primitive_set) const272 crypto::tink::util::StatusOr<std::unique_ptr<AeadVariant>> Wrap(
273 std::unique_ptr<PrimitiveSet<AeadVariant>> primitive_set) const override {
274 return absl::make_unique<AeadVariant>(
275 primitive_set->get_primary()->get_primitive().get());
276 }
277 };
278
279 class AeadVariantToStringWrapper
280 : public PrimitiveWrapper<AeadVariant, std::string> {
281 public:
Wrap(std::unique_ptr<PrimitiveSet<AeadVariant>> primitive_set) const282 crypto::tink::util::StatusOr<std::unique_ptr<std::string>> Wrap(
283 std::unique_ptr<PrimitiveSet<AeadVariant>> primitive_set) const override {
284 return absl::make_unique<std::string>(
285 primitive_set->get_primary()->get_primitive().get());
286 }
287 };
288
register_test_managers(const std::string & key_type_prefix,int manager_count)289 void register_test_managers(const std::string& key_type_prefix,
290 int manager_count) {
291 for (int i = 0; i < manager_count; i++) {
292 std::string key_type = key_type_prefix + std::to_string(i);
293 util::Status status = Registry::RegisterKeyManager(
294 absl::make_unique<TestAeadKeyManager>(key_type),
295 /* new_key_allowed= */ true);
296 EXPECT_TRUE(status.ok()) << status;
297 }
298 }
299
verify_test_managers(const std::string & key_type_prefix,int manager_count)300 void verify_test_managers(const std::string& key_type_prefix,
301 int manager_count) {
302 for (int i = 0; i < manager_count; i++) {
303 std::string key_type = key_type_prefix + std::to_string(i);
304 auto manager_result = Registry::get_key_manager<Aead>(key_type);
305 EXPECT_TRUE(manager_result.ok()) << manager_result.status();
306 auto manager = manager_result.value();
307 EXPECT_EQ(key_type, manager->get_key_type());
308 }
309 }
310
TEST_F(RegistryTest,testRegisterKeyManagerMoreRestrictiveNewKeyAllowed)311 TEST_F(RegistryTest, testRegisterKeyManagerMoreRestrictiveNewKeyAllowed) {
312 std::string key_type = "some_key_type";
313 KeyTemplate key_template;
314 key_template.set_type_url(key_type);
315
316 // Register the key manager with new_key_allowed == true and verify that
317 // new key data can be created.
318 util::Status status = Registry::RegisterKeyManager(
319 absl::make_unique<TestAeadKeyManager>(key_type),
320 /* new_key_allowed= */ true);
321 EXPECT_TRUE(status.ok()) << status;
322
323 auto result_before = Registry::NewKeyData(key_template);
324 EXPECT_TRUE(result_before.ok()) << result_before.status();
325
326 // Re-register the key manager with new_key_allowed == false and check the
327 // restriction (i.e. new key data cannot be created).
328 status = Registry::RegisterKeyManager(
329 absl::make_unique<TestAeadKeyManager>(key_type),
330 /* new_key_allowed= */ false);
331 EXPECT_TRUE(status.ok()) << status;
332
333 auto result_after = Registry::NewKeyData(key_template);
334 EXPECT_FALSE(result_after.ok());
335 EXPECT_EQ(absl::StatusCode::kInvalidArgument, result_after.status().code());
336 EXPECT_PRED_FORMAT2(testing::IsSubstring, key_type,
337 std::string(result_after.status().message()));
338 EXPECT_PRED_FORMAT2(testing::IsSubstring, "does not allow",
339 std::string(result_after.status().message()));
340 }
341
TEST_F(RegistryTest,testRegisterKeyManagerLessRestrictiveNewKeyAllowed)342 TEST_F(RegistryTest, testRegisterKeyManagerLessRestrictiveNewKeyAllowed) {
343 std::string key_type = "some_key_type";
344 KeyTemplate key_template;
345 key_template.set_type_url(key_type);
346
347 // Register the key manager with new_key_allowed == false.
348 util::Status status = Registry::RegisterKeyManager(
349 absl::make_unique<TestAeadKeyManager>(key_type),
350 /* new_key_allowed= */ false);
351 EXPECT_TRUE(status.ok()) << status;
352
353 // Verify that re-registering the key manager with new_key_allowed == true is
354 // not possible and that the restriction still holds after that operation
355 // (i.e. new key data cannot be created).
356 status = Registry::RegisterKeyManager(
357 absl::make_unique<TestAeadKeyManager>(key_type),
358 /* new_key_allowed= */ true);
359 EXPECT_FALSE(status.ok());
360 EXPECT_EQ(absl::StatusCode::kAlreadyExists, status.code()) << status;
361 EXPECT_PRED_FORMAT2(testing::IsSubstring, key_type,
362 std::string(status.message()))
363 << status;
364 EXPECT_PRED_FORMAT2(testing::IsSubstring, "forbidden new key operation",
365 std::string(status.message()))
366 << status;
367
368 auto result_after = Registry::NewKeyData(key_template);
369 EXPECT_FALSE(result_after.ok());
370 EXPECT_EQ(absl::StatusCode::kInvalidArgument, result_after.status().code());
371 EXPECT_PRED_FORMAT2(testing::IsSubstring, key_type,
372 std::string(result_after.status().message()));
373 EXPECT_PRED_FORMAT2(testing::IsSubstring, "does not allow",
374 std::string(result_after.status().message()));
375 }
376
TEST_F(RegistryTest,testConcurrentRegistration)377 TEST_F(RegistryTest, testConcurrentRegistration) {
378 std::string key_type_prefix_a = "key_type_a_";
379 std::string key_type_prefix_b = "key_type_b_";
380 int count_a = 42;
381 int count_b = 72;
382
383 // Register some managers.
384 std::thread register_a(register_test_managers, key_type_prefix_a, count_a);
385 std::thread register_b(register_test_managers, key_type_prefix_b, count_b);
386 register_a.join();
387 register_b.join();
388
389 // Check that the managers were registered. Also, keep registering new
390 // versions while we check.
391 std::thread register_more_a(register_test_managers, key_type_prefix_a,
392 count_a);
393 std::thread register_more_b(register_test_managers, key_type_prefix_b,
394 count_b);
395 std::thread verify_a(verify_test_managers, key_type_prefix_a, count_a);
396 std::thread verify_b(verify_test_managers, key_type_prefix_b, count_b);
397 verify_a.join();
398 verify_b.join();
399 register_more_a.join();
400 register_more_b.join();
401
402 // Check that there are no extra managers.
403 std::string key_type = key_type_prefix_a + std::to_string(count_a - 1);
404 auto manager_result = Registry::get_key_manager<Aead>(key_type);
405 EXPECT_TRUE(manager_result.ok()) << manager_result.status();
406 EXPECT_EQ(key_type, manager_result.value()->get_key_type());
407
408 key_type = key_type_prefix_a + std::to_string(count_a);
409 manager_result = Registry::get_key_manager<Aead>(key_type);
410 EXPECT_FALSE(manager_result.ok());
411 EXPECT_EQ(absl::StatusCode::kNotFound, manager_result.status().code());
412 }
413
TEST_F(RegistryTest,testBasic)414 TEST_F(RegistryTest, testBasic) {
415 std::string key_type_1 = "google.crypto.tink.AesCtrHmacAeadKey";
416 std::string key_type_2 = "google.crypto.tink.AesGcmKey";
417 auto manager_result = Registry::get_key_manager<Aead>(key_type_1);
418 EXPECT_FALSE(manager_result.ok());
419 EXPECT_EQ(absl::StatusCode::kNotFound, manager_result.status().code());
420
421 auto status = Registry::RegisterKeyManager(
422 absl::make_unique<TestAeadKeyManager>(key_type_1), true);
423
424 EXPECT_TRUE(status.ok()) << status;
425
426 status = Registry::RegisterKeyManager(
427 absl::make_unique<TestAeadKeyManager>(key_type_2), true);
428 EXPECT_TRUE(status.ok()) << status;
429
430 manager_result = Registry::get_key_manager<Aead>(key_type_1);
431 EXPECT_TRUE(manager_result.ok()) << manager_result.status();
432 auto manager = manager_result.value();
433 EXPECT_TRUE(manager->DoesSupport(key_type_1));
434 EXPECT_FALSE(manager->DoesSupport(key_type_2));
435
436 manager_result = Registry::get_key_manager<Aead>(key_type_2);
437 EXPECT_TRUE(manager_result.ok()) << manager_result.status();
438 manager = manager_result.value();
439 EXPECT_TRUE(manager->DoesSupport(key_type_2));
440 EXPECT_FALSE(manager->DoesSupport(key_type_1));
441 }
442
TEST_F(RegistryTest,testRegisterKeyManager)443 TEST_F(RegistryTest, testRegisterKeyManager) {
444 std::string key_type_1 = AesGcmKeyManager().get_key_type();
445
446 std::unique_ptr<TestAeadKeyManager> null_key_manager = nullptr;
447 auto status = Registry::RegisterKeyManager(std::move(null_key_manager), true);
448 EXPECT_FALSE(status.ok());
449 EXPECT_EQ(absl::StatusCode::kInvalidArgument, status.code()) << status;
450
451 // Register a key manager.
452 status = Registry::RegisterKeyManager(
453 absl::make_unique<TestAeadKeyManager>(key_type_1), true);
454 EXPECT_TRUE(status.ok()) << status;
455
456 // Register the same key manager again, it should work (idempotence).
457 status = Registry::RegisterKeyManager(
458 absl::make_unique<TestAeadKeyManager>(key_type_1), true);
459 EXPECT_TRUE(status.ok()) << status;
460
461 // Try overriding a key manager.
462 AesGcmKeyManager key_type_manager;
463 status = Registry::RegisterKeyManager(
464 crypto::tink::internal::MakeKeyManager<Aead>(&key_type_manager), true);
465 EXPECT_FALSE(status.ok());
466 EXPECT_EQ(absl::StatusCode::kAlreadyExists, status.code()) << status;
467
468 // Check the key manager is still registered.
469 auto manager_result = Registry::get_key_manager<Aead>(key_type_1);
470 EXPECT_TRUE(manager_result.ok()) << manager_result.status();
471 auto manager = manager_result.value();
472 EXPECT_TRUE(manager->DoesSupport(key_type_1));
473 }
474
475 // Tests that if we register a key manager once more after a call to
476 // get_key_manager, the key manager previously obtained with "get_key_manager()"
477 // remains valid.
TEST_F(RegistryTest,GetKeyManagerRemainsValid)478 TEST_F(RegistryTest, GetKeyManagerRemainsValid) {
479 std::string key_type = AesGcmKeyManager().get_key_type();
480 EXPECT_THAT(Registry::RegisterKeyManager(
481 absl::make_unique<TestAeadKeyManager>(key_type), true),
482 IsOk());
483
484 crypto::tink::util::StatusOr<const KeyManager<Aead>*> key_manager =
485 Registry::get_key_manager<Aead>(key_type);
486 ASSERT_THAT(key_manager, IsOk());
487 EXPECT_THAT(Registry::RegisterKeyManager(
488 absl::make_unique<TestAeadKeyManager>(key_type), true),
489 IsOk());
490 EXPECT_THAT(key_manager.value()->get_key_type(), Eq(key_type));
491 }
492
TEST_F(RegistryTest,testGettingPrimitives)493 TEST_F(RegistryTest, testGettingPrimitives) {
494 std::string key_type_1 = "google.crypto.tink.AesCtrHmacAeadKey";
495 std::string key_type_2 = "google.crypto.tink.AesGcmKey";
496 AesCtrHmacAeadKey dummy_key_1;
497 AesGcmKey dummy_key_2;
498
499 // Prepare keyset.
500 Keyset keyset;
501
502 uint32_t key_id_1 = 1234543;
503 AddTinkKey(key_type_1, key_id_1, dummy_key_1, KeyStatusType::ENABLED,
504 KeyData::SYMMETRIC, &keyset);
505
506 uint32_t key_id_2 = 726329;
507 AddTinkKey(key_type_2, key_id_2, dummy_key_2, KeyStatusType::DISABLED,
508 KeyData::SYMMETRIC, &keyset);
509
510 uint32_t key_id_3 = 7213743;
511 AddLegacyKey(key_type_2, key_id_3, dummy_key_2, KeyStatusType::ENABLED,
512 KeyData::SYMMETRIC, &keyset);
513
514 uint32_t key_id_4 = 6268492;
515 AddRawKey(key_type_1, key_id_4, dummy_key_1, KeyStatusType::ENABLED,
516 KeyData::SYMMETRIC, &keyset);
517
518 uint32_t key_id_5 = 42;
519 AddRawKey(key_type_2, key_id_5, dummy_key_2, KeyStatusType::ENABLED,
520 KeyData::SYMMETRIC, &keyset);
521
522 keyset.set_primary_key_id(key_id_3);
523
524 // Register key managers.
525 util::Status status;
526 status = Registry::RegisterKeyManager(
527 absl::make_unique<TestAeadKeyManager>(key_type_1), true);
528 EXPECT_TRUE(status.ok()) << status;
529 status = Registry::RegisterKeyManager(
530 absl::make_unique<TestAeadKeyManager>(key_type_2), true);
531 EXPECT_TRUE(status.ok()) << status;
532
533 // Get and use primitives.
534 std::string plaintext = "some data";
535 std::string aad = "aad";
536
537 // Key #1.
538 {
539 auto result = Registry::GetPrimitive<Aead>(keyset.key(0).key_data());
540 EXPECT_TRUE(result.ok()) << result.status();
541 auto aead = std::move(result.value());
542 EXPECT_EQ(DummyAead(key_type_1).Encrypt(plaintext, aad).value(),
543 aead->Encrypt(plaintext, aad).value());
544 }
545
546 // Key #3.
547 {
548 auto result = Registry::GetPrimitive<Aead>(keyset.key(2).key_data());
549 EXPECT_TRUE(result.ok()) << result.status();
550 auto aead = std::move(result.value());
551 EXPECT_EQ(DummyAead(key_type_2).Encrypt(plaintext, aad).value(),
552 aead->Encrypt(plaintext, aad).value());
553 }
554 }
555
TEST_F(RegistryTest,testNewKeyData)556 TEST_F(RegistryTest, testNewKeyData) {
557 std::string key_type_1 = "google.crypto.tink.AesCtrHmacAeadKey";
558 std::string key_type_2 = "google.crypto.tink.AesGcmKey";
559 std::string key_type_3 = "yet/another/keytype";
560
561 // Register key managers.
562 util::Status status;
563 status = Registry::RegisterKeyManager(
564 absl::make_unique<TestAeadKeyManager>(key_type_1),
565 /*new_key_allowed=*/true);
566 EXPECT_TRUE(status.ok()) << status;
567 status = Registry::RegisterKeyManager(
568 absl::make_unique<TestAeadKeyManager>(key_type_2),
569 /*new_key_allowed=*/true);
570 EXPECT_TRUE(status.ok()) << status;
571 status = Registry::RegisterKeyManager(
572 absl::make_unique<TestAeadKeyManager>(key_type_3),
573 /*new_key_allowed=*/false);
574 EXPECT_TRUE(status.ok()) << status;
575
576 { // A supported key type.
577 KeyTemplate key_template;
578 key_template.set_type_url(key_type_1);
579 key_template.set_value("test value 42");
580 auto new_key_data_result = Registry::NewKeyData(key_template);
581 EXPECT_TRUE(new_key_data_result.ok()) << new_key_data_result.status();
582 EXPECT_EQ(key_type_1, new_key_data_result.value()->type_url());
583 EXPECT_EQ(key_template.value(), new_key_data_result.value()->value());
584 }
585
586 { // Another supported key type.
587 KeyTemplate key_template;
588 key_template.set_type_url(key_type_2);
589 key_template.set_value("yet another test value 42");
590 auto new_key_data_result = Registry::NewKeyData(key_template);
591 EXPECT_TRUE(new_key_data_result.ok()) << new_key_data_result.status();
592 EXPECT_EQ(key_type_2, new_key_data_result.value()->type_url());
593 EXPECT_EQ(key_template.value(), new_key_data_result.value()->value());
594 }
595
596 { // A key type that does not allow NewKey-operations.
597 KeyTemplate key_template;
598 key_template.set_type_url(key_type_3);
599 key_template.set_value("some other value 72");
600 auto new_key_data_result = Registry::NewKeyData(key_template);
601 EXPECT_FALSE(new_key_data_result.ok());
602 EXPECT_EQ(absl::StatusCode::kInvalidArgument,
603 new_key_data_result.status().code());
604 EXPECT_PRED_FORMAT2(testing::IsSubstring, key_type_3,
605 std::string(new_key_data_result.status().message()));
606 EXPECT_PRED_FORMAT2(testing::IsSubstring, "does not allow",
607 std::string(new_key_data_result.status().message()));
608 }
609
610 { // A key type that is not supported.
611 KeyTemplate key_template;
612 std::string bad_type_url = "some key type that is not supported";
613 key_template.set_type_url(bad_type_url);
614 key_template.set_value("some totally other value 42");
615 auto new_key_data_result = Registry::NewKeyData(key_template);
616 EXPECT_FALSE(new_key_data_result.ok());
617 EXPECT_EQ(absl::StatusCode::kNotFound, new_key_data_result.status().code());
618 EXPECT_PRED_FORMAT2(testing::IsSubstring, bad_type_url,
619 std::string(new_key_data_result.status().message()));
620 }
621 }
622
TEST_F(RegistryTest,testGetPublicKeyData)623 TEST_F(RegistryTest, testGetPublicKeyData) {
624 // Setup the registry.
625 Registry::Reset();
626 auto private_key_type_manager =
627 absl::make_unique<EciesAeadHkdfPrivateKeyManager>();
628 auto public_key_type_manager =
629 absl::make_unique<EciesAeadHkdfPublicKeyManager>();
630
631 auto status = Registry::RegisterKeyManager(
632 internal::MakePrivateKeyManager<HybridDecrypt>(
633 private_key_type_manager.get(), public_key_type_manager.get()),
634 true);
635 ASSERT_TRUE(status.ok()) << status;
636 AesGcmKeyManager key_type_manager;
637 status = Registry::RegisterKeyManager(
638 crypto::tink::internal::MakeKeyManager<Aead>(&key_type_manager), true);
639 ASSERT_TRUE(status.ok()) << status;
640
641 // Get a test private key.
642 auto ecies_key = test::GetEciesAesGcmHkdfTestKey(
643 EllipticCurveType::NIST_P256, EcPointFormat::UNCOMPRESSED,
644 HashType::SHA256, /* aes_gcm_key_size= */ 24);
645
646 // Extract public key data and check.
647 auto public_key_data_result = Registry::GetPublicKeyData(
648 EciesAeadHkdfPrivateKeyManager().get_key_type(),
649 ecies_key.SerializeAsString());
650 EXPECT_TRUE(public_key_data_result.ok()) << public_key_data_result.status();
651 auto public_key_data = std::move(public_key_data_result.value());
652 EXPECT_EQ(EciesAeadHkdfPublicKeyManager().get_key_type(),
653 public_key_data->type_url());
654 EXPECT_EQ(KeyData::ASYMMETRIC_PUBLIC, public_key_data->key_material_type());
655 EXPECT_EQ(ecies_key.public_key().SerializeAsString(),
656 public_key_data->value());
657
658 // Try with a wrong key type.
659 auto wrong_key_type_result = Registry::GetPublicKeyData(
660 AesGcmKeyManager().get_key_type(), ecies_key.SerializeAsString());
661 EXPECT_FALSE(wrong_key_type_result.ok());
662 EXPECT_EQ(absl::StatusCode::kInvalidArgument,
663 wrong_key_type_result.status().code());
664 EXPECT_PRED_FORMAT2(testing::IsSubstring, "PrivateKeyFactory",
665 std::string(wrong_key_type_result.status().message()));
666
667 // Try with a bad serialized key.
668 auto bad_key_result = Registry::GetPublicKeyData(
669 EciesAeadHkdfPrivateKeyManager().get_key_type(),
670 "some bad serialized key");
671 EXPECT_FALSE(bad_key_result.ok());
672 EXPECT_EQ(absl::StatusCode::kInvalidArgument, bad_key_result.status().code());
673 EXPECT_PRED_FORMAT2(testing::IsSubstring, "Could not parse",
674 std::string(bad_key_result.status().message()));
675 }
676
677 // Tests that if we register the same type of wrapper twice, the second call
678 // succeeds.
TEST_F(RegistryTest,RegisterWrapperTwice)679 TEST_F(RegistryTest, RegisterWrapperTwice) {
680 EXPECT_TRUE(
681 Registry::RegisterPrimitiveWrapper(absl::make_unique<AeadWrapper>())
682 .ok());
683 EXPECT_TRUE(
684 Registry::RegisterPrimitiveWrapper(absl::make_unique<AeadWrapper>())
685 .ok());
686 }
687
688 // Tests that if we register the same type of wrapper twice, the second call
689 // succeeds.
TEST_F(RegistryTest,RegisterTransformingWrapperTwice)690 TEST_F(RegistryTest, RegisterTransformingWrapperTwice) {
691 EXPECT_TRUE(Registry::RegisterPrimitiveWrapper(
692 absl::make_unique<AeadVariantToStringWrapper>())
693 .ok());
694 EXPECT_TRUE(Registry::RegisterPrimitiveWrapper(
695 absl::make_unique<AeadVariantToStringWrapper>())
696 .ok());
697 }
698
699 // Test that if we register a second wrapper, wrapping to the same type as a
700 // previous wrapper it will fail.
TEST_F(RegistryTest,RegisterTransformingWrapperTwiceMixing)701 TEST_F(RegistryTest, RegisterTransformingWrapperTwiceMixing) {
702 EXPECT_TRUE(Registry::RegisterPrimitiveWrapper(
703 absl::make_unique<AeadVariantToStringWrapper>())
704 .ok());
705 // We cannot register a different wrapper creating a std::string.
706 EXPECT_THAT(Registry::RegisterPrimitiveWrapper(
707 absl::make_unique<TestWrapper<std::string>>()),
708 Not(IsOk()));
709 // But one creating an Aead.
710 EXPECT_THAT(Registry::RegisterPrimitiveWrapper(
711 absl::make_unique<TestWrapper<AeadVariant>>()),
712 IsOk());
713 }
714
715 // Test that if we register a second wrapper, wrapping to the same type as a
716 // previous wrapper it will fail (order swapped).
TEST_F(RegistryTest,RegisterTransformingWrapperTwiceMixingBackwards)717 TEST_F(RegistryTest, RegisterTransformingWrapperTwiceMixingBackwards) {
718 EXPECT_THAT(Registry::RegisterPrimitiveWrapper(
719 absl::make_unique<TestWrapper<std::string>>()),
720 IsOk());
721 // We cannot register another wrapper producing strings.
722 EXPECT_THAT(Registry::RegisterPrimitiveWrapper(
723 absl::make_unique<AeadVariantToStringWrapper>()),
724 Not(IsOk()));
725 }
726
727 // Tests that if we register different wrappers for the same primitive twice,
728 // the second call fails.
TEST_F(RegistryTest,RegisterDifferentWrappers)729 TEST_F(RegistryTest, RegisterDifferentWrappers) {
730 EXPECT_TRUE(
731 Registry::RegisterPrimitiveWrapper(absl::make_unique<AeadWrapper>())
732 .ok());
733 util::Status result = Registry::RegisterPrimitiveWrapper(
734 absl::make_unique<TestWrapper<Aead>>());
735 EXPECT_FALSE(result.ok());
736 EXPECT_EQ(absl::StatusCode::kAlreadyExists, result.code());
737 }
738
739 // Tests that if we register different wrappers for different primitives, this
740 // returns ok.
TEST_F(RegistryTest,RegisterDifferentWrappersDifferentPrimitives)741 TEST_F(RegistryTest, RegisterDifferentWrappersDifferentPrimitives) {
742 EXPECT_TRUE(
743 Registry::RegisterPrimitiveWrapper(absl::make_unique<TestWrapper<Aead>>())
744 .ok());
745 EXPECT_TRUE(
746 Registry::RegisterPrimitiveWrapper(absl::make_unique<TestWrapper<Mac>>())
747 .ok());
748 }
749
750 // Tests that if we do not register a wrapper, then calls to Wrap
751 // fail with "No wrapper registered" -- even if there is a wrapper for a
752 // different primitive registered.
TEST_F(RegistryTest,NoWrapperRegistered)753 TEST_F(RegistryTest, NoWrapperRegistered) {
754 EXPECT_TRUE(
755 Registry::RegisterPrimitiveWrapper(absl::make_unique<TestWrapper<Mac>>())
756 .ok());
757
758 crypto::tink::util::StatusOr<std::unique_ptr<Aead>> result =
759 Registry::Wrap<Aead>(absl::make_unique<PrimitiveSet<Aead>>());
760 EXPECT_FALSE(result.ok());
761 EXPECT_EQ(absl::StatusCode::kNotFound, result.status().code());
762 EXPECT_PRED_FORMAT2(testing::IsSubstring, "No wrapper registered",
763 std::string(result.status().message()));
764 }
765
766 // Tests that if the wrapper fails, the error of the wrapped is forwarded
767 // in GetWrappedPrimitive.
TEST_F(RegistryTest,WrapperFails)768 TEST_F(RegistryTest, WrapperFails) {
769 EXPECT_TRUE(
770 Registry::RegisterPrimitiveWrapper(absl::make_unique<TestWrapper<Aead>>())
771 .ok());
772
773 crypto::tink::util::StatusOr<std::unique_ptr<Aead>> result =
774 Registry::Wrap<Aead>(absl::make_unique<PrimitiveSet<Aead>>());
775 EXPECT_FALSE(result.ok());
776 EXPECT_PRED_FORMAT2(testing::IsSubstring, "This is a test wrapper",
777 std::string(result.status().message()));
778 }
779
780 // Tests that wrapping works as expected in the usual case.
TEST_F(RegistryTest,UsualWrappingTest)781 TEST_F(RegistryTest, UsualWrappingTest) {
782 KeysetInfo keyset_info;
783
784 keyset_info.add_key_info();
785 keyset_info.mutable_key_info(0)->set_output_prefix_type(
786 OutputPrefixType::TINK);
787 keyset_info.mutable_key_info(0)->set_key_id(1234543);
788 keyset_info.mutable_key_info(0)->set_status(KeyStatusType::ENABLED);
789 keyset_info.add_key_info();
790 keyset_info.mutable_key_info(1)->set_output_prefix_type(
791 OutputPrefixType::LEGACY);
792 keyset_info.mutable_key_info(1)->set_key_id(726329);
793 keyset_info.mutable_key_info(1)->set_status(KeyStatusType::ENABLED);
794 keyset_info.add_key_info();
795 keyset_info.mutable_key_info(2)->set_output_prefix_type(
796 OutputPrefixType::TINK);
797 keyset_info.mutable_key_info(2)->set_key_id(7213743);
798 keyset_info.mutable_key_info(2)->set_status(KeyStatusType::ENABLED);
799
800 auto primitive_set = absl::make_unique<PrimitiveSet<Aead>>();
801 ASSERT_TRUE(primitive_set
802 ->AddPrimitive(absl::make_unique<DummyAead>("aead0"),
803 keyset_info.key_info(0))
804 .ok());
805 ASSERT_TRUE(primitive_set
806 ->AddPrimitive(absl::make_unique<DummyAead>("aead1"),
807 keyset_info.key_info(1))
808 .ok());
809 auto entry_result = primitive_set->AddPrimitive(
810 absl::make_unique<DummyAead>("primary_aead"), keyset_info.key_info(2));
811 ASSERT_THAT(primitive_set->set_primary(entry_result.value()), IsOk());
812
813 EXPECT_TRUE(
814 Registry::RegisterPrimitiveWrapper(absl::make_unique<AeadWrapper>())
815 .ok());
816
817 auto aead_result = Registry::Wrap<Aead>(std::move(primitive_set));
818 EXPECT_TRUE(aead_result.ok()) << aead_result.status();
819 std::unique_ptr<Aead> aead = std::move(aead_result.value());
820 std::string plaintext = "some_plaintext";
821 std::string aad = "some_aad";
822
823 auto encrypt_result = aead->Encrypt(plaintext, aad);
824 EXPECT_TRUE(encrypt_result.ok()) << encrypt_result.status();
825 std::string ciphertext = encrypt_result.value();
826 EXPECT_PRED_FORMAT2(testing::IsSubstring, "primary_aead", ciphertext);
827
828 auto decrypt_result = aead->Decrypt(ciphertext, aad);
829 EXPECT_TRUE(decrypt_result.ok()) << decrypt_result.status();
830 EXPECT_EQ(plaintext, decrypt_result.value());
831
832 decrypt_result = aead->Decrypt("some bad ciphertext", aad);
833 EXPECT_FALSE(decrypt_result.ok());
834 EXPECT_EQ(absl::StatusCode::kInvalidArgument, decrypt_result.status().code());
835 EXPECT_PRED_FORMAT2(testing::IsSubstring, "decryption failed",
836 std::string(decrypt_result.status().message()));
837 }
838
AddAesGcmKey(uint32_t key_id,OutputPrefixType output_prefix_type,KeyStatusType key_status_type,Keyset & modified_keyset)839 std::string AddAesGcmKey(uint32_t key_id, OutputPrefixType output_prefix_type,
840 KeyStatusType key_status_type,
841 Keyset& modified_keyset) {
842 AesGcmKey key;
843 key.set_version(0);
844 key.set_key_value(subtle::Random::GetRandomBytes(16));
845 KeyData key_data;
846 key_data.set_value(key.SerializeAsString());
847 key_data.set_type_url("type.googleapis.com/google.crypto.tink.AesGcmKey");
848 test::AddKeyData(key_data, key_id, output_prefix_type, key_status_type,
849 &modified_keyset);
850 return key.key_value();
851 }
852
853 // Tests that wrapping of a keyset works in the usual case.
TEST_F(RegistryTest,KeysetWrappingTest)854 TEST_F(RegistryTest, KeysetWrappingTest) {
855 if (!IsFipsEnabledInSsl()) {
856 GTEST_SKIP() << "Not supported when BoringSSL is not built in FIPS-mode.";
857 }
858
859 Keyset keyset;
860 std::string raw_key =
861 AddAesGcmKey(13, OutputPrefixType::TINK, KeyStatusType::ENABLED, keyset);
862 keyset.set_primary_key_id(13);
863
864 auto fips_key_manager = absl::make_unique<ExampleKeyTypeManager>();
865
866 ON_CALL(*fips_key_manager, FipsStatus())
867 .WillByDefault(testing::Return(FipsCompatibility::kRequiresBoringCrypto));
868
869 ASSERT_THAT(
870 Registry::RegisterKeyTypeManager(std::move(fips_key_manager), true),
871 IsOk());
872 ASSERT_THAT(Registry::RegisterPrimitiveWrapper(
873 absl::make_unique<AeadVariantWrapper>()),
874 IsOk());
875
876 crypto::tink::util::StatusOr<std::unique_ptr<AeadVariant>> aead_variant =
877 RegistryImpl::GlobalInstance().WrapKeyset<AeadVariant>(
878 keyset, /*annotations=*/{});
879 EXPECT_THAT(aead_variant, IsOk());
880 EXPECT_THAT(aead_variant.value()->get(), Eq(raw_key));
881 }
882
883 // Tests that wrapping of a keyset works.
TEST_F(RegistryTest,TransformingKeysetWrappingTest)884 TEST_F(RegistryTest, TransformingKeysetWrappingTest) {
885 if (kUseOnlyFips) {
886 GTEST_SKIP() << "Not supported in FIPS-only mode";
887 }
888
889 Keyset keyset;
890 std::string raw_key =
891 AddAesGcmKey(13, OutputPrefixType::TINK, KeyStatusType::ENABLED, keyset);
892 keyset.set_primary_key_id(13);
893
894 ASSERT_THAT(Registry::RegisterKeyTypeManager(
895 absl::make_unique<ExampleKeyTypeManager>(), true),
896 IsOk());
897 ASSERT_THAT(Registry::RegisterPrimitiveWrapper(
898 absl::make_unique<AeadVariantToStringWrapper>()),
899 IsOk());
900
901 crypto::tink::util::StatusOr<std::unique_ptr<std::string>> string_primitive =
902 RegistryImpl::GlobalInstance().WrapKeyset<std::string>(
903 keyset, /*annotations=*/{});
904 EXPECT_THAT(string_primitive, IsOk());
905 EXPECT_THAT(*string_primitive.value(), Eq(raw_key));
906 }
907
908 // Tests that when we ask the registry to wrap a PrimitiveSet<Aead> into an
909 // Aead, but the wrapper is in fact from something else into Aead, we give a
910 // correct error message.
TEST_F(RegistryTest,TransformingPrimitiveWrapperCustomKeyManager)911 TEST_F(RegistryTest, TransformingPrimitiveWrapperCustomKeyManager) {
912 if (kUseOnlyFips) {
913 GTEST_SKIP() << "Not supported in FIPS-only mode";
914 }
915
916 ASSERT_THAT(Registry::RegisterKeyTypeManager(
917 absl::make_unique<ExampleKeyTypeManager>(), true),
918 IsOk());
919 // Register a transforming wrapper taking strings and making Aeads.
920 ASSERT_THAT(Registry::RegisterPrimitiveWrapper(
921 absl::make_unique<TestWrapper<std::string, Aead>>()),
922 IsOk());
923
924 KeysetInfo keyset_info;
925 keyset_info.add_key_info();
926 keyset_info.mutable_key_info(0)->set_output_prefix_type(
927 OutputPrefixType::TINK);
928 keyset_info.mutable_key_info(0)->set_key_id(1234543);
929 keyset_info.mutable_key_info(0)->set_status(KeyStatusType::ENABLED);
930 keyset_info.set_primary_key_id(1234543);
931
932 auto primitive_set = absl::make_unique<PrimitiveSet<Aead>>();
933 ASSERT_TRUE(primitive_set
934 ->AddPrimitive(absl::make_unique<DummyAead>("aead0"),
935 keyset_info.key_info(0))
936 .ok());
937
938 EXPECT_THAT(Registry::Wrap<Aead>(std::move(primitive_set)).status(),
939 StatusIs(absl::StatusCode::kFailedPrecondition,
940 HasSubstr("custom key manager")));
941 }
942
943 // Tests that the error message in GetKeyManager contains the type_id.name() of
944 // the primitive for which the key manager was actually registered.
TEST_F(RegistryTest,GetKeyManagerErrorMessage)945 TEST_F(RegistryTest, GetKeyManagerErrorMessage) {
946 AesGcmKeyManager key_type_manager;
947 EXPECT_TRUE(
948 Registry::RegisterKeyManager(
949 crypto::tink::internal::MakeKeyManager<Aead>(&key_type_manager), true)
950 .ok());
951 auto result =
952 Registry::get_key_manager<int>(AesGcmKeyManager().get_key_type());
953 EXPECT_FALSE(result.ok());
954 EXPECT_THAT(std::string(result.status().message()),
955 HasSubstr(AesGcmKeyManager().get_key_type()));
956 // Note: The C++ standard does not guarantee the next line. If some toolchain
957 // update fails it, one can delete it.
958 EXPECT_THAT(std::string(result.status().message()),
959 HasSubstr(typeid(Aead).name()));
960 }
961
TEST_F(RegistryTest,RegisterKeyTypeManager)962 TEST_F(RegistryTest, RegisterKeyTypeManager) {
963 if (kUseOnlyFips) {
964 GTEST_SKIP() << "Not supported in FIPS-only mode";
965 }
966
967 EXPECT_THAT(Registry::RegisterKeyTypeManager(
968 absl::make_unique<ExampleKeyTypeManager>(), true),
969 IsOk());
970 }
971
TEST_F(RegistryTest,RegisterFipsKeyTypeManager)972 TEST_F(RegistryTest, RegisterFipsKeyTypeManager) {
973 if (!kUseOnlyFips || !IsFipsEnabledInSsl()) {
974 GTEST_SKIP() << "Only supported in FIPS-mode with BoringCrypto available.";
975 }
976
977 auto fips_key_manager = absl::make_unique<ExampleKeyTypeManager>();
978
979 ON_CALL(*fips_key_manager, FipsStatus())
980 .WillByDefault(testing::Return(FipsCompatibility::kRequiresBoringCrypto));
981
982 EXPECT_THAT(
983 Registry::RegisterKeyTypeManager(std::move(fips_key_manager), true),
984 IsOk());
985 }
986
TEST_F(RegistryTest,RegisterFipsKeyTypeManagerNoBoringCrypto)987 TEST_F(RegistryTest, RegisterFipsKeyTypeManagerNoBoringCrypto) {
988 if (!kUseOnlyFips || IsFipsEnabledInSsl()) {
989 GTEST_SKIP()
990 << "Only supported in FIPS-mode with BoringCrypto not available.";
991 }
992
993 auto fips_key_manager = absl::make_unique<ExampleKeyTypeManager>();
994
995 ON_CALL(*fips_key_manager, FipsStatus())
996 .WillByDefault(testing::Return(FipsCompatibility::kNotFips));
997
998 EXPECT_THAT(
999 Registry::RegisterKeyTypeManager(std::move(fips_key_manager), true),
1000 StatusIs(absl::StatusCode::kInternal));
1001 }
1002
TEST_F(RegistryTest,KeyTypeManagerGetFirstKeyManager)1003 TEST_F(RegistryTest, KeyTypeManagerGetFirstKeyManager) {
1004 if (kUseOnlyFips) {
1005 GTEST_SKIP() << "Not supported in FIPS-only mode";
1006 }
1007
1008 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1009 absl::make_unique<ExampleKeyTypeManager>(), true),
1010 IsOk());
1011 AesGcmKeyFormat format;
1012 format.set_key_size(16);
1013 AesGcmKey key = ExampleKeyTypeManager().CreateKey(format).value();
1014 auto aead = Registry::get_key_manager<Aead>(
1015 "type.googleapis.com/google.crypto.tink.AesGcmKey")
1016 .value()
1017 ->GetPrimitive(key)
1018 .value();
1019 std::string encryption = aead->Encrypt("TESTMESSAGE", "").value();
1020 std::string decryption = aead->Decrypt(encryption, "").value();
1021 EXPECT_THAT(decryption, Eq("TESTMESSAGE"));
1022 }
1023
TEST_F(RegistryTest,KeyTypeManagerGetSecondKeyManager)1024 TEST_F(RegistryTest, KeyTypeManagerGetSecondKeyManager) {
1025 if (kUseOnlyFips) {
1026 GTEST_SKIP() << "Not supported in FIPS-only mode";
1027 }
1028
1029 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1030 absl::make_unique<ExampleKeyTypeManager>(), true),
1031 IsOk());
1032 AesGcmKeyFormat format;
1033 format.set_key_size(16);
1034 AesGcmKey key = ExampleKeyTypeManager().CreateKey(format).value();
1035 auto aead_variant = Registry::get_key_manager<AeadVariant>(
1036 "type.googleapis.com/google.crypto.tink.AesGcmKey")
1037 .value()
1038 ->GetPrimitive(key)
1039 .value();
1040 EXPECT_THAT(aead_variant->get(), Eq(key.key_value()));
1041 }
1042
TEST_F(RegistryTest,KeyTypeManagerNotSupportedPrimitive)1043 TEST_F(RegistryTest, KeyTypeManagerNotSupportedPrimitive) {
1044 if (kUseOnlyFips) {
1045 GTEST_SKIP() << "Not supported in FIPS-only mode";
1046 }
1047
1048 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1049 absl::make_unique<ExampleKeyTypeManager>(), true),
1050 IsOk());
1051 EXPECT_THAT(Registry::get_key_manager<Mac>(
1052 "type.googleapis.com/google.crypto.tink.AesGcmKey")
1053 .status(),
1054 StatusIs(absl::StatusCode::kInvalidArgument,
1055 HasSubstr("not among supported primitives")));
1056 }
1057
1058 // Tests that if we register a key manager once more after a call to
1059 // get_key_manager, the key manager previously obtained with "get_key_manager()"
1060 // remains valid.
TEST_F(RegistryTest,GetKeyManagerRemainsValidForKeyTypeManagers)1061 TEST_F(RegistryTest, GetKeyManagerRemainsValidForKeyTypeManagers) {
1062 if (kUseOnlyFips) {
1063 GTEST_SKIP() << "Not supported in FIPS-only mode";
1064 }
1065
1066 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1067 absl::make_unique<ExampleKeyTypeManager>(), true),
1068 IsOk());
1069
1070 crypto::tink::util::StatusOr<const KeyManager<Aead>*> key_manager =
1071 Registry::get_key_manager<Aead>(ExampleKeyTypeManager().get_key_type());
1072 ASSERT_THAT(key_manager, IsOk());
1073 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1074 absl::make_unique<ExampleKeyTypeManager>(), true),
1075 IsOk());
1076 EXPECT_THAT(key_manager.value()->get_key_type(),
1077 Eq(ExampleKeyTypeManager().get_key_type()));
1078 }
1079
TEST_F(RegistryTest,KeyTypeManagerNewKey)1080 TEST_F(RegistryTest, KeyTypeManagerNewKey) {
1081 if (kUseOnlyFips) {
1082 GTEST_SKIP() << "Not supported in FIPS-only mode";
1083 }
1084
1085 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1086 absl::make_unique<ExampleKeyTypeManager>(), true),
1087 IsOk());
1088
1089 AesGcmKeyFormat format;
1090 format.set_key_size(32);
1091 KeyTemplate key_template;
1092 key_template.set_type_url("type.googleapis.com/google.crypto.tink.AesGcmKey");
1093 key_template.set_value(format.SerializeAsString());
1094
1095 KeyData key_data = *Registry::NewKeyData(key_template).value();
1096 EXPECT_THAT(key_data.type_url(),
1097 Eq("type.googleapis.com/google.crypto.tink.AesGcmKey"));
1098 EXPECT_THAT(key_data.key_material_type(),
1099 Eq(google::crypto::tink::KeyData::SYMMETRIC));
1100 AesGcmKey key;
1101 key.ParseFromString(key_data.value());
1102 EXPECT_THAT(key.key_value(), SizeIs(32));
1103 }
1104
TEST_F(RegistryTest,KeyTypeManagerNewKeyInvalidSize)1105 TEST_F(RegistryTest, KeyTypeManagerNewKeyInvalidSize) {
1106 if (kUseOnlyFips) {
1107 GTEST_SKIP() << "Not supported in FIPS-only mode";
1108 }
1109
1110 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1111 absl::make_unique<ExampleKeyTypeManager>(), true),
1112 IsOk());
1113
1114 AesGcmKeyFormat format;
1115 format.set_key_size(33);
1116 KeyTemplate key_template;
1117 key_template.set_type_url("type.googleapis.com/google.crypto.tink.AesGcmKey");
1118 key_template.set_value(format.SerializeAsString());
1119
1120 EXPECT_THAT(Registry::NewKeyData(key_template), IsOk());
1121 }
1122
TEST_F(RegistryTest,KeyTypeManagerDeriveKey)1123 TEST_F(RegistryTest, KeyTypeManagerDeriveKey) {
1124 if (kUseOnlyFips) {
1125 GTEST_SKIP() << "Not supported in FIPS-only mode";
1126 }
1127
1128 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1129 absl::make_unique<ExampleKeyTypeManager>(), true),
1130 IsOk());
1131
1132 AesGcmKeyFormat format;
1133 format.set_key_size(32);
1134 KeyTemplate key_template;
1135 key_template.set_type_url("type.googleapis.com/google.crypto.tink.AesGcmKey");
1136 key_template.set_value(format.SerializeAsString());
1137
1138 crypto::tink::util::IstreamInputStream input_stream{
1139 absl::make_unique<std::stringstream>(
1140 "0123456789012345678901234567890123456789")};
1141
1142 auto key_data_or =
1143 RegistryImpl::GlobalInstance().DeriveKey(key_template, &input_stream);
1144 ASSERT_THAT(key_data_or, IsOk());
1145 EXPECT_THAT(key_data_or.value().type_url(), Eq(key_template.type_url()));
1146 AesGcmKey key;
1147 EXPECT_TRUE(key.ParseFromString(key_data_or.value().value()));
1148 // 32 byte prefix of above string.
1149 EXPECT_THAT(key.key_value(), Eq("01234567890123456789012345678901"));
1150 }
1151
1152 // The same, but we register the key manager twice. This should catch some of
1153 // the possible lifetime issues.
TEST_F(RegistryTest,KeyTypeManagerDeriveKeyRegisterTwice)1154 TEST_F(RegistryTest, KeyTypeManagerDeriveKeyRegisterTwice) {
1155 if (kUseOnlyFips) {
1156 GTEST_SKIP() << "Not supported in FIPS-only mode";
1157 }
1158
1159 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1160 absl::make_unique<ExampleKeyTypeManager>(), true),
1161 IsOk());
1162 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1163 absl::make_unique<ExampleKeyTypeManager>(), true),
1164 IsOk());
1165
1166 AesGcmKeyFormat format;
1167 format.set_key_size(32);
1168 KeyTemplate key_template;
1169 key_template.set_type_url("type.googleapis.com/google.crypto.tink.AesGcmKey");
1170 key_template.set_value(format.SerializeAsString());
1171
1172 crypto::tink::util::IstreamInputStream input_stream{
1173 absl::make_unique<std::stringstream>(
1174 "0123456789012345678901234567890123456789")};
1175
1176 auto key_data_or =
1177 RegistryImpl::GlobalInstance().DeriveKey(key_template, &input_stream);
1178 ASSERT_THAT(key_data_or, IsOk());
1179 EXPECT_THAT(key_data_or.value().type_url(), Eq(key_template.type_url()));
1180 AesGcmKey key;
1181 EXPECT_TRUE(key.ParseFromString(key_data_or.value().value()));
1182 // 32 byte prefix of above string.
1183 EXPECT_THAT(key.key_value(), Eq("01234567890123456789012345678901"));
1184 }
1185
1186 // Tests that if we register a KeyManager instead of a KeyTypeManager, DeriveKey
1187 // fails properly.
TEST_F(RegistryTest,KeyManagerDeriveKeyFail)1188 TEST_F(RegistryTest, KeyManagerDeriveKeyFail) {
1189 std::string key_type = "type.googleapis.com/google.crypto.tink.AesGcmKey";
1190 ASSERT_THAT(Registry::RegisterKeyManager(
1191 absl::make_unique<TestAeadKeyManager>(key_type),
1192 /* new_key_allowed= */ true),
1193 IsOk());
1194
1195 KeyTemplate key_template;
1196 key_template.set_type_url("type.googleapis.com/google.crypto.tink.AesGcmKey");
1197
1198 EXPECT_THAT(
1199 RegistryImpl::GlobalInstance().DeriveKey(key_template, nullptr).status(),
1200 StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("cannot derive")));
1201 }
1202
TEST_F(RegistryTest,KeyManagerDeriveNotRegistered)1203 TEST_F(RegistryTest, KeyManagerDeriveNotRegistered) {
1204 KeyTemplate key_template;
1205 key_template.set_type_url("some_inexistent_keytype");
1206
1207 EXPECT_THAT(
1208 RegistryImpl::GlobalInstance().DeriveKey(key_template, nullptr).status(),
1209 StatusIs(absl::StatusCode::kNotFound, HasSubstr("No manager")));
1210 }
1211
TEST_F(RegistryTest,RegisterKeyTypeManagerTwiceMoreRestrictive)1212 TEST_F(RegistryTest, RegisterKeyTypeManagerTwiceMoreRestrictive) {
1213 if (kUseOnlyFips) {
1214 GTEST_SKIP() << "Not supported in FIPS-only mode";
1215 }
1216
1217 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1218 absl::make_unique<ExampleKeyTypeManager>(), true),
1219 IsOk());
1220 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1221 absl::make_unique<ExampleKeyTypeManager>(), false),
1222 IsOk());
1223 }
1224
TEST_F(RegistryTest,RegisterKeyTypeManagerTwice)1225 TEST_F(RegistryTest, RegisterKeyTypeManagerTwice) {
1226 if (kUseOnlyFips) {
1227 GTEST_SKIP() << "Not supported in FIPS-only mode";
1228 }
1229
1230 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1231 absl::make_unique<ExampleKeyTypeManager>(), true),
1232 IsOk());
1233 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1234 absl::make_unique<ExampleKeyTypeManager>(), true),
1235 IsOk());
1236 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1237 absl::make_unique<ExampleKeyTypeManager>(), false),
1238 IsOk());
1239 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1240 absl::make_unique<ExampleKeyTypeManager>(), false),
1241 IsOk());
1242 }
1243
TEST_F(RegistryTest,RegisterKeyTypeManagerLessRestrictive)1244 TEST_F(RegistryTest, RegisterKeyTypeManagerLessRestrictive) {
1245 if (kUseOnlyFips) {
1246 GTEST_SKIP() << "Not supported in FIPS-only mode";
1247 }
1248
1249 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1250 absl::make_unique<ExampleKeyTypeManager>(), false),
1251 IsOk());
1252 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1253 absl::make_unique<ExampleKeyTypeManager>(), true),
1254 StatusIs(absl::StatusCode::kAlreadyExists));
1255 }
1256
TEST_F(RegistryTest,RegisterKeyTypeManagerBeforeKeyManager)1257 TEST_F(RegistryTest, RegisterKeyTypeManagerBeforeKeyManager) {
1258 if (kUseOnlyFips) {
1259 GTEST_SKIP() << "Not supported in FIPS-only mode";
1260 }
1261
1262 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1263 absl::make_unique<ExampleKeyTypeManager>(), true),
1264 IsOk());
1265 EXPECT_THAT(Registry::RegisterKeyManager(
1266 absl::make_unique<TestAeadKeyManager>(
1267 "type.googleapis.com/google.crypto.tink.AesGcmKey"),
1268 true),
1269 StatusIs(absl::StatusCode::kAlreadyExists));
1270 }
1271
TEST_F(RegistryTest,RegisterKeyTypeManagerAfterKeyManager)1272 TEST_F(RegistryTest, RegisterKeyTypeManagerAfterKeyManager) {
1273 if (kUseOnlyFips) {
1274 GTEST_SKIP() << "Not supported in FIPS-only mode";
1275 }
1276
1277 EXPECT_THAT(Registry::RegisterKeyManager(
1278 absl::make_unique<TestAeadKeyManager>(
1279 "type.googleapis.com/google.crypto.tink.AesGcmKey"),
1280 true),
1281 IsOk());
1282 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1283 absl::make_unique<ExampleKeyTypeManager>(), true),
1284 StatusIs(absl::StatusCode::kAlreadyExists));
1285 }
1286
1287 } // namespace
1288
1289 // NOTE: These are outside of the anonymous namespace to allow compiling with
1290 // MSVC.
1291 class PrivatePrimitiveA {};
1292 class PrivatePrimitiveB {};
1293
1294 namespace {
1295
1296 class TestPrivateKeyTypeManager
1297 : public PrivateKeyTypeManager<EcdsaPrivateKey, EcdsaKeyFormat,
1298 EcdsaPublicKey,
1299 List<PrivatePrimitiveA, PrivatePrimitiveB>> {
1300 public:
1301 class PrivatePrimitiveAFactory : public PrimitiveFactory<PrivatePrimitiveA> {
1302 public:
Create(const EcdsaPrivateKey & key) const1303 crypto::tink::util::StatusOr<std::unique_ptr<PrivatePrimitiveA>> Create(
1304 const EcdsaPrivateKey& key) const override {
1305 return util::Status(absl::StatusCode::kUnimplemented, "Not implemented");
1306 }
1307 };
1308 class PrivatePrimitiveBFactory : public PrimitiveFactory<PrivatePrimitiveB> {
1309 public:
Create(const EcdsaPrivateKey & key) const1310 crypto::tink::util::StatusOr<std::unique_ptr<PrivatePrimitiveB>> Create(
1311 const EcdsaPrivateKey& key) const override {
1312 return util::Status(absl::StatusCode::kUnimplemented, "Not implemented");
1313 }
1314 };
1315
TestPrivateKeyTypeManager()1316 TestPrivateKeyTypeManager()
1317 : PrivateKeyTypeManager(absl::make_unique<PrivatePrimitiveAFactory>(),
1318 absl::make_unique<PrivatePrimitiveBFactory>()) {}
1319
key_material_type() const1320 google::crypto::tink::KeyData::KeyMaterialType key_material_type()
1321 const override {
1322 return google::crypto::tink::KeyData::ASYMMETRIC_PRIVATE;
1323 }
1324
get_version() const1325 uint32_t get_version() const override { return 0; }
ValidateKey(const EcdsaPrivateKey & key) const1326 crypto::tink::util::Status ValidateKey(
1327 const EcdsaPrivateKey& key) const override {
1328 return crypto::tink::util::OkStatus();
1329 }
ValidateKeyFormat(const EcdsaKeyFormat & key) const1330 crypto::tink::util::Status ValidateKeyFormat(
1331 const EcdsaKeyFormat& key) const override {
1332 return crypto::tink::util::OkStatus();
1333 }
1334
get_key_type() const1335 const std::string& get_key_type() const override { return kKeyType; }
1336
CreateKey(const EcdsaKeyFormat & key_format) const1337 crypto::tink::util::StatusOr<EcdsaPrivateKey> CreateKey(
1338 const EcdsaKeyFormat& key_format) const override {
1339 EcdsaPublicKey public_key;
1340 *public_key.mutable_params() = key_format.params();
1341 EcdsaPrivateKey result;
1342 *result.mutable_public_key() = public_key;
1343 return result;
1344 }
1345
GetPublicKey(const EcdsaPrivateKey & private_key) const1346 crypto::tink::util::StatusOr<EcdsaPublicKey> GetPublicKey(
1347 const EcdsaPrivateKey& private_key) const override {
1348 return private_key.public_key();
1349 }
1350
1351 MOCK_METHOD(FipsCompatibility, FipsStatus, (), (const, override));
1352
1353 private:
1354 const std::string kKeyType =
1355 "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey";
1356 };
1357
1358 } // namespace
1359
1360 // NOTE: These are outside of the anonymous namespace to allow compiling with
1361 // MSVC.
1362 class PublicPrimitiveA {};
1363 class PublicPrimitiveB {};
1364
1365 namespace {
1366
1367 class TestPublicKeyTypeManager
1368 : public KeyTypeManager<EcdsaPublicKey, void,
1369 List<PublicPrimitiveA, PublicPrimitiveB>> {
1370 public:
1371 class PublicPrimitiveAFactory : public PrimitiveFactory<PublicPrimitiveA> {
1372 public:
Create(const EcdsaPublicKey & key) const1373 crypto::tink::util::StatusOr<std::unique_ptr<PublicPrimitiveA>> Create(
1374 const EcdsaPublicKey& key) const override {
1375 return util::Status(absl::StatusCode::kUnimplemented, "Not implemented");
1376 }
1377 };
1378 class PublicPrimitiveBFactory : public PrimitiveFactory<PublicPrimitiveB> {
1379 public:
Create(const EcdsaPublicKey & key) const1380 crypto::tink::util::StatusOr<std::unique_ptr<PublicPrimitiveB>> Create(
1381 const EcdsaPublicKey& key) const override {
1382 return util::Status(absl::StatusCode::kUnimplemented, "Not implemented");
1383 }
1384 };
1385
TestPublicKeyTypeManager()1386 TestPublicKeyTypeManager()
1387 : KeyTypeManager(absl::make_unique<PublicPrimitiveAFactory>(),
1388 absl::make_unique<PublicPrimitiveBFactory>()) {}
1389
key_material_type() const1390 google::crypto::tink::KeyData::KeyMaterialType key_material_type()
1391 const override {
1392 return google::crypto::tink::KeyData::ASYMMETRIC_PRIVATE;
1393 }
1394
get_version() const1395 uint32_t get_version() const override { return 0; }
ValidateKey(const EcdsaPublicKey & key) const1396 crypto::tink::util::Status ValidateKey(
1397 const EcdsaPublicKey& key) const override {
1398 return crypto::tink::util::OkStatus();
1399 }
1400
get_key_type() const1401 const std::string& get_key_type() const override { return kKeyType; }
1402
1403 MOCK_METHOD(FipsCompatibility, FipsStatus, (), (const, override));
1404
1405 private:
1406 const std::string kKeyType =
1407 "type.googleapis.com/google.crypto.tink.EcdsaPublicKey";
1408 };
1409
1410 std::unique_ptr<TestPrivateKeyTypeManager>
CreateTestPrivateKeyManagerFipsCompatible()1411 CreateTestPrivateKeyManagerFipsCompatible() {
1412 auto private_key_manager = absl::make_unique<TestPrivateKeyTypeManager>();
1413 ON_CALL(*private_key_manager, FipsStatus())
1414 .WillByDefault(testing::Return(FipsCompatibility::kRequiresBoringCrypto));
1415 return private_key_manager;
1416 }
1417
1418 std::unique_ptr<TestPublicKeyTypeManager>
CreateTestPublicKeyManagerFipsCompatible()1419 CreateTestPublicKeyManagerFipsCompatible() {
1420 auto public_key_manager = absl::make_unique<TestPublicKeyTypeManager>();
1421 ON_CALL(*public_key_manager, FipsStatus())
1422 .WillByDefault(testing::Return(FipsCompatibility::kRequiresBoringCrypto));
1423 return public_key_manager;
1424 }
1425
TEST_F(RegistryTest,RegisterAsymmetricKeyManagers)1426 TEST_F(RegistryTest, RegisterAsymmetricKeyManagers) {
1427 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1428 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1429 "not available";
1430 }
1431
1432 crypto::tink::util::Status status = Registry::RegisterAsymmetricKeyManagers(
1433 CreateTestPrivateKeyManagerFipsCompatible(),
1434 CreateTestPublicKeyManagerFipsCompatible(), true);
1435 ASSERT_TRUE(status.ok()) << status;
1436 }
1437
TEST_F(RegistryTest,AsymmetricMoreRestrictiveNewKey)1438 TEST_F(RegistryTest, AsymmetricMoreRestrictiveNewKey) {
1439 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1440 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1441 "not available";
1442 }
1443
1444 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1445 CreateTestPrivateKeyManagerFipsCompatible(),
1446 CreateTestPublicKeyManagerFipsCompatible(), true)
1447 .ok());
1448
1449 crypto::tink::util::Status status = Registry::RegisterAsymmetricKeyManagers(
1450 CreateTestPrivateKeyManagerFipsCompatible(),
1451 CreateTestPublicKeyManagerFipsCompatible(), false);
1452 ASSERT_TRUE(status.ok()) << status;
1453 }
1454
TEST_F(RegistryTest,AsymmetricSameNewKey)1455 TEST_F(RegistryTest, AsymmetricSameNewKey) {
1456 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1457 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1458 "not available";
1459 }
1460
1461 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1462 CreateTestPrivateKeyManagerFipsCompatible(),
1463 CreateTestPublicKeyManagerFipsCompatible(), true)
1464 .ok());
1465 crypto::tink::util::Status status = Registry::RegisterAsymmetricKeyManagers(
1466 CreateTestPrivateKeyManagerFipsCompatible(),
1467 CreateTestPublicKeyManagerFipsCompatible(), true);
1468 ASSERT_TRUE(status.ok()) << status;
1469
1470 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1471 CreateTestPrivateKeyManagerFipsCompatible(),
1472 CreateTestPublicKeyManagerFipsCompatible(), false)
1473 .ok());
1474 status = Registry::RegisterAsymmetricKeyManagers(
1475 CreateTestPrivateKeyManagerFipsCompatible(),
1476 CreateTestPublicKeyManagerFipsCompatible(), false);
1477 ASSERT_TRUE(status.ok()) << status;
1478 }
1479
TEST_F(RegistryTest,AsymmetricLessRestrictiveGivesError)1480 TEST_F(RegistryTest, AsymmetricLessRestrictiveGivesError) {
1481 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1482 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1483 "not available";
1484 }
1485
1486 crypto::tink::util::Status status = Registry::RegisterAsymmetricKeyManagers(
1487 CreateTestPrivateKeyManagerFipsCompatible(),
1488 CreateTestPublicKeyManagerFipsCompatible(), false);
1489 ASSERT_TRUE(status.ok()) << status;
1490 EXPECT_THAT(Registry::RegisterAsymmetricKeyManagers(
1491 CreateTestPrivateKeyManagerFipsCompatible(),
1492 CreateTestPublicKeyManagerFipsCompatible(), true),
1493 StatusIs(absl::StatusCode::kAlreadyExists,
1494 HasSubstr("forbidden new key operation")));
1495 }
1496
1497 // Tests that if we register asymmetric key managers once more after a call to
1498 // get_key_manager, the key manager previously obtained with "get_key_manager()"
1499 // remains valid.
1500
TEST_F(RegistryTest,RegisterAsymmetricKeyManagersGetKeyManagerStaysValid)1501 TEST_F(RegistryTest, RegisterAsymmetricKeyManagersGetKeyManagerStaysValid) {
1502 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1503 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1504 "not available";
1505 }
1506
1507 ASSERT_THAT(Registry::RegisterAsymmetricKeyManagers(
1508 CreateTestPrivateKeyManagerFipsCompatible(),
1509 CreateTestPublicKeyManagerFipsCompatible(), true),
1510 IsOk());
1511
1512 crypto::tink::util::StatusOr<const KeyManager<PrivatePrimitiveA>*>
1513 private_key_manager = Registry::get_key_manager<PrivatePrimitiveA>(
1514 TestPrivateKeyTypeManager().get_key_type());
1515 crypto::tink::util::StatusOr<const KeyManager<PublicPrimitiveA>*>
1516 public_key_manager = Registry::get_key_manager<PublicPrimitiveA>(
1517 TestPublicKeyTypeManager().get_key_type());
1518
1519 ASSERT_THAT(Registry::RegisterAsymmetricKeyManagers(
1520 CreateTestPrivateKeyManagerFipsCompatible(),
1521 CreateTestPublicKeyManagerFipsCompatible(), true),
1522 IsOk());
1523
1524 EXPECT_THAT(private_key_manager.value()->get_key_type(),
1525 Eq(TestPrivateKeyTypeManager().get_key_type()));
1526 EXPECT_THAT(public_key_manager.value()->get_key_type(),
1527 Eq(TestPublicKeyTypeManager().get_key_type()));
1528 }
1529
TEST_F(RegistryTest,AsymmetricPrivateRegisterAlone)1530 TEST_F(RegistryTest, AsymmetricPrivateRegisterAlone) {
1531 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1532 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1533 "not available";
1534 }
1535
1536 ASSERT_TRUE(Registry::RegisterKeyTypeManager(
1537 CreateTestPrivateKeyManagerFipsCompatible(), true)
1538 .ok());
1539 ASSERT_TRUE(Registry::RegisterKeyTypeManager(
1540 CreateTestPublicKeyManagerFipsCompatible(), true)
1541 .ok());
1542 // Registering the same as asymmetric key managers must fail, because doing so
1543 // would mean we invalidate key managers previously obtained with
1544 // get_key_manager().
1545 ASSERT_FALSE(Registry::RegisterAsymmetricKeyManagers(
1546 CreateTestPrivateKeyManagerFipsCompatible(),
1547 CreateTestPublicKeyManagerFipsCompatible(), true)
1548 .ok());
1549 ASSERT_TRUE(Registry::RegisterKeyTypeManager(
1550 CreateTestPrivateKeyManagerFipsCompatible(), true)
1551 .ok());
1552 ASSERT_TRUE(Registry::RegisterKeyTypeManager(
1553 CreateTestPublicKeyManagerFipsCompatible(), true)
1554 .ok());
1555 }
1556
TEST_F(RegistryTest,AsymmetricGetPrimitiveA)1557 TEST_F(RegistryTest, AsymmetricGetPrimitiveA) {
1558 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1559 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1560 "not available";
1561 }
1562
1563 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1564 CreateTestPrivateKeyManagerFipsCompatible(),
1565 CreateTestPublicKeyManagerFipsCompatible(), true)
1566 .ok());
1567 crypto::tink::util::StatusOr<const KeyManager<PrivatePrimitiveA>*> km =
1568 Registry::get_key_manager<PrivatePrimitiveA>(
1569 TestPrivateKeyTypeManager().get_key_type());
1570 ASSERT_TRUE(km.ok()) << km.status();
1571 EXPECT_THAT(km.value()->get_key_type(),
1572 Eq(TestPrivateKeyTypeManager().get_key_type()));
1573 }
1574
TEST_F(RegistryTest,AsymmetricGetPrimitiveB)1575 TEST_F(RegistryTest, AsymmetricGetPrimitiveB) {
1576 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1577 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1578 "not available";
1579 }
1580
1581 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1582 CreateTestPrivateKeyManagerFipsCompatible(),
1583 CreateTestPublicKeyManagerFipsCompatible(), true)
1584 .ok());
1585 crypto::tink::util::StatusOr<const KeyManager<PrivatePrimitiveB>*> km =
1586 Registry::get_key_manager<PrivatePrimitiveB>(
1587 TestPrivateKeyTypeManager().get_key_type());
1588 ASSERT_TRUE(km.ok()) << km.status();
1589 EXPECT_THAT(km.value()->get_key_type(),
1590 Eq(TestPrivateKeyTypeManager().get_key_type()));
1591 }
1592
TEST_F(RegistryTest,AsymmetricGetPublicPrimitiveA)1593 TEST_F(RegistryTest, AsymmetricGetPublicPrimitiveA) {
1594 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1595 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1596 "not available";
1597 }
1598
1599 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1600 CreateTestPrivateKeyManagerFipsCompatible(),
1601 CreateTestPublicKeyManagerFipsCompatible(), true)
1602 .ok());
1603 crypto::tink::util::StatusOr<const KeyManager<PublicPrimitiveA>*> km =
1604 Registry::get_key_manager<PublicPrimitiveA>(
1605 TestPublicKeyTypeManager().get_key_type());
1606 ASSERT_TRUE(km.ok()) << km.status();
1607 EXPECT_THAT(km.value()->get_key_type(),
1608 Eq(TestPublicKeyTypeManager().get_key_type()));
1609 }
1610
TEST_F(RegistryTest,AsymmetricGetPublicPrimitiveB)1611 TEST_F(RegistryTest, AsymmetricGetPublicPrimitiveB) {
1612 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1613 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1614 "not available";
1615 }
1616
1617 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1618 CreateTestPrivateKeyManagerFipsCompatible(),
1619 CreateTestPublicKeyManagerFipsCompatible(), true)
1620 .ok());
1621 crypto::tink::util::StatusOr<const KeyManager<PublicPrimitiveB>*> km =
1622 Registry::get_key_manager<PublicPrimitiveB>(
1623 TestPublicKeyTypeManager().get_key_type());
1624 ASSERT_TRUE(km.ok()) << km.status();
1625 EXPECT_THAT(km.value()->get_key_type(),
1626 Eq(TestPublicKeyTypeManager().get_key_type()));
1627 }
1628
TEST_F(RegistryTest,AsymmetricGetWrongPrimitiveError)1629 TEST_F(RegistryTest, AsymmetricGetWrongPrimitiveError) {
1630 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1631 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1632 "not available";
1633 }
1634
1635 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1636 CreateTestPrivateKeyManagerFipsCompatible(),
1637 CreateTestPublicKeyManagerFipsCompatible(), true)
1638 .ok());
1639 crypto::tink::util::StatusOr<const KeyManager<PublicPrimitiveA>*> km =
1640 Registry::get_key_manager<PublicPrimitiveA>(
1641 TestPrivateKeyTypeManager().get_key_type());
1642 EXPECT_THAT(km.status(),
1643 StatusIs(absl::StatusCode::kInvalidArgument,
1644 HasSubstr("not among supported primitives")));
1645 }
1646
1647 class PrivateKeyManagerImplTest : public testing::Test {
SetUp()1648 void SetUp() override { Registry::Reset(); }
1649
TearDown()1650 void TearDown() override {
1651 // Reset is needed here to ensure Mock objects get deleted and do not leak.
1652 Registry::Reset();
1653 }
1654 };
1655
TEST_F(PrivateKeyManagerImplTest,AsymmetricFactoryNewKeyFromMessage)1656 TEST_F(PrivateKeyManagerImplTest, AsymmetricFactoryNewKeyFromMessage) {
1657 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1658 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1659 "not available";
1660 }
1661
1662 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1663 CreateTestPrivateKeyManagerFipsCompatible(),
1664 CreateTestPublicKeyManagerFipsCompatible(), true)
1665 .ok());
1666
1667 EcdsaKeyFormat key_format;
1668 key_format.mutable_params()->set_encoding(EcdsaSignatureEncoding::DER);
1669 KeyTemplate key_template;
1670 key_template.set_type_url(TestPrivateKeyTypeManager().get_key_type());
1671 key_template.set_value(key_format.SerializeAsString());
1672 key_template.set_output_prefix_type(OutputPrefixType::TINK);
1673 std::unique_ptr<KeyData> key_data =
1674 Registry::NewKeyData(key_template).value();
1675 EXPECT_THAT(key_data->type_url(),
1676 Eq(TestPrivateKeyTypeManager().get_key_type()));
1677 EcdsaPrivateKey private_key;
1678 private_key.ParseFromString(key_data->value());
1679 EXPECT_THAT(private_key.public_key().params().encoding(),
1680 Eq(EcdsaSignatureEncoding::DER));
1681 }
1682
TEST_F(PrivateKeyManagerImplTest,AsymmetricNewKeyDisallowed)1683 TEST_F(PrivateKeyManagerImplTest, AsymmetricNewKeyDisallowed) {
1684 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1685 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1686 "not available";
1687 }
1688
1689 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1690 CreateTestPrivateKeyManagerFipsCompatible(),
1691 CreateTestPublicKeyManagerFipsCompatible(), true)
1692 .ok());
1693 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1694 CreateTestPrivateKeyManagerFipsCompatible(),
1695 CreateTestPublicKeyManagerFipsCompatible(), false)
1696 .ok());
1697
1698 KeyTemplate key_template;
1699 key_template.set_type_url(TestPrivateKeyTypeManager().get_key_type());
1700 EXPECT_THAT(
1701 Registry::NewKeyData(key_template).status(),
1702 StatusIs(absl::StatusCode::kInvalidArgument, HasSubstr("not allow")));
1703 }
1704
TEST_F(RegistryTest,AsymmetricGetPublicKeyData)1705 TEST_F(RegistryTest, AsymmetricGetPublicKeyData) {
1706 if (kUseOnlyFips && !IsFipsEnabledInSsl()) {
1707 GTEST_SKIP() << "Not supported if FIPS-mode is used and BoringCrypto is "
1708 "not available";
1709 }
1710
1711 crypto::tink::util::Status status = Registry::RegisterAsymmetricKeyManagers(
1712 CreateTestPrivateKeyManagerFipsCompatible(),
1713 CreateTestPublicKeyManagerFipsCompatible(), true);
1714 EcdsaPrivateKey private_key;
1715 private_key.mutable_public_key()->mutable_params()->set_encoding(
1716 EcdsaSignatureEncoding::DER);
1717
1718 std::unique_ptr<KeyData> key_data =
1719 Registry::GetPublicKeyData(TestPrivateKeyTypeManager().get_key_type(),
1720 private_key.SerializeAsString())
1721 .value();
1722 ASSERT_THAT(key_data->type_url(),
1723 Eq(TestPublicKeyTypeManager().get_key_type()));
1724 EcdsaPublicKey public_key;
1725 public_key.ParseFromString(key_data->value());
1726 EXPECT_THAT(public_key.params().encoding(), Eq(EcdsaSignatureEncoding::DER));
1727 }
1728
1729 class TestPrivateKeyTypeManager2 : public TestPrivateKeyTypeManager {};
1730 class TestPublicKeyTypeManager2 : public TestPublicKeyTypeManager {};
1731
TEST_F(RegistryTest,RegisterAssymmetricReregistrationWithWrongClasses)1732 TEST_F(RegistryTest, RegisterAssymmetricReregistrationWithWrongClasses) {
1733 if (kUseOnlyFips) {
1734 GTEST_SKIP() << "Not supported in FIPS-only mode";
1735 }
1736
1737 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1738 absl::make_unique<TestPrivateKeyTypeManager>(),
1739 absl::make_unique<TestPublicKeyTypeManager>(), true)
1740 .ok());
1741 EXPECT_THAT(Registry::RegisterAsymmetricKeyManagers(
1742 absl::make_unique<TestPrivateKeyTypeManager2>(),
1743 absl::make_unique<TestPublicKeyTypeManager>(), true),
1744 StatusIs(absl::StatusCode::kAlreadyExists,
1745 HasSubstr("already registered")));
1746 EXPECT_THAT(Registry::RegisterAsymmetricKeyManagers(
1747 absl::make_unique<TestPrivateKeyTypeManager>(),
1748 absl::make_unique<TestPublicKeyTypeManager2>(), true),
1749 StatusIs(absl::StatusCode::kAlreadyExists,
1750 HasSubstr("already registered")));
1751 EXPECT_THAT(Registry::RegisterAsymmetricKeyManagers(
1752 absl::make_unique<TestPrivateKeyTypeManager2>(),
1753 absl::make_unique<TestPublicKeyTypeManager2>(), true),
1754 StatusIs(absl::StatusCode::kAlreadyExists,
1755 HasSubstr("already registered")));
1756 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1757 absl::make_unique<TestPrivateKeyTypeManager2>(), true),
1758 StatusIs(absl::StatusCode::kAlreadyExists,
1759 HasSubstr("already registered")));
1760 EXPECT_THAT(Registry::RegisterKeyTypeManager(
1761 absl::make_unique<TestPublicKeyTypeManager2>(), true),
1762 StatusIs(absl::StatusCode::kAlreadyExists,
1763 HasSubstr("already registered")));
1764 }
1765
1766 class TestPublicKeyTypeManagerWithDifferentKeyType
1767 : public TestPublicKeyTypeManager {
get_key_type() const1768 const std::string& get_key_type() const override { return kKeyType; }
1769
1770 private:
1771 const std::string kKeyType = "bla";
1772 };
1773
TEST_F(RegistryTest,RegisterAssymmetricReregistrationWithNewKeyType)1774 TEST_F(RegistryTest, RegisterAssymmetricReregistrationWithNewKeyType) {
1775 if (kUseOnlyFips) {
1776 GTEST_SKIP() << "Not supported in FIPS-only mode";
1777 }
1778
1779 ASSERT_TRUE(Registry::RegisterAsymmetricKeyManagers(
1780 absl::make_unique<TestPrivateKeyTypeManager>(),
1781 absl::make_unique<TestPublicKeyTypeManager>(), true)
1782 .ok());
1783 EXPECT_THAT(
1784 Registry::RegisterAsymmetricKeyManagers(
1785 absl::make_unique<TestPrivateKeyTypeManager>(),
1786 absl::make_unique<TestPublicKeyTypeManagerWithDifferentKeyType>(),
1787 true),
1788 StatusIs(absl::StatusCode::kInvalidArgument,
1789 HasSubstr("impossible to register")));
1790 }
1791
1792 // The DelegatingKeyTypeManager calls the registry
1793 class DelegatingKeyTypeManager
1794 : public PrivateKeyTypeManager<EcdsaPrivateKey, EcdsaKeyFormat,
1795 EcdsaPublicKey, List<>> {
1796 public:
DelegatingKeyTypeManager()1797 DelegatingKeyTypeManager() : PrivateKeyTypeManager() {}
1798
set_registry(RegistryImpl * registry)1799 void set_registry(RegistryImpl* registry) { registry_ = registry; }
1800
key_material_type() const1801 google::crypto::tink::KeyData::KeyMaterialType key_material_type()
1802 const override {
1803 return google::crypto::tink::KeyData::SYMMETRIC;
1804 }
1805
get_version() const1806 uint32_t get_version() const override { return kVersion; }
1807
get_key_type() const1808 const std::string& get_key_type() const override { return kKeyType; }
1809
ValidateKey(const EcdsaPrivateKey & key) const1810 crypto::tink::util::Status ValidateKey(
1811 const EcdsaPrivateKey& key) const override {
1812 return util::OkStatus();
1813 }
1814
ValidateKeyFormat(const EcdsaKeyFormat & key_format) const1815 crypto::tink::util::Status ValidateKeyFormat(
1816 const EcdsaKeyFormat& key_format) const override {
1817 return util::OkStatus();
1818 }
1819
CreateKey(const EcdsaKeyFormat & key_format) const1820 crypto::tink::util::StatusOr<EcdsaPrivateKey> CreateKey(
1821 const EcdsaKeyFormat& key_format) const override {
1822 AesGcmKeyFormat format;
1823 KeyTemplate key_template;
1824 key_template.set_type_url(
1825 "type.googleapis.com/google.crypto.tink.AesGcmKey");
1826 key_template.set_value(format.SerializeAsString());
1827 auto result = registry_->NewKeyData(key_template);
1828 if (!result.ok()) return result.status();
1829 // Return a string we can check for.
1830 return util::Status(absl::StatusCode::kDeadlineExceeded,
1831 "CreateKey worked");
1832 }
1833
DeriveKey(const EcdsaKeyFormat & key_format,InputStream * input_stream) const1834 crypto::tink::util::StatusOr<EcdsaPrivateKey> DeriveKey(
1835 const EcdsaKeyFormat& key_format,
1836 InputStream* input_stream) const override {
1837 AesGcmKeyFormat format;
1838 KeyTemplate key_template;
1839 key_template.set_type_url(
1840 "type.googleapis.com/google.crypto.tink.AesGcmKey");
1841 key_template.set_value(format.SerializeAsString());
1842
1843 auto result = registry_->DeriveKey(key_template, input_stream);
1844 if (!result.ok()) return result.status();
1845 // Return a string we can check for.
1846 return util::Status(absl::StatusCode::kDeadlineExceeded,
1847 "DeriveKey worked");
1848 }
1849
GetPublicKey(const EcdsaPrivateKey & private_key) const1850 crypto::tink::util::StatusOr<EcdsaPublicKey> GetPublicKey(
1851 const EcdsaPrivateKey& private_key) const override {
1852 AesGcmKeyFormat format;
1853 KeyTemplate key_template;
1854 key_template.set_type_url(
1855 "type.googleapis.com/google.crypto.tink.AesGcmKey");
1856 key_template.set_value(format.SerializeAsString());
1857 auto result = registry_->NewKeyData(key_template);
1858 if (!result.ok()) return result.status();
1859 // Return a string we can check for.
1860 return util::Status(absl::StatusCode::kDeadlineExceeded,
1861 "GetPublicKey worked");
1862 }
1863
1864 private:
1865 RegistryImpl* registry_;
1866
1867 static constexpr int kVersion = 0;
1868 const std::string kKeyType =
1869 "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey";
1870 };
1871
1872 class RegistryImplTest : public ::testing::Test {
1873 protected:
TearDown()1874 void TearDown() override {
1875 // Calling RestrictToFipsIfEmpty() may call SetFipsRestricted(), which
1876 // set a global variable to true. We have to reset that after the test.
1877 UnSetFipsRestricted();
1878 }
1879 };
1880
1881 // Check that we can call the registry again from within NewKeyData
TEST_F(RegistryImplTest,CanDelegateCreateKey)1882 TEST_F(RegistryImplTest, CanDelegateCreateKey) {
1883 if (kUseOnlyFips) {
1884 GTEST_SKIP() << "Not supported in FIPS-only mode";
1885 }
1886
1887 RegistryImpl registry_impl;
1888 auto delegating_key_manager = absl::make_unique<DelegatingKeyTypeManager>();
1889 delegating_key_manager->set_registry(®istry_impl);
1890 auto status =
1891 registry_impl
1892 .RegisterKeyTypeManager<EcdsaPrivateKey, EcdsaKeyFormat, List<>>(
1893 std::move(delegating_key_manager), true);
1894 EXPECT_THAT(status, IsOk());
1895 status = registry_impl.RegisterKeyTypeManager<AesGcmKey, AesGcmKeyFormat,
1896 List<Aead, AeadVariant>>(
1897 absl::make_unique<ExampleKeyTypeManager>(), true);
1898 EXPECT_THAT(status, IsOk());
1899
1900 EcdsaKeyFormat format;
1901 KeyTemplate key_template;
1902 key_template.set_type_url(
1903 "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey");
1904 key_template.set_value(format.SerializeAsString());
1905 EXPECT_THAT(registry_impl.NewKeyData(key_template).status(),
1906 StatusIs(absl::StatusCode::kDeadlineExceeded,
1907 HasSubstr("CreateKey worked")));
1908 }
1909
1910 // Check that we can call the registry again from within NewKeyData
TEST_F(RegistryImplTest,CanDelegateDeriveKey)1911 TEST_F(RegistryImplTest, CanDelegateDeriveKey) {
1912 if (kUseOnlyFips) {
1913 GTEST_SKIP() << "Not supported in FIPS-only mode";
1914 }
1915
1916 RegistryImpl registry_impl;
1917 auto delegating_key_manager = absl::make_unique<DelegatingKeyTypeManager>();
1918 delegating_key_manager->set_registry(®istry_impl);
1919 auto status =
1920 registry_impl
1921 .RegisterKeyTypeManager<EcdsaPrivateKey, EcdsaKeyFormat, List<>>(
1922 std::move(delegating_key_manager), true);
1923 EXPECT_THAT(status, IsOk());
1924 status = registry_impl.RegisterKeyTypeManager<AesGcmKey, AesGcmKeyFormat,
1925 List<Aead, AeadVariant>>(
1926 absl::make_unique<ExampleKeyTypeManager>(), true);
1927 EXPECT_THAT(status, IsOk());
1928
1929 EcdsaKeyFormat format;
1930 KeyTemplate key_template;
1931 key_template.set_type_url(
1932 "type.googleapis.com/google.crypto.tink.EcdsaPrivateKey");
1933 key_template.set_value(format.SerializeAsString());
1934 EXPECT_THAT(registry_impl.DeriveKey(key_template, nullptr).status(),
1935 StatusIs(absl::StatusCode::kDeadlineExceeded,
1936 HasSubstr("DeriveKey worked")));
1937 }
1938
TEST_F(RegistryImplTest,CanDelegateGetPublicKey)1939 TEST_F(RegistryImplTest, CanDelegateGetPublicKey) {
1940 if (kUseOnlyFips) {
1941 GTEST_SKIP() << "Not supported in FIPS-only mode";
1942 }
1943
1944 RegistryImpl registry_impl;
1945 auto delegating_key_manager = absl::make_unique<DelegatingKeyTypeManager>();
1946 delegating_key_manager->set_registry(®istry_impl);
1947 auto status = registry_impl.RegisterAsymmetricKeyManagers(
1948 delegating_key_manager.release(),
1949 absl::make_unique<TestPublicKeyTypeManager>().release(), true);
1950 EXPECT_THAT(status, IsOk());
1951 status = registry_impl.RegisterKeyTypeManager<AesGcmKey, AesGcmKeyFormat,
1952 List<Aead, AeadVariant>>(
1953 absl::make_unique<ExampleKeyTypeManager>(), true);
1954 EXPECT_THAT(status, IsOk());
1955
1956 EcdsaPrivateKey private_key;
1957 private_key.mutable_public_key()->mutable_params()->set_encoding(
1958 EcdsaSignatureEncoding::DER);
1959
1960 EXPECT_THAT(registry_impl
1961 .GetPublicKeyData(DelegatingKeyTypeManager().get_key_type(),
1962 private_key.SerializeAsString())
1963 .status(),
1964 StatusIs(absl::StatusCode::kDeadlineExceeded,
1965 HasSubstr("GetPublicKey worked")));
1966 }
1967
TEST_F(RegistryImplTest,FipsRestrictionSucceedsOnEmptyRegistry)1968 TEST_F(RegistryImplTest, FipsRestrictionSucceedsOnEmptyRegistry) {
1969 RegistryImpl registry_impl;
1970 EXPECT_THAT(registry_impl.RestrictToFipsIfEmpty(), IsOk());
1971 }
1972
TEST_F(RegistryImplTest,FipsRestrictionSucceedsWhenSettingMultipleTimes)1973 TEST_F(RegistryImplTest, FipsRestrictionSucceedsWhenSettingMultipleTimes) {
1974 RegistryImpl registry_impl;
1975 EXPECT_THAT(registry_impl.RestrictToFipsIfEmpty(), IsOk());
1976 EXPECT_THAT(registry_impl.RestrictToFipsIfEmpty(), IsOk());
1977 EXPECT_THAT(registry_impl.RestrictToFipsIfEmpty(), IsOk());
1978 }
1979
TEST_F(RegistryImplTest,FipsRestrictionSucceedsIfBuildInFipsMode)1980 TEST_F(RegistryImplTest, FipsRestrictionSucceedsIfBuildInFipsMode) {
1981 if (!kUseOnlyFips) {
1982 GTEST_SKIP() << "Not supported when Tink is not built in FIPS mode.";
1983 }
1984 RegistryImpl registry_impl;
1985 EXPECT_THAT(registry_impl.RestrictToFipsIfEmpty(), IsOk());
1986 }
1987
TEST_F(RegistryImplTest,FipsFailsIfNotEmpty)1988 TEST_F(RegistryImplTest, FipsFailsIfNotEmpty) {
1989 if (kUseOnlyFips) {
1990 GTEST_SKIP() << "Not supported in FIPS-only mode";
1991 }
1992
1993 auto fips_key_manager = absl::make_unique<ExampleKeyTypeManager>();
1994 ON_CALL(*fips_key_manager, FipsStatus())
1995 .WillByDefault(testing::Return(FipsCompatibility::kRequiresBoringCrypto));
1996
1997 RegistryImpl registry_impl;
1998 auto status = registry_impl.RegisterKeyTypeManager<AesGcmKey, AesGcmKeyFormat,
1999 List<Aead, AeadVariant>>(
2000 std::move(fips_key_manager), true);
2001 EXPECT_THAT(status, IsOk());
2002 EXPECT_THAT(registry_impl.RestrictToFipsIfEmpty(),
2003 StatusIs(absl::StatusCode::kInternal));
2004 }
2005
TEST_F(RegistryImplTest,CanRegisterOnlyOneMonitoringFactory)2006 TEST_F(RegistryImplTest, CanRegisterOnlyOneMonitoringFactory) {
2007 auto monitoring_client_factory =
2008 absl::make_unique<MockMonitoringClientFactory>();
2009
2010 RegistryImpl registry_impl;
2011 EXPECT_THAT(registry_impl.RegisterMonitoringClientFactory(
2012 std::move(monitoring_client_factory)),
2013 IsOk());
2014 ASSERT_THAT(registry_impl.GetMonitoringClientFactory(), Not(IsNull()));
2015 EXPECT_THAT(registry_impl.RegisterMonitoringClientFactory(
2016 std::move(monitoring_client_factory)),
2017 StatusIs(absl::StatusCode::kAlreadyExists));
2018 }
2019
2020 } // namespace
2021 } // namespace internal
2022 } // namespace tink
2023 } // namespace crypto
2024