File: os_crypt_async_unittest.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (941 lines) | stat: -rw-r--r-- 36,189 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
// Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/os_crypt/async/browser/os_crypt_async.h"

#include <optional>

#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/task_environment.h"
#include "base/test/test_future.h"
#include "components/os_crypt/async/browser/key_provider.h"
#include "components/os_crypt/async/browser/test_utils.h"
#include "components/os_crypt/async/common/algorithm.mojom.h"
#include "components/os_crypt/async/common/encryptor.h"
#include "components/os_crypt/sync/os_crypt.h"
#include "components/os_crypt/sync/os_crypt_mocker.h"
#include "crypto/hkdf.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_LINUX)
#include "components/os_crypt/sync/key_storage_linux.h"
#endif

namespace os_crypt_async {

class OSCryptAsyncTest : public ::testing::Test {
 protected:
  using ProviderList =
      std::vector<std::pair<size_t, std::unique_ptr<KeyProvider>>>;

  Encryptor GetInstanceSync(
      OSCryptAsync& factory,
      Encryptor::Option option = Encryptor::Option::kNone) {
    base::test::TestFuture<Encryptor> future;
    factory.GetInstance(future.GetCallback(), option);
    return future.Take();
  }

  // Simulate a 'locked' OSCrypt keychain on platforms that need it, which makes
  // OSCrypt::IsEncryptionAvailable return false, without hitting a CHECK on
  // Linux. Note this is different from using the full OSCryptMocker, because in
  // this state, no key is available for encryption. Returns a
  // ScopedClosureRunner that will reset the behavior back to default when it
  // goes out of scope.
  [[nodiscard]] static std::optional<base::ScopedClosureRunner>
  MaybeSimulateLockedKeyChain() {
#if BUILDFLAG(IS_LINUX)
    OSCrypt::UseMockKeyStorageForTesting(base::BindOnce(
        []() -> std::unique_ptr<KeyStorageLinux> { return nullptr; }));
    return std::nullopt;
#elif BUILDFLAG(IS_APPLE)
    OSCrypt::UseLockedMockKeychainForTesting(/*use_locked=*/true);
    return base::ScopedClosureRunner(base::BindOnce([]() {
      OSCrypt::UseLockedMockKeychainForTesting(/*use_locked=*/false);
    }));
#elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
    OSCrypt::SetEncryptionAvailableForTesting(/*available=*/false);
    return base::ScopedClosureRunner(base::BindOnce([]() {
      OSCrypt::SetEncryptionAvailableForTesting(/*available=*/std::nullopt);
    }));
#else
    return std::nullopt;
#endif
  }

  base::test::TaskEnvironment task_environment_;
};

class TestKeyProvider : public KeyProvider {
 public:
  TestKeyProvider(const std::string& name,
                  bool use_for_encryption,
                  bool compatible_with_os_crypt_sync = false)
      : name_(name),
        use_for_encryption_(use_for_encryption),
        compatible_with_os_crypt_sync_(compatible_with_os_crypt_sync) {}

 protected:
  TestKeyProvider()
      : name_("TEST"),
        use_for_encryption_(true),
        compatible_with_os_crypt_sync_(false) {}

  Encryptor::Key GenerateKey() {
    // Make the key derive from the name to ensure different providers have
    // different keys.
    std::string key = crypto::HkdfSha256(name_, "salt", "info",
                                         Encryptor::Key::kAES256GCMKeySize);
    return Encryptor::Key(std::vector<uint8_t>(key.begin(), key.end()),
                          mojom::Algorithm::kAES256GCM);
  }

  const std::string name_;

 private:
  void GetKey(KeyCallback callback) override {
    std::move(callback).Run(name_, GenerateKey());
  }

  bool UseForEncryption() override { return use_for_encryption_; }
  bool IsCompatibleWithOsCryptSync() override {
    return compatible_with_os_crypt_sync_;
  }

  const bool use_for_encryption_;
  const bool compatible_with_os_crypt_sync_;
};

TEST_F(OSCryptAsyncTest, EncryptHeader) {
  const std::string kTestProviderName("TEST");
  ProviderList providers;
  providers.emplace_back(
      std::make_pair(10u, std::make_unique<TestKeyProvider>(
                              kTestProviderName, /*use_for_encryption=*/true)));
  OSCryptAsync factory(std::move(providers));
  Encryptor encryptor = GetInstanceSync(factory);

  auto ciphertext = encryptor.EncryptString("secrets");
  ASSERT_TRUE(std::equal(kTestProviderName.cbegin(), kTestProviderName.cend(),
                         ciphertext->cbegin()));
}

TEST_F(OSCryptAsyncTest, TwoProvidersBothEnabled) {
  std::optional<std::vector<uint8_t>> ciphertext;
  {
    const std::string kFooProviderName("FOO");
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u, std::make_unique<TestKeyProvider>(
                                kFooProviderName, /*use_for_encryption=*/true));
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("BAR", /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);

    ciphertext = encryptor.EncryptString("secrets");
    ASSERT_TRUE(ciphertext);
    // The higher of the two providers should have been picked for data
    // encryption.
    EXPECT_TRUE(std::equal(kFooProviderName.cbegin(), kFooProviderName.cend(),
                           ciphertext->cbegin()));
  }
  // Check that provider precedence does not matter for decrypt.
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("FOO", /*use_for_encryption=*/true));
    // BAR is the preferred provider since it has the higher precedence.
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<TestKeyProvider>("BAR", /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);

    auto plaintext = encryptor.DecryptData(*ciphertext);
    // The correct provider based on the encrypted data header should have been
    // picked for data decryption.
    ASSERT_TRUE(plaintext);
    EXPECT_EQ("secrets", *plaintext);
  }
  // Check that order of providers does not affect which one is chosen for
  // encrypt operations.
  {
    const std::string kFooProviderName("FOO");
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("BAR", /*use_for_encryption=*/true));
    providers.emplace_back(
        /*precedence=*/10u, std::make_unique<TestKeyProvider>(
                                kFooProviderName, /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);

    ciphertext = encryptor.EncryptString("secrets");
    ASSERT_TRUE(ciphertext);
    // The higher of the two providers should have been picked for data
    // encryption.
    EXPECT_TRUE(std::equal(kFooProviderName.cbegin(), kFooProviderName.cend(),
                           ciphertext->cbegin()));
  }
}

TEST_F(OSCryptAsyncTest, TwoProvidersOneEnabled) {
  std::optional<std::vector<uint8_t>> ciphertext;
  {
    const std::string kBarProviderName("BAR");
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<TestKeyProvider>("FOO", /*use_for_encryption=*/false));
    providers.emplace_back(
        /*precedence=*/5u, std::make_unique<TestKeyProvider>(
                               kBarProviderName, /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);

    ciphertext = encryptor.EncryptString("secrets");
    ASSERT_TRUE(ciphertext);
    // Despite FOO being higher than BAR, BAR is chosen for encryption because
    // FOO is not enabled for encryption.
    EXPECT_TRUE(std::equal(kBarProviderName.cbegin(), kBarProviderName.cend(),
                           ciphertext->cbegin()));
  }
  // Check that even with no enabled providers, data can still be decrypted by
  // any registered provider.
  {
    ProviderList providers;
    // Neither is enabled for encrypt.
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("FOO", /*use_for_encryption=*/false));
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<TestKeyProvider>("BAR", /*use_for_encryption=*/false));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);

    auto plaintext = encryptor.DecryptData(*ciphertext);
    // The correct provider based on the encrypted data header should have been
    // picked for data decryption.
    ASSERT_TRUE(plaintext);
    EXPECT_EQ("secrets", *plaintext);
  }
}

class OSCryptAsyncTestSwapped
    : public OSCryptAsyncTest,
      public ::testing::WithParamInterface</*switched=*/bool> {};

TEST_P(OSCryptAsyncTestSwapped, EncryptorOption) {
  std::string first_provider_name("TEST");
  std::string second_provider_name("BLAH");

  // This tests std::map ordering does not matter.
  if (GetParam()) {
    first_provider_name = "BLAH";
    second_provider_name = "TEST";
  }

  std::optional<std::vector<uint8_t>> first_ciphertext, second_ciphertext;
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<TestKeyProvider>(first_provider_name,
                                          /*use_for_encryption=*/true));
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>(
            second_provider_name, /*use_for_encryption=*/true,
            /*compatible_with_os_crypt_sync=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);

    first_ciphertext = encryptor.EncryptString("secrets");
    ASSERT_TRUE(first_ciphertext);
    // First provider should be picked, because it has a higher precedence than
    // the second.
    EXPECT_TRUE(std::equal(first_provider_name.cbegin(),
                           first_provider_name.cend(),
                           first_ciphertext->cbegin()));

    // Now obtain an encryptor with a compatibility option.
    Encryptor encryptor_compat =
        GetInstanceSync(factory, Encryptor::Option::kEncryptSyncCompat);
    second_ciphertext = encryptor_compat.EncryptString("secrets");
    ASSERT_TRUE(second_ciphertext);
    // Should be encrypted with second key now.
    EXPECT_TRUE(std::equal(second_provider_name.cbegin(),
                           second_provider_name.cend(),
                           second_ciphertext->cbegin()));
  }
  // Check that with just second provider, data can still be decrypted.
  {
    auto cleanup = MaybeSimulateLockedKeyChain();
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>(second_provider_name,
                                          /*use_for_encryption=*/false));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);

    // The only provider has indicated that it is not to be used for encryption,
    // so encryption should not be available, as OSCrypt fallback is not
    // available.
    ASSERT_FALSE(encryptor.IsEncryptionAvailable());
    // Decryption is possible, as long as the data is encrypted with the second
    // key.
    ASSERT_TRUE(encryptor.IsDecryptionAvailable());

    auto plaintext = encryptor.DecryptData(*second_ciphertext);
    // The correct provider based on the encrypted data header should have been
    // picked for data decryption.
    ASSERT_TRUE(plaintext);
    EXPECT_EQ("secrets", *plaintext);

    // The first data that was encrypted with v20 cannot be decrypted.
    auto failing_plaintext = encryptor.DecryptData(*first_ciphertext);
    EXPECT_FALSE(failing_plaintext);
  }
  // Test also that if there are multiple key providers with
  // compatible_with_os_crypt_sync then the highest precedence is picked.
  {
    ProviderList providers;
    providers.emplace_back(/*precedence=*/10u,
                           std::make_unique<TestKeyProvider>(
                               first_provider_name, /*use_for_encryption=*/true,
                               /*compatible_with_os_crypt_sync=*/true));
    providers.emplace_back(/*precedence=*/8u,
                           std::make_unique<TestKeyProvider>(
                               "FOO", /*use_for_encryption=*/true,
                               /*compatible_with_os_crypt_sync=*/false));
    providers.emplace_back(/*precedence=*/5u,
                           std::make_unique<TestKeyProvider>(
                               "BAR", /*use_for_encryption=*/true,
                               /*compatible_with_os_crypt_sync=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor =
        GetInstanceSync(factory, Encryptor::Option::kEncryptSyncCompat);
    const auto ciphertext = encryptor.EncryptString("secrets");
    ASSERT_TRUE(ciphertext);
    // Should be encrypted with first provider - it's the highest precedence
    // provider that indicates it's compatible with OSCrypt sync.
    EXPECT_TRUE(std::equal(first_provider_name.cbegin(),
                           first_provider_name.cend(), ciphertext->cbegin()));
  }
  // Just in case, test that order doesn't matter here, although this is also
  // tested elsewhere.
  {
    ProviderList providers;
    providers.emplace_back(/*precedence=*/5u,
                           std::make_unique<TestKeyProvider>(
                               "BAR", /*use_for_encryption=*/true,
                               /*compatible_with_os_crypt_sync=*/true));
    providers.emplace_back(/*precedence=*/8u,
                           std::make_unique<TestKeyProvider>(
                               "FOO", /*use_for_encryption=*/true,
                               /*compatible_with_os_crypt_sync=*/false));
    providers.emplace_back(/*precedence=*/10u,
                           std::make_unique<TestKeyProvider>(
                               first_provider_name, /*use_for_encryption=*/true,
                               /*compatible_with_os_crypt_sync=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor =
        GetInstanceSync(factory, Encryptor::Option::kEncryptSyncCompat);
    const auto ciphertext = encryptor.EncryptString("secrets");
    ASSERT_TRUE(ciphertext);
    // Should be encrypted with first provider - it's the highest precedence
    // provider that indicates it's compatible with OSCrypt sync.
    EXPECT_TRUE(std::equal(first_provider_name.cbegin(),
                           first_provider_name.cend(), ciphertext->cbegin()));
  }
}

INSTANTIATE_TEST_SUITE_P(, OSCryptAsyncTestSwapped, ::testing::Bool());

class SlowTestKeyProvider : public TestKeyProvider {
 public:
  explicit SlowTestKeyProvider(base::TimeDelta sleep_time) {}

 private:
  void GetKey(KeyCallback callback) override {
    base::SequencedTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(
            [](KeyCallback callback, Encryptor::Key key,
               const std::string& name) {
              std::move(callback).Run(name, std::move(key));
            },
            std::move(callback), GenerateKey(), name_),
        sleep_time_);
  }

  const base::TimeDelta sleep_time_;
};

// This test verifies that GetInstanceAsync can correctly handle multiple queued
// requests for an instance for a slow init.
TEST_F(OSCryptAsyncTest, MultipleCalls) {
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<SlowTestKeyProvider>(base::Seconds(1)));
  OSCryptAsync factory(std::move(providers));

  size_t calls = 0;
  const size_t kExpectedCalls = 10;
  base::RunLoop run_loop;
  for (size_t call = 0; call < kExpectedCalls; call++) {
    factory.GetInstance(
        base::BindLambdaForTesting([&calls, &run_loop](Encryptor encryptor) {
          calls++;
          if (calls == kExpectedCalls) {
            run_loop.Quit();
          }
        }));
  }
  run_loop.Run();
  EXPECT_EQ(calls, kExpectedCalls);
}

TEST_F(OSCryptAsyncTest, TestOSCryptAsyncInterface) {
  auto os_crypt = GetTestOSCryptAsyncForTesting();
  auto encryptor = GetInstanceSync(*os_crypt);
  auto ciphertext = encryptor.EncryptString("testsecrets");
  ASSERT_TRUE(ciphertext);
  {
    auto decrypted = encryptor.DecryptData(*ciphertext);
    ASSERT_TRUE(decrypted);
    EXPECT_EQ(*decrypted, "testsecrets");
  }
  {
    // Verify that all encryptors returned by the test OSCryptAsync instance use
    // the same keys.
    auto second_encryptor = GetInstanceSync(*os_crypt);
    auto decrypted = second_encryptor.DecryptData(*ciphertext);
    ASSERT_TRUE(decrypted);
    EXPECT_EQ(*decrypted, "testsecrets");
  }
  {
    // Verify that the key used by the encryptor returned from the testing
    // instance indicates compatibility with OSCrypt Sync. This avoids all tests
    // having to install the OSCrypt mocker in every fixture.
    const auto os_crypt_compat_encryptor =
        GetInstanceSync(*os_crypt, Encryptor::Option::kEncryptSyncCompat);
    {
      Encryptor::DecryptFlags flags;
      const auto decrypted =
          os_crypt_compat_encryptor.DecryptData(*ciphertext, &flags);
      ASSERT_TRUE(decrypted);
      // Switching from kNone to kEncryptSyncCompat should result in the data
      // needing to be re-encrypted.
      EXPECT_TRUE(flags.should_reencrypt);
      EXPECT_EQ(*decrypted, "testsecrets");
    }
    {
      // Encrypt with the OSCrypt Sync compat one, then decrypt with the new
      // one, which should signal again that the data needs to be re-encrypted.
      const auto os_crypt_compat_ciphertext =
          os_crypt_compat_encryptor.EncryptString("moresecret");
      ASSERT_TRUE(os_crypt_compat_ciphertext);
      Encryptor::DecryptFlags flags;
      const auto decrypted =
          encryptor.DecryptData(*os_crypt_compat_ciphertext, &flags);
      ASSERT_TRUE(decrypted);
      EXPECT_TRUE(flags.should_reencrypt);
      EXPECT_EQ(*decrypted, "moresecret");
    }
  }
  {
    auto another_encryptor =
        GetInstanceSync(*os_crypt, Encryptor::Option::kEncryptSyncCompat);
    auto decrypted = another_encryptor.DecryptData(*ciphertext);
    ASSERT_TRUE(decrypted);
    EXPECT_EQ(*decrypted, "testsecrets");
  }
}

TEST_F(OSCryptAsyncTest, TestEncryptorInterface) {
  auto encryptor = GetTestEncryptorForTesting();
  auto ciphertext = encryptor.EncryptString("testsecrets");
  ASSERT_TRUE(ciphertext);
  auto decrypted = encryptor.DecryptData(*ciphertext);
  ASSERT_TRUE(decrypted);
  EXPECT_EQ(*decrypted, "testsecrets");
}

TEST_F(OSCryptAsyncTest, TestEncryptorIsEncryptionAvailable) {
  auto encryptor = GetTestEncryptorForTesting();

  EXPECT_TRUE(encryptor.IsDecryptionAvailable());
  encryptor.set_decryption_available_for_testing(false);
  EXPECT_FALSE(encryptor.IsDecryptionAvailable());

  encryptor.set_decryption_available_for_testing(std::nullopt);
  EXPECT_TRUE(encryptor.IsDecryptionAvailable());

  EXPECT_TRUE(encryptor.IsEncryptionAvailable());
  encryptor.set_encryption_available_for_testing(false);
  EXPECT_FALSE(encryptor.IsEncryptionAvailable());

  encryptor.set_encryption_available_for_testing(std::nullopt);
  EXPECT_TRUE(encryptor.IsEncryptionAvailable());
}

class FailingKeyProvider : public TestKeyProvider {
 public:
  FailingKeyProvider(KeyProvider::KeyError reason, const std::string& name)
      : reason_(reason), name_(name) {}

 private:
  void GetKey(KeyCallback callback) override {
    std::move(callback).Run(name_, base::unexpected(reason_));
  }

  const KeyProvider::KeyError reason_;
  const std::string name_;
};

// Some tests require a working OSCrypt.
class OSCryptAsyncTestWithOSCrypt : public OSCryptAsyncTest {
 protected:
  void SetUp() override { OSCryptMocker::SetUp(); }

  void TearDown() override {
    OSCryptMocker::TearDown();
#if BUILDFLAG(IS_WIN)
    OSCrypt::ResetStateForTesting();
#endif  // BUILDFLAG(IS_WIN)
  }
};

// This test merely verifies that OSCryptAsync can operate with no key providers
// and return a valid Encryptor with no keys, and that it can interop with
// OSCrypt. The rest of the encryption tests for this mode are located in
// encryptor_unittest.cc.
TEST_F(OSCryptAsyncTestWithOSCrypt, Empty) {
  base::HistogramTester histograms;
  ProviderList providers;
  OSCryptAsync factory(std::move(providers));
  Encryptor encryptor = GetInstanceSync(factory);
  {
    std::string ciphertext;
    EXPECT_TRUE(OSCrypt::EncryptString("secrets", &ciphertext));
    std::string plaintext;
    EXPECT_TRUE(encryptor.DecryptString(ciphertext, &plaintext));
    EXPECT_EQ("secrets", plaintext);
  }
  {
    const auto ciphertext = encryptor.EncryptString("moresecrets");
    ASSERT_TRUE(ciphertext.has_value());
    std::string plaintext;
    EXPECT_TRUE(OSCrypt::DecryptString(
        std::string(ciphertext->begin(), ciphertext->end()), &plaintext));
    EXPECT_EQ("moresecrets", plaintext);
  }
  histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount", 0, 1);
  histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount.Available", 0, 1);
  histograms.ExpectBucketCount(
      "OSCrypt.EncryptorKeyCount.TemporarilyUnavailable", 0, 1);
  histograms.ExpectBucketCount(
      "OSCrypt.EncryptorKeyCount.PermanentlyUnavailable", 0, 1);
}

TEST_F(OSCryptAsyncTestWithOSCrypt, FailingKeyProvider) {
  base::HistogramTester histograms;
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<FailingKeyProvider>(
          KeyProvider::KeyError::kPermanentlyUnavailable, "BLAH"));
  OSCryptAsync factory(std::move(providers));
  // TODO: Work out how best to handle provider failures.
  Encryptor encryptor = GetInstanceSync(factory);

  {
    // Encryption should still work, because an empty Encryptor is made which
    // falls back to OSCrypt.
    auto ciphertext = encryptor.EncryptString("secrets");
    EXPECT_TRUE(ciphertext);
    std::string plaintext;
    EXPECT_TRUE(OSCrypt::DecryptString(
        std::string(ciphertext->cbegin(), ciphertext->cend()), &plaintext));
    EXPECT_EQ("secrets", plaintext);
  }
  {
    std::string ciphertext;
    EXPECT_TRUE(OSCrypt::EncryptString("secrets", &ciphertext));
    std::string plaintext;
    // Decryption falls back to OSCrypt if there are no matching providers. In
    // this case, there are no providers at all.
    EXPECT_TRUE(encryptor.DecryptString(ciphertext, &plaintext));
    EXPECT_EQ("secrets", plaintext);
  }

  // Permanently failing key providers never get emplaced into the keyring at
  // all.
  histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount", 1, 1);
  histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount.Available", 0, 1);
  histograms.ExpectBucketCount(
      "OSCrypt.EncryptorKeyCount.TemporarilyUnavailable", 0, 1);
  histograms.ExpectBucketCount(
      "OSCrypt.EncryptorKeyCount.PermanentlyUnavailable", 1, 1);
}

TEST_F(OSCryptAsyncTestWithOSCrypt, TemporarilyFailingKeyProvider) {
  std::optional<std::vector<uint8_t>> ciphertext;

  // First, encrypt some data with the BLAH key provider.
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<TestKeyProvider>("BLAH", /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    ciphertext = encryptor.EncryptString("secrets");
    EXPECT_TRUE(ciphertext);
  }

  // Next, cause this key provider to fail temporarily. This should cause
  // decryption to fail but with kFailureKeyTemporarilyUnavailable.
  {
    base::HistogramTester histograms;
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<FailingKeyProvider>(
            KeyProvider::KeyError::kTemporarilyUnavailable, "BLAH"));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    Encryptor::DecryptFlags flags;
    const auto plaintext = encryptor.DecryptData(*ciphertext, &flags);
    EXPECT_FALSE(plaintext);
    EXPECT_TRUE(flags.temporarily_unavailable);

    // Encryption should still work, even with a temporarily failing key
    // provider, but it will delegate to OSCrypt.
    {
      const auto ciphertext2 = encryptor.EncryptString("secret");
      EXPECT_TRUE(ciphertext2);
      std::string plaintext2;
      EXPECT_TRUE(OSCrypt::DecryptString(
          std::string(ciphertext2->begin(), ciphertext2->end()), &plaintext2));
      EXPECT_EQ(plaintext2, "secret");
    }
    histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount", 1, 1);
    histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount.Available", 0, 1);
    histograms.ExpectBucketCount(
        "OSCrypt.EncryptorKeyCount.TemporarilyUnavailable", 1, 1);
    histograms.ExpectBucketCount(
        "OSCrypt.EncryptorKeyCount.PermanentlyUnavailable", 0, 1);
  }

  // Test permanently unavailable.
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<FailingKeyProvider>(
            KeyProvider::KeyError::kPermanentlyUnavailable, "BLAH"));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    Encryptor::DecryptFlags flags;
    const auto plaintext = encryptor.DecryptData(*ciphertext, &flags);
    // Since there is no key at all, this case has fallback to OSCrypt sync
    // which cannot decrypt data encrypted with BLAH key.
    EXPECT_FALSE(plaintext);
    EXPECT_FALSE(flags.temporarily_unavailable);

    // With no key provided at all (a permanent failure), encryption is
    // delegated to OSCrypt.
    {
      const auto ciphertext2 = encryptor.EncryptString("secret");
      EXPECT_TRUE(ciphertext2);
      std::string plaintext2;
      EXPECT_TRUE(OSCrypt::DecryptString(
          std::string(ciphertext2->begin(), ciphertext2->end()), &plaintext2));
      EXPECT_EQ(plaintext2, "secret");
    }
  }
}

TEST_F(OSCryptAsyncTest, MultipleKeysSomeTemporarilyUnavailable) {
  std::optional<std::vector<uint8_t>> ciphertext;
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<TestKeyProvider>("BLAH", /*use_for_encryption=*/true));
    // Note: TEST is higher precedence so would normally be picked for
    // encryption, were it not unavailable.
    providers.emplace_back(
        /*precedence=*/15u,
        std::make_unique<FailingKeyProvider>(
            KeyProvider::KeyError::kTemporarilyUnavailable, "TEST"));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    ciphertext = encryptor.EncryptString("secret data");
    EXPECT_TRUE(ciphertext);
  }

  // Verify that BLAH is used by creating a new encryptor with only BLAH and
  // decrypting.
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/10u,
        std::make_unique<TestKeyProvider>("BLAH", /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    const auto plaintext = encryptor.DecryptData(*ciphertext);
    EXPECT_TRUE(plaintext);
    EXPECT_EQ(*plaintext, "secret data");
  }
}

TEST_F(OSCryptAsyncTest, ShouldReencrypt) {
  std::string ciphertext;
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("BAR", /*use_for_encryption=*/true));
    providers.emplace_back(
        /*precedence=*/8u,
        std::make_unique<TestKeyProvider>("FOO", /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    ASSERT_TRUE(encryptor.EncryptString("secrets", &ciphertext));
    // FOO should be used, as it's the higher precedence.
    EXPECT_THAT(base::span(ciphertext).first<3>(),
                ::testing::ElementsAreArray(base::span_from_cstring("FOO")));
    std::string plaintext;
    Encryptor::DecryptFlags flags;
    ASSERT_TRUE(encryptor.DecryptString(ciphertext, &plaintext, &flags));
    EXPECT_EQ(plaintext, "secrets");
    EXPECT_FALSE(flags.should_reencrypt);
  }

  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("FOO", /*use_for_encryption=*/true));
    providers.emplace_back(
        /*precedence=*/8u,
        std::make_unique<TestKeyProvider>("BAR", /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    Encryptor::DecryptFlags flags;
    std::string plaintext;
    ASSERT_TRUE(encryptor.DecryptString(ciphertext, &plaintext, &flags));
    EXPECT_EQ(plaintext, "secrets");
    EXPECT_TRUE(flags.should_reencrypt);
  }
}

TEST_F(OSCryptAsyncTestWithOSCrypt, OSCryptShouldReencrypt) {
  std::string ciphertext;
  ASSERT_TRUE(OSCrypt::EncryptString("secrets", &ciphertext));

  {
    ProviderList providers;
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    std::string plaintext;
    Encryptor::DecryptFlags flags;
    // This encryptor has no providers, so falls back to OSCrypt Sync.
    ASSERT_TRUE(encryptor.DecryptString(ciphertext, &plaintext, &flags));
    EXPECT_EQ(plaintext, "secrets");
    EXPECT_FALSE(flags.should_reencrypt);
  }
  {
    ProviderList providers;
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("FOO", /*use_for_encryption=*/true));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    Encryptor::DecryptFlags flags;
    std::string plaintext;
    ASSERT_TRUE(encryptor.DecryptString(ciphertext, &plaintext, &flags));
    EXPECT_EQ(plaintext, "secrets");
    EXPECT_TRUE(flags.should_reencrypt);
  }
  {
    ProviderList providers;
    // Specify not to encrypt data with this provider.
    providers.emplace_back(
        /*precedence=*/5u,
        std::make_unique<TestKeyProvider>("FOO", /*use_for_encryption=*/false));
    OSCryptAsync factory(std::move(providers));
    Encryptor encryptor = GetInstanceSync(factory);
    Encryptor::DecryptFlags flags;
    std::string plaintext;
    ASSERT_TRUE(encryptor.DecryptString(ciphertext, &plaintext, &flags));
    EXPECT_EQ(plaintext, "secrets");
    EXPECT_FALSE(flags.should_reencrypt);
  }
}

// Test also that if no key providers have OSCrypt sync compatibility then
// encryption simply falls back to OSCrypt, and that OSCrypt can decrypt it
// fine.
TEST_F(OSCryptAsyncTestWithOSCrypt, EncryptorOption) {
  ProviderList providers;
  providers.emplace_back(/*precedence=*/5u,
                         std::make_unique<TestKeyProvider>(
                             "BAR", /*use_for_encryption=*/true,
                             /*compatible_with_os_crypt_sync=*/false));
  OSCryptAsync factory(std::move(providers));
  Encryptor encryptor =
      GetInstanceSync(factory, Encryptor::Option::kEncryptSyncCompat);
  const auto ciphertext = encryptor.EncryptString("os_crypt_secrets");
  ASSERT_TRUE(ciphertext);
  std::string plaintext;
  ASSERT_TRUE(OSCrypt::DecryptString(
      std::string(ciphertext->begin(), ciphertext->end()), &plaintext));
  EXPECT_EQ("os_crypt_secrets", plaintext);
}

using OSCryptAsyncDeathTest = OSCryptAsyncTest;

TEST_F(OSCryptAsyncDeathTest, SamePrecedence) {
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/5u,
      std::make_unique<TestKeyProvider>("A", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/20u,
      std::make_unique<TestKeyProvider>("B", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/5u,
      std::make_unique<TestKeyProvider>("C", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<TestKeyProvider>("D", /*use_for_encryption=*/true));
  EXPECT_DCHECK_DEATH_WITH({ OSCryptAsync factory(std::move(providers)); },
                           "Cannot have two providers with same precedence.");
}

TEST_F(OSCryptAsyncDeathTest, SameName) {
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/5u,
      std::make_unique<TestKeyProvider>("TEST", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<TestKeyProvider>("TEST", /*use_for_encryption=*/true));
  EXPECT_DCHECK_DEATH_WITH(
      {
        OSCryptAsync factory(std::move(providers));
        std::ignore = GetInstanceSync(factory);
      },
      "Tags must not overlap.");
}

TEST_F(OSCryptAsyncDeathTest, OverlappingNames) {
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/5u,
      std::make_unique<TestKeyProvider>("TEST", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<TestKeyProvider>("TEST2", /*use_for_encryption=*/true));
  EXPECT_DCHECK_DEATH_WITH(
      {
        OSCryptAsync factory(std::move(providers));
        std::ignore = GetInstanceSync(factory);
      },
      "Tags must not overlap.");
}

TEST_F(OSCryptAsyncDeathTest, OverlappingNamesBackwards) {
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/5u,
      std::make_unique<TestKeyProvider>("TEST2", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<TestKeyProvider>("TEST", /*use_for_encryption=*/true));
  EXPECT_DCHECK_DEATH_WITH(
      {
        OSCryptAsync factory(std::move(providers));
        std::ignore = GetInstanceSync(factory);
      },
      "Tags must not overlap.");
}

TEST_F(OSCryptAsyncDeathTest, EmptyProviderName) {
  ProviderList providers;
  providers.emplace_back(/*precedence=*/10u,
                         std::make_unique<TestKeyProvider>(
                             std::string(), /*use_for_encryption=*/true));
  EXPECT_DCHECK_DEATH_WITH(
      {
        OSCryptAsync factory(std::move(providers));
        std::ignore = GetInstanceSync(factory);
      },
      "Tag cannot be empty.");
}

TEST_F(OSCryptAsyncTest, NoCrashWithLongNames) {
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<TestKeyProvider>("ABC", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/5u,
      std::make_unique<TestKeyProvider>(
          "TEST_REALLY_LOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG_NAME",
          /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/15u,
      std::make_unique<TestKeyProvider>("XYZ", /*use_for_encryption=*/true));
  OSCryptAsync factory(std::move(providers));
  GetInstanceSync(factory);
}

TEST_F(OSCryptAsyncTest, Metrics) {
  base::HistogramTester histograms;
  ProviderList providers;
  providers.emplace_back(
      /*precedence=*/10u,
      std::make_unique<TestKeyProvider>("ABC", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/15u,
      std::make_unique<TestKeyProvider>("DEF", /*use_for_encryption=*/true));
  providers.emplace_back(
      /*precedence=*/20u,
      std::make_unique<FailingKeyProvider>(
          KeyProvider::KeyError::kPermanentlyUnavailable, "GHI"));
  providers.emplace_back(
      /*precedence=*/25u,
      std::make_unique<FailingKeyProvider>(
          KeyProvider::KeyError::kTemporarilyUnavailable, "JKL"));

  OSCryptAsync factory(std::move(providers));
  GetInstanceSync(factory);
  // See TemporarilyFailingKeyProvider, FailingKeyProvider and Empty tests above
  // for further testing of these counts.
  histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount", 4, 1);
  histograms.ExpectBucketCount("OSCrypt.EncryptorKeyCount.Available", 2, 1);
  histograms.ExpectBucketCount(
      "OSCrypt.EncryptorKeyCount.TemporarilyUnavailable", 1, 1);
  histograms.ExpectBucketCount(
      "OSCrypt.EncryptorKeyCount.PermanentlyUnavailable", 1, 1);
}

}  // namespace os_crypt_async