File: extension_platform_keys_service.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; 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 (1187 lines) | stat: -rw-r--r-- 41,686 bytes parent folder | download | duplicates (6)
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/platform_keys/extension_platform_keys_service.h"

#include <stddef.h>
#include <stdint.h>

#include <optional>
#include <string>
#include <utility>
#include <vector>

#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/values.h"
#include "chrome/browser/ash/crosapi/keystore_service_ash.h"
#include "chrome/browser/ash/crosapi/keystore_service_factory_ash.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/chromeos/platform_keys/extension_key_permissions_service.h"
#include "chrome/browser/chromeos/platform_keys/extension_key_permissions_service_factory.h"
#include "chrome/browser/chromeos/platform_keys/platform_keys.h"
#include "chrome/browser/profiles/profile.h"
#include "chromeos/constants/chromeos_features.h"
#include "chromeos/crosapi/cpp/keystore_service_util.h"
#include "chromeos/crosapi/mojom/keystore_error.mojom-shared.h"
#include "chromeos/crosapi/mojom/keystore_error.mojom.h"
#include "chromeos/crosapi/mojom/keystore_service.mojom.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_id.h"
#include "extensions/common/features/behavior_feature.h"
#include "extensions/common/features/feature.h"
#include "extensions/common/features/feature_provider.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/cert/x509_certificate.h"

using content::BrowserThread;
using crosapi::keystore_service_util::MakeEcdsaKeystoreAlgorithm;
using crosapi::keystore_service_util::MakeRsaOaepKeystoreAlgorithm;
using crosapi::keystore_service_util::MakeRsassaPkcs1v15KeystoreAlgorithm;
using crosapi::mojom::KeystoreAlgorithmPtr;
using crosapi::mojom::KeystoreBinaryResult;
using crosapi::mojom::KeystoreBinaryResultPtr;
using crosapi::mojom::KeystoreError;
using crosapi::mojom::KeystoreKeyAttributeType;
using crosapi::mojom::KeystoreSelectClientCertificatesResult;
using crosapi::mojom::KeystoreSelectClientCertificatesResultPtr;
using crosapi::mojom::KeystoreService;
using crosapi::mojom::KeystoreSigningScheme;
using crosapi::mojom::KeystoreType;

namespace chromeos {

namespace {

// Verify the allowlisted kKeyPermissionsInLoginScreen feature behaviors.
bool IsExtensionAllowlisted(const extensions::Extension* extension) {
  // Can be nullptr if the extension is uninstalled before the SignTask is
  // completed.
  if (!extension) {
    return false;
  }

  const extensions::Feature* key_permissions_in_login_screen =
      extensions::FeatureProvider::GetBehaviorFeature(
          extensions::behavior_feature::kKeyPermissionsInLoginScreen);

  return key_permissions_in_login_screen->IsAvailableToExtension(extension)
      .is_available();
}

KeystoreType KeystoreTypeFromTokenId(platform_keys::TokenId token_id) {
  switch (token_id) {
    case platform_keys::TokenId::kUser:
      return KeystoreType::kUser;
    case platform_keys::TokenId::kSystem:
      return KeystoreType::kDevice;
  }
}

KeystoreSigningScheme GetKeystoreSigningScheme(
    platform_keys::KeyType key_type,
    platform_keys::HashAlgorithm hash_algorithm) {
  switch (key_type) {
    case platform_keys::KeyType::kRsassaPkcs1V15: {
      switch (hash_algorithm) {
        case platform_keys::HASH_ALGORITHM_NONE:
          return KeystoreSigningScheme::kRsassaPkcs1V15None;
        case platform_keys::HASH_ALGORITHM_SHA1:
          return KeystoreSigningScheme::kRsassaPkcs1V15Sha1;
        case platform_keys::HASH_ALGORITHM_SHA256:
          return KeystoreSigningScheme::kRsassaPkcs1V15Sha256;
        case platform_keys::HASH_ALGORITHM_SHA384:
          return KeystoreSigningScheme::kRsassaPkcs1V15Sha384;
        case platform_keys::HASH_ALGORITHM_SHA512:
          return KeystoreSigningScheme::kRsassaPkcs1V15Sha512;
      }
    }
    case platform_keys::KeyType::kEcdsa: {
      switch (hash_algorithm) {
        case platform_keys::HASH_ALGORITHM_NONE:
          // This combination is not supported.
          return KeystoreSigningScheme::kUnknown;
        case platform_keys::HASH_ALGORITHM_SHA1:
          return KeystoreSigningScheme::kEcdsaSha1;
        case platform_keys::HASH_ALGORITHM_SHA256:
          return KeystoreSigningScheme::kEcdsaSha256;
        case platform_keys::HASH_ALGORITHM_SHA384:
          return KeystoreSigningScheme::kEcdsaSha384;
        case platform_keys::HASH_ALGORITHM_SHA512:
          return KeystoreSigningScheme::kEcdsaSha512;
      }
    }
    case platform_keys::KeyType::kRsaOaep:
      // Keys with type RSA-OAEP cannot be used for signing.
      return KeystoreSigningScheme::kUnknown;
  }
}

// Returns whether a key with algorithm `key_type` can be used for signing.
bool IsKeyUsedForSigning(platform_keys::KeyType key_type) {
  switch (key_type) {
    case platform_keys::KeyType::kRsassaPkcs1V15:
    case platform_keys::KeyType::kEcdsa:
      return true;
    case platform_keys::KeyType::kRsaOaep:
      return false;
  }
}

// Returns appropriate KeystoreService for |browser_context|, which can be:
// * an instance owned by CrosapiManager (that is created before profiles and
// should outlive ExtensionPlatformKeysService)
// * or an appropriate keyed service that will always exist
// during ExtensionPlatformKeysService lifetime (because of KeyedService
// dependencies).
crosapi::mojom::KeystoreService* GetKeystoreService(
    content::BrowserContext* browser_context) {
  return crosapi::KeystoreServiceFactoryAsh::GetForBrowserContext(
      browser_context);
}

}  // namespace

class ExtensionPlatformKeysService::Task {
 public:
  Task() = default;
  Task(const Task&) = delete;
  auto operator=(const Task&) = delete;
  virtual ~Task() = default;
  virtual void Start() = 0;
  virtual bool IsDone() = 0;
};

class ExtensionPlatformKeysService::GenerateKeyTask : public Task {
 public:
  enum class Step {
    GENERATE_KEY,
    GET_EXTENSION_PERMISSIONS,
    UPDATE_PERMISSIONS_AND_CALLBACK,
    DONE,
  };

  GenerateKeyTask(platform_keys::TokenId token_id,
                  platform_keys::KeyType key_type,
                  extensions::ExtensionId extension_id,
                  GenerateKeyCallback callback,
                  ExtensionPlatformKeysService* service)
      : token_id_(token_id),
        key_type_(key_type),
        extension_id_(std::move(extension_id)),
        callback_(std::move(callback)),
        service_(service) {}

  GenerateKeyTask(const GenerateKeyTask&) = delete;
  auto operator=(const GenerateKeyTask&) = delete;

  ~GenerateKeyTask() override = default;

  void Start() override {
    CHECK(next_step_ == Step::GENERATE_KEY);
    DoStep();
  }

  bool IsDone() override { return next_step_ == Step::DONE; }

 protected:
  virtual void GenerateKey(KeystoreService::GenerateKeyCallback callback) = 0;

  platform_keys::TokenId token_id_;
  platform_keys::KeyType key_type_;
  std::vector<uint8_t> public_key_spki_der_;
  const extensions::ExtensionId extension_id_;
  GenerateKeyCallback callback_;
  std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
      extension_key_permissions_service_;
  const raw_ptr<ExtensionPlatformKeysService> service_;

 private:
  void DoStep() {
    switch (next_step_) {
      case Step::GENERATE_KEY:
        next_step_ = Step::GET_EXTENSION_PERMISSIONS;
        GenerateKey(base::BindOnce(&GenerateKeyTask::OnKeyGenerated,
                                   weak_factory_.GetWeakPtr()));
        return;
      case Step::GET_EXTENSION_PERMISSIONS:
        next_step_ = Step::UPDATE_PERMISSIONS_AND_CALLBACK;
        GetExtensionPermissions();
        return;
      case Step::UPDATE_PERMISSIONS_AND_CALLBACK:
        next_step_ = Step::DONE;
        UpdatePermissionsAndCallBack();
        return;
      case Step::DONE:
        service_->TaskFinished(this);
        // |this| might be invalid now.
        return;
    }
  }

  // Stores the generated key or in case of an error calls |callback_| with the
  // error status.
  void OnKeyGenerated(KeystoreBinaryResultPtr result) {
    using Tag = KeystoreBinaryResult::Tag;
    switch (result->which()) {
      case Tag::kError:
        next_step_ = Step::DONE;
        std::move(callback_).Run(/*public_key_spki_der=*/std::vector<uint8_t>(),
                                 result->get_error());
        break;
      case Tag::kBlob:
        public_key_spki_der_ = std::move(result->get_blob());
        break;
    }
    DoStep();
  }

  // Gets the permissions for the extension with id |extension_id|.
  void GetExtensionPermissions() {
    platform_keys::ExtensionKeyPermissionsServiceFactory::
        GetForBrowserContextAndExtension(
            base::BindOnce(&GenerateKeyTask::OnPermissionsGot,
                           weak_factory_.GetWeakPtr()),
            service_->browser_context_, extension_id_);
  }

  void OnPermissionsGot(
      std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
          extension_key_permissions_service) {
    extension_key_permissions_service_ =
        std::move(extension_key_permissions_service);
    DoStep();
  }

  void UpdatePermissionsAndCallBack() {
    // Only set the one-time signing permissions for keys used for signing.
    if (IsKeyUsedForSigning(key_type_)) {
      extension_key_permissions_service_
          ->RegisterOneTimeSigningPermissionForKey(public_key_spki_der_);
    }

    extension_key_permissions_service_->RegisterKeyForCorporateUsage(
        public_key_spki_der_,
        base::BindOnce(&GenerateKeyTask::OnKeyRegisteredForCorporateUsage,
                       weak_factory_.GetWeakPtr()));
  }

  void OnKeyRegisteredForCorporateUsage(bool is_error,
                                        crosapi::mojom::KeystoreError error) {
    if (!is_error) {
      std::move(callback_).Run(std::move(public_key_spki_der_),
                               /*error=*/std::nullopt);
      DoStep();
      return;
    }

    LOG(ERROR) << "Corporate key registration failed: "
               << platform_keys::KeystoreErrorToString(error);

    service_->keystore_service_->RemoveKey(
        KeystoreTypeFromTokenId(token_id_), std::move(public_key_spki_der_),
        base::BindOnce(&GenerateKeyTask::RemoveKeyCallback,
                       weak_factory_.GetWeakPtr(),
                       /*corporate_key_registration_error_status=*/error));
  }

  void RemoveKeyCallback(
      crosapi::mojom::KeystoreError corporate_key_registration_error,
      bool is_remove_error,
      KeystoreError remove_error) {
    if (is_remove_error) {
      LOG(ERROR)
          << "Failed to remove a dangling key with error: "
          << platform_keys::KeystoreErrorToString(remove_error)
          << ", after failing to register key for corporate usage with error: "
          << platform_keys::KeystoreErrorToString(
                 corporate_key_registration_error);
    }

    next_step_ = Step::DONE;
    std::move(callback_).Run(/*public_key_spki_der=*/std::vector<uint8_t>(),
                             corporate_key_registration_error);
    DoStep();
  }

  Step next_step_ = Step::GENERATE_KEY;

  base::WeakPtrFactory<GenerateKeyTask> weak_factory_{this};
};

class ExtensionPlatformKeysService::GenerateRSAKeyTask
    : public GenerateKeyTask {
 public:
  // This key task generates an RSA key with the parameters |token_id| and
  // |modulus_length| and registers it for the extension with id |extension_id|.
  // The generated key will be passed to |callback|.
  GenerateRSAKeyTask(platform_keys::TokenId token_id,
                     platform_keys::KeyType key_type,
                     unsigned int modulus_length,
                     bool sw_backed,
                     const std::string& extension_id,
                     GenerateKeyCallback callback,
                     ExtensionPlatformKeysService* service)
      : GenerateKeyTask(token_id,
                        key_type,
                        extension_id,
                        std::move(callback),
                        service),
        modulus_length_(modulus_length),
        sw_backed_(sw_backed) {}

  ~GenerateRSAKeyTask() override = default;

 private:
  // Generates the RSA key.
  void GenerateKey(KeystoreService::GenerateKeyCallback callback) override {
    CHECK(key_type_ == platform_keys::KeyType::kRsassaPkcs1V15 ||
          key_type_ == platform_keys::KeyType::kRsaOaep);

    KeystoreAlgorithmPtr algorithm_ptr =
        key_type_ == platform_keys::KeyType::kRsassaPkcs1V15
            ? MakeRsassaPkcs1v15KeystoreAlgorithm(modulus_length_, sw_backed_)
            : MakeRsaOaepKeystoreAlgorithm(modulus_length_, sw_backed_);
    service_->keystore_service_->GenerateKey(KeystoreTypeFromTokenId(token_id_),
                                             std::move(algorithm_ptr),
                                             std::move(callback));
  }

  const unsigned int modulus_length_;
  const bool sw_backed_;
};

class ExtensionPlatformKeysService::GenerateECKeyTask : public GenerateKeyTask {
 public:
  // This Task generates an EC key with the parameters |token_id| and
  // |named_curve| and registers it for the extension with id |extension_id|.
  // The generated key will be passed to |callback|.
  GenerateECKeyTask(platform_keys::TokenId token_id,
                    platform_keys::KeyType key_type,
                    std::string named_curve,
                    std::string extension_id,
                    GenerateKeyCallback callback,
                    ExtensionPlatformKeysService* service)
      : GenerateKeyTask(token_id,
                        key_type,
                        std::move(extension_id),
                        std::move(callback),
                        service),
        named_curve_(std::move(named_curve)) {}

  ~GenerateECKeyTask() override = default;

 private:
  // Generates the EC key.
  void GenerateKey(KeystoreService::GenerateKeyCallback callback) override {
    CHECK(key_type_ == platform_keys::KeyType::kEcdsa);

    service_->keystore_service_->GenerateKey(
        KeystoreTypeFromTokenId(token_id_),
        MakeEcdsaKeystoreAlgorithm(named_curve_), std::move(callback));
  }

  const std::string named_curve_;
};

class ExtensionPlatformKeysService::SignTask : public Task {
 public:
  enum class Step {
    GET_EXTENSION_PERMISSIONS,
    CHECK_SIGN_PERMISSIONS,
    UPDATE_SIGN_PERMISSIONS,
    SIGN,
    DONE,
  };

  // This Task will check the permissions of the extension with |extension_id|
  // for the key of type |key_type| identified by |public_key_spki_der|. If the
  // permission check was positive, signs |data| with the key and passes the
  // signature to |callback|. If the extension is not allowed to use the key
  // multiple times, also updates the permission to prevent any future signing
  // operation of that extension using that same key. If an error occurs, an
  // error status is passed to |callback|.
  SignTask(std::optional<platform_keys::TokenId> token_id,
           std::vector<uint8_t> data,
           std::vector<uint8_t> public_key_spki_der,
           platform_keys::KeyType key_type,
           platform_keys::HashAlgorithm hash_algorithm,
           std::string extension_id,
           SignCallback callback,
           ExtensionPlatformKeysService* service)
      : token_id_(token_id),
        data_(std::move(data)),
        public_key_spki_der_(std::move(public_key_spki_der)),
        extension_id_(std::move(extension_id)),
        callback_(std::move(callback)),
        service_(service) {
    signing_scheme_ = GetKeystoreSigningScheme(key_type, hash_algorithm);
    DCHECK(signing_scheme_ != KeystoreSigningScheme::kUnknown);
  }

  SignTask(const SignTask&) = delete;
  auto operator=(const SignTask&) = delete;

  ~SignTask() override = default;

  void Start() override {
    CHECK(next_step_ == Step::GET_EXTENSION_PERMISSIONS);
    DoStep();
  }

  bool IsDone() override { return next_step_ == Step::DONE; }

 private:
  void DoStep() {
    switch (next_step_) {
      case Step::GET_EXTENSION_PERMISSIONS:
        next_step_ = Step::CHECK_SIGN_PERMISSIONS;
        GetExtensionPermissions();
        return;
      case Step::CHECK_SIGN_PERMISSIONS:
        next_step_ = Step::UPDATE_SIGN_PERMISSIONS;
        CheckSignPermissions();
        return;
      case Step::UPDATE_SIGN_PERMISSIONS:
        next_step_ = Step::SIGN;
        UpdateSignPermissions();
        return;
      case Step::SIGN:
        next_step_ = Step::DONE;
        Sign();
        return;
      case Step::DONE:
        service_->TaskFinished(this);
        // |this| might be invalid now.
        return;
    }
  }

  void GetExtensionPermissions() {
    platform_keys::ExtensionKeyPermissionsServiceFactory::
        GetForBrowserContextAndExtension(
            base::BindOnce(&SignTask::OnPermissionsGot,
                           weak_factory_.GetWeakPtr()),
            service_->browser_context_, extension_id_);
  }

  void OnPermissionsGot(
      std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
          extension_key_permissions_service) {
    extension_key_permissions_service_ =
        std::move(extension_key_permissions_service);
    DoStep();
  }

  void CheckSignPermissions() {
    const extensions::Extension* extension =
        extensions::ExtensionRegistry::Get(service_->browser_context_)
            ->enabled_extensions()
            .GetByID(extension_id_);
    if (service_->IsUsingSigninProfile() && IsExtensionAllowlisted(extension)) {
      DoStep();
      return;
    }

    extension_key_permissions_service_->CanUseKey(
        public_key_spki_der_, /*is_sign_operation=*/true,
        base::BindOnce(&SignTask::OnCanUseKeyForSigningKnown,
                       weak_factory_.GetWeakPtr()));
  }

  void OnCanUseKeyForSigningKnown(bool allowed) {
    if (!allowed) {
      std::move(callback_).Run(/*signature=*/std::vector<uint8_t>(),
                               KeystoreError::kKeyNotAllowedForOperation);
      next_step_ = Step::DONE;
      DoStep();
      return;
    }

    DoStep();
  }

  // Updates the signing permissions for |public_key_spki_der_|.
  void UpdateSignPermissions() {
    extension_key_permissions_service_->SetKeyUsedForSigning(
        public_key_spki_der_,
        base::BindOnce(&SignTask::OnSetKeyUsedForSigningDone,
                       weak_factory_.GetWeakPtr()));
  }

  void OnSetKeyUsedForSigningDone(bool is_error,
                                  crosapi::mojom::KeystoreError error) {
    if (is_error) {
      LOG(ERROR) << "Marking a key used for signing failed: "
                 << platform_keys::KeystoreErrorToString(error);
      next_step_ = Step::DONE;
      std::move(callback_).Run(/*signature=*/std::vector<uint8_t>(), error);
      DoStep();
      return;
    }

    DoStep();
  }

  // Starts the actual signing operation and afterwards passes the signature (or
  // error) to |callback_|.
  void Sign() {
    // TODO(crbug.com/40489779): This can be simplified when mojo supports
    // optional enums.
    bool is_keystore_provided = false;
    KeystoreType keystore = KeystoreType::kUser;
    if (token_id_.has_value()) {
      is_keystore_provided = true;
      keystore = KeystoreTypeFromTokenId(token_id_.value());
    }

    service_->keystore_service_->Sign(
        is_keystore_provided, keystore, public_key_spki_der_, signing_scheme_,
        data_, base::BindOnce(&SignTask::DidSign, weak_factory_.GetWeakPtr()));
  }

  void DidSign(KeystoreBinaryResultPtr result) {
    switch (result->which()) {
      case KeystoreBinaryResult::Tag::kError:
        std::move(callback_).Run(/*signature=*/std::vector<uint8_t>(),
                                 result->get_error());
        break;
      case KeystoreBinaryResult::Tag::kBlob:
        std::move(callback_).Run(
            /*signature=*/std::move(result->get_blob()),
            /*error=*/std::nullopt);
        break;
    }
    DoStep();
  }

  Step next_step_ = Step::GET_EXTENSION_PERMISSIONS;

  std::optional<platform_keys::TokenId> token_id_;
  const std::vector<uint8_t> data_;
  const std::vector<uint8_t> public_key_spki_der_;

  KeystoreSigningScheme signing_scheme_;
  const extensions::ExtensionId extension_id_;
  SignCallback callback_;
  std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
      extension_key_permissions_service_;
  const raw_ptr<ExtensionPlatformKeysService> service_;
  base::WeakPtrFactory<SignTask> weak_factory_{this};
};

class ExtensionPlatformKeysService::SetKeyTagTask : public Task {
 public:
  enum class Step {
    GET_EXTENSION_PERMISSIONS,
    CHECK_PERMISSIONS,
    SET_KEY_TAG,
    DONE,
  };

  SetKeyTagTask(platform_keys::TokenId token_id,
                std::vector<uint8_t> key_tag,
                std::vector<uint8_t> public_key_spki_der,
                std::string extension_id,
                SetKeyTagCallback callback,
                ExtensionPlatformKeysService* service)
      : token_id_(token_id),
        key_tag_(std::move(key_tag)),
        public_key_spki_der_(std::move(public_key_spki_der)),
        extension_id_(std::move(extension_id)),
        callback_(std::move(callback)),
        service_(service) {}

  SetKeyTagTask(const SetKeyTagTask&) = delete;
  auto operator=(const SetKeyTagTask&) = delete;

  ~SetKeyTagTask() override = default;

  void Start() override {
    CHECK(next_step_ == Step::GET_EXTENSION_PERMISSIONS);
    DoStep();
  }

  bool IsDone() override { return next_step_ == Step::DONE; }

 private:
  void DoStep() {
    switch (next_step_) {
      case Step::GET_EXTENSION_PERMISSIONS:
        next_step_ = Step::CHECK_PERMISSIONS;
        GetExtensionPermissions();
        return;
      case Step::CHECK_PERMISSIONS:
        next_step_ = Step::SET_KEY_TAG;
        CheckPermissions();
        return;
      case Step::SET_KEY_TAG:
        next_step_ = Step::DONE;
        SetKeyTag();
        return;
      case Step::DONE:
        service_->TaskFinished(this);
        // |this| might be invalid now.
        return;
    }
  }

  void GetExtensionPermissions() {
    platform_keys::ExtensionKeyPermissionsServiceFactory::
        GetForBrowserContextAndExtension(
            base::BindOnce(&SetKeyTagTask::GotPermissions,
                           weak_factory_.GetWeakPtr()),
            service_->browser_context_, extension_id_);
  }

  void GotPermissions(
      std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
          extension_key_permissions_service) {
    extension_key_permissions_service_ =
        std::move(extension_key_permissions_service);
    DoStep();
  }

  void CheckPermissions() {
    extension_key_permissions_service_->CanUseKey(
        public_key_spki_der_, /*is_sign_operation=*/false,
        base::BindOnce(&SetKeyTagTask::OnCanUseKeyKnown,
                       weak_factory_.GetWeakPtr()));
  }

  void OnCanUseKeyKnown(bool allowed) {
    if (!allowed) {
      std::move(callback_).Run(KeystoreError::kKeyNotAllowedForOperation);
      next_step_ = Step::DONE;
      DoStep();
      return;
    }

    DoStep();
  }

  void SetKeyTag() {
    service_->keystore_service_->SetAttributeForKey(
        KeystoreTypeFromTokenId(token_id_), public_key_spki_der_,
        KeystoreKeyAttributeType::kPlatformKeysTag, key_tag_,
        base::BindOnce(&SetKeyTagTask::DidSetKeyTag,
                       weak_factory_.GetWeakPtr()));
  }

  void DidSetKeyTag(bool is_error, KeystoreError error) {
    if (is_error) {
      LOG(ERROR) << "Failed to set the tag to the key with an error: "
                 << platform_keys::KeystoreErrorToString(error);
      std::move(callback_).Run(error);
    } else {
      std::move(callback_).Run(/*error=*/std::nullopt);
    }

    DoStep();
  }

  Step next_step_ = Step::GET_EXTENSION_PERMISSIONS;

  platform_keys::TokenId token_id_;
  const std::vector<uint8_t> key_tag_;
  const std::vector<uint8_t> public_key_spki_der_;

  const extensions::ExtensionId extension_id_;
  SetKeyTagCallback callback_;
  std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
      extension_key_permissions_service_;
  const raw_ptr<ExtensionPlatformKeysService> service_;
  base::WeakPtrFactory<SetKeyTagTask> weak_factory_{this};
};

class ExtensionPlatformKeysService::SelectTask : public Task {
 public:
  enum class Step {
    GET_EXTENSION_PERMISSIONS,
    GET_MATCHING_CERTS,
    CHECK_KEY_PERMISSIONS,
    INTERSECT_WITH_INPUT_CERTS,
    SELECT_CERTS,
    UPDATE_PERMISSION,
    PASS_RESULTING_CERTS,
    DONE,
  };

  // This task determines all known client certs matching |request| and that are
  // elements of |input_client_certificates|, if given. If |interactive| is
  // true, calls |service->select_delegate_->Select()| to select a cert from all
  // matches. The extension with |extension_id| will be granted unlimited sign
  // permission for the selected cert. Finally, either the selection or, if
  // |interactive| is false, matching certs that the extension has permission
  // for are passed to |callback|.
  SelectTask(const platform_keys::ClientCertificateRequest& request,
             std::unique_ptr<net::CertificateList> input_client_certificates,
             bool interactive,
             std::string extension_id,
             SelectCertificatesCallback callback,
             content::WebContents* web_contents,
             ExtensionPlatformKeysService* service)
      : request_(request),
        input_client_certificates_(std::move(input_client_certificates)),
        interactive_(interactive),
        extension_id_(std::move(extension_id)),
        callback_(std::move(callback)),
        web_contents_(web_contents),
        service_(service) {}

  SelectTask(const SelectTask&) = delete;
  auto operator=(const SelectTask) = delete;

  ~SelectTask() override = default;

  void Start() override {
    CHECK(next_step_ == Step::GET_EXTENSION_PERMISSIONS);
    DoStep();
  }

  bool IsDone() override { return next_step_ == Step::DONE; }

 private:
  void DoStep() {
    switch (next_step_) {
      case Step::GET_EXTENSION_PERMISSIONS:
        next_step_ = Step::GET_MATCHING_CERTS;
        GetExtensionPermissions();
        return;
      case Step::GET_MATCHING_CERTS:
        next_step_ = Step::CHECK_KEY_PERMISSIONS;
        GetMatchingCerts();
        return;
      case Step::CHECK_KEY_PERMISSIONS:
        // Don't advance to the next step yet - CheckKeyPermissions is repeated
        // for all matching certs. The next step will be selected in
        // CheckKeyPermissions.
        CheckKeyPermissions(Step::INTERSECT_WITH_INPUT_CERTS /* next_step */);
        return;
      case Step::INTERSECT_WITH_INPUT_CERTS:
        if (interactive_) {
          next_step_ = Step::SELECT_CERTS;
        } else {  // Skip SelectCerts and UpdatePermission if not interactive.
          next_step_ = Step::PASS_RESULTING_CERTS;
        }
        IntersectWithInputCerts();
        return;
      case Step::SELECT_CERTS:
        next_step_ = Step::UPDATE_PERMISSION;
        SelectCerts();
        return;
      case Step::UPDATE_PERMISSION:
        next_step_ = Step::PASS_RESULTING_CERTS;
        UpdatePermission();
        return;
      case Step::PASS_RESULTING_CERTS:
        next_step_ = Step::DONE;
        PassResultingCerts();
        return;
      case Step::DONE:
        service_->TaskFinished(this);
        // |this| might be invalid now.
        return;
    }
  }

  void GetExtensionPermissions() {
    platform_keys::ExtensionKeyPermissionsServiceFactory::
        GetForBrowserContextAndExtension(
            base::BindOnce(&SelectTask::OnPermissionsGot,
                           weak_factory_.GetWeakPtr()),
            service_->browser_context_, extension_id_);
  }

  void OnPermissionsGot(
      std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
          extension_key_permissions_service) {
    extension_key_permissions_service_ =
        std::move(extension_key_permissions_service);
    DoStep();
  }

  // Retrieves all certificates matching |request_|. Will call back to
  // |GotMatchingCerts()|.
  void GetMatchingCerts() {
    service_->keystore_service_->SelectClientCertificates(
        request_.certificate_authorities,
        base::BindOnce(&SelectTask::GotMatchingCerts,
                       weak_factory_.GetWeakPtr()));
  }

  // If the certificate request could be processed successfully, |matches| will
  // contain the list of matching certificates (maybe empty). If an error
  // occurred, |matches| will be null. Note that the order of |matches|, based
  // on the expiration/issuance date, is relevant and must be preserved in any
  // processing of the list.
  void GotMatchingCerts(KeystoreSelectClientCertificatesResultPtr result) {
    if (result->which() ==
        KeystoreSelectClientCertificatesResult::Tag::kError) {
      next_step_ = Step::DONE;
      std::move(callback_).Run(nullptr /* no certificates */,
                               result->get_error());
      DoStep();
      return;
    }

    for (const std::vector<uint8_t>& binary_cert : result->get_certificates()) {
      scoped_refptr<net::X509Certificate> certificate =
          net::X509Certificate::CreateFromBytes(binary_cert);

      // Filter the retrieved certificates returning only those whose type
      // is equal to one of the entries in the type field of the certificate
      // request.
      // If the type field does not contain any entries, certificates of all
      // types shall be returned.
      if (!request_.certificate_key_types.empty()) {
        net::X509Certificate::PublicKeyType actual_key_type =
            net::X509Certificate::kPublicKeyTypeUnknown;
        size_t unused_key_size = 0;
        net::X509Certificate::GetPublicKeyInfo(
            certificate->cert_buffer(), &unused_key_size, &actual_key_type);
        const std::vector<net::X509Certificate::PublicKeyType>& accepted_types =
            request_.certificate_key_types;
        if (!base::Contains(accepted_types, actual_key_type)) {
          continue;
        }
      }

      matches_pending_permissions_check_.push_back(std::move(certificate));
    }
    DoStep();
  }

  // This is called once for each certificate in
  // |matches_pending_permissions_check_|. Each invocation processes the first
  // element and removes it from the deque. Each processed certificate is added
  // to |matches_| if it is selectable according to
  // ExtensionKeyPermissionsService. When all certificates have been processed,
  // advances the SelectTask state machine to |next_step|.
  void CheckKeyPermissions(Step next_step) {
    if (matches_pending_permissions_check_.empty()) {
      next_step_ = next_step;
      DoStep();
      return;
    }

    scoped_refptr<net::X509Certificate> certificate =
        std::move(matches_pending_permissions_check_.front());
    matches_pending_permissions_check_.pop_front();
    std::vector<uint8_t> public_key_spki_der =
        platform_keys::GetSubjectPublicKeyInfoBlob(certificate);

    extension_key_permissions_service_->CanUseKey(
        public_key_spki_der, /*is_sign_operation=*/true,
        base::BindOnce(&SelectTask::OnKeySigningPermissionKnown,
                       weak_factory_.GetWeakPtr(), public_key_spki_der,
                       certificate));
  }

  void OnKeySigningPermissionKnown(
      std::vector<uint8_t> public_key_spki_der,
      const scoped_refptr<net::X509Certificate>& certificate,
      bool allowed) {
    if (allowed) {
      matches_.push_back(certificate);
      DoStep();
    } else if (interactive_) {
      service_->keystore_service_->CanUserGrantPermissionForKey(
          std::move(public_key_spki_der),
          base::BindOnce(&SelectTask::OnAbilityToGrantPermissionKnown,
                         weak_factory_.GetWeakPtr(), std::move(certificate)));
    } else {
      DoStep();
    }
  }

  void OnAbilityToGrantPermissionKnown(
      const scoped_refptr<net::X509Certificate>& certificate,
      bool allowed) {
    if (allowed) {
      matches_.push_back(certificate);
    }
    DoStep();
  }

  // If |input_client_certificates_| is given, removes from |matches_| all
  // certificates that are not elements of |input_client_certificates_|.
  void IntersectWithInputCerts() {
    if (!input_client_certificates_) {
      DoStep();
      return;
    }
    platform_keys::IntersectCertificates(
        matches_, *input_client_certificates_,
        base::BindOnce(&SelectTask::GotIntersection,
                       weak_factory_.GetWeakPtr()));
  }

  void GotIntersection(std::unique_ptr<net::CertificateList> intersection) {
    matches_.swap(*intersection);
    DoStep();
  }

  // Calls |service_->select_delegate_->Select()| to select a cert from
  // |matches_|, which will be stored in |selected_cert_|.
  // Will call back to |GotSelection()|.
  void SelectCerts() {
    CHECK(interactive_);
    if (matches_.empty()) {
      // Don't show a select dialog if no certificate is matching.
      DoStep();
      return;
    }
    service_->select_delegate_->Select(
        extension_id_, matches_,
        base::BindOnce(&SelectTask::GotSelection, weak_factory_.GetWeakPtr()),
        web_contents_, service_->browser_context_);
  }

  // Will be called by |SelectCerts()| with the selected cert or null if no cert
  // was selected.
  void GotSelection(scoped_refptr<net::X509Certificate> selected_cert) {
    selected_cert_ = selected_cert;
    DoStep();
  }

  // Updates the extension's state store about unlimited sign permission for the
  // selected cert. Does nothing if no cert was selected.
  void UpdatePermission() {
    CHECK(interactive_);
    if (!selected_cert_) {
      DoStep();
      return;
    }
    extension_key_permissions_service_->SetUserGrantedSigningPermission(
        platform_keys::GetSubjectPublicKeyInfoBlob(selected_cert_),
        base::BindOnce(&SelectTask::OnPermissionsUpdated,
                       weak_factory_.GetWeakPtr()));
  }

  void OnPermissionsUpdated(bool is_error,
                            crosapi::mojom::KeystoreError error) {
    if (is_error) {
      LOG(WARNING) << "Error while updating permissions: "
                   << platform_keys::KeystoreErrorToString(error);
    }

    DoStep();
  }

  // Passes the filtered certs to |callback_|.
  void PassResultingCerts() {
    std::unique_ptr<net::CertificateList> selection(new net::CertificateList);
    if (interactive_) {
      if (selected_cert_) {
        selection->push_back(selected_cert_);
      }
    } else {
      selection->assign(matches_.begin(), matches_.end());
    }

    std::move(callback_).Run(std::move(selection), /*error=*/std::nullopt);
    DoStep();
  }

  Step next_step_ = Step::GET_EXTENSION_PERMISSIONS;

  std::deque<scoped_refptr<net::X509Certificate>>
      matches_pending_permissions_check_;
  net::CertificateList matches_;
  scoped_refptr<net::X509Certificate> selected_cert_;
  platform_keys::ClientCertificateRequest request_;
  std::unique_ptr<net::CertificateList> input_client_certificates_;
  const bool interactive_;
  const extensions::ExtensionId extension_id_;
  SelectCertificatesCallback callback_;
  const raw_ptr<content::WebContents> web_contents_;
  std::unique_ptr<platform_keys::ExtensionKeyPermissionsService>
      extension_key_permissions_service_;
  const raw_ptr<ExtensionPlatformKeysService> service_;
  base::WeakPtrFactory<SelectTask> weak_factory_{this};
};

ExtensionPlatformKeysService::SelectDelegate::SelectDelegate() = default;

ExtensionPlatformKeysService::SelectDelegate::~SelectDelegate() = default;

ExtensionPlatformKeysService::ExtensionPlatformKeysService(
    content::BrowserContext* browser_context)
    : browser_context_(browser_context),
      keystore_service_(GetKeystoreService(browser_context_)) {
  DCHECK(browser_context);
}

ExtensionPlatformKeysService::~ExtensionPlatformKeysService() = default;

void ExtensionPlatformKeysService::SetSelectDelegate(
    std::unique_ptr<SelectDelegate> delegate) {
  select_delegate_ = std::move(delegate);
}

void ExtensionPlatformKeysService::GenerateRSAKey(
    platform_keys::TokenId token_id,
    platform_keys::KeyType key_type,
    unsigned int modulus_length,
    bool sw_backed,
    std::string extension_id,
    GenerateKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!keystore_service_) [[unlikely]] {
    std::move(callback).Run(/*public_key_spki_der=*/std::vector<uint8_t>(),
                            crosapi::mojom::KeystoreError::kMojoUnavailable);
    return;
  }

  if (key_type == platform_keys::KeyType::kRsaOaep &&
      !chromeos::features::IsPlatformKeysChangesWave1Enabled()) {
    std::move(callback).Run(
        /*public_key_spki_der=*/std::vector<uint8_t>(),
        crosapi::mojom::KeystoreError::kAlgorithmNotSupported);
    return;
  }

  StartOrQueueTask(std::make_unique<GenerateRSAKeyTask>(
      token_id, key_type, modulus_length, sw_backed, std::move(extension_id),
      std::move(callback), this));
}

void ExtensionPlatformKeysService::GenerateECKey(
    platform_keys::TokenId token_id,
    platform_keys::KeyType key_type,
    std::string named_curve,
    std::string extension_id,
    GenerateKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!keystore_service_) [[unlikely]] {
    std::move(callback).Run(/*public_key_spki_der=*/std::vector<uint8_t>(),
                            crosapi::mojom::KeystoreError::kMojoUnavailable);
    return;
  }

  StartOrQueueTask(std::make_unique<GenerateECKeyTask>(
      token_id, key_type, std::move(named_curve), std::move(extension_id),
      std::move(callback), this));
}

bool ExtensionPlatformKeysService::IsUsingSigninProfile() {
  return ash::ProfileHelper::IsSigninProfile(
      Profile::FromBrowserContext(browser_context_));
}

void ExtensionPlatformKeysService::SignDigest(
    std::optional<platform_keys::TokenId> token_id,
    std::vector<uint8_t> data,
    std::vector<uint8_t> public_key_spki_der,
    platform_keys::KeyType key_type,
    platform_keys::HashAlgorithm hash_algorithm,
    std::string extension_id,
    SignCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!keystore_service_) [[unlikely]] {
    std::move(callback).Run(/*signature=*/std::vector<uint8_t>(),
                            crosapi::mojom::KeystoreError::kMojoUnavailable);
    return;
  }

  StartOrQueueTask(std::make_unique<SignTask>(
      token_id, std::move(data), std::move(public_key_spki_der), key_type,
      hash_algorithm, std::move(extension_id), std::move(callback), this));
}

void ExtensionPlatformKeysService::SignRSAPKCS1Raw(
    std::optional<platform_keys::TokenId> token_id,
    std::vector<uint8_t> data,
    std::vector<uint8_t> public_key_spki_der,
    std::string extension_id,
    SignCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!keystore_service_) [[unlikely]] {
    std::move(callback).Run(/*signature=*/std::vector<uint8_t>(),
                            crosapi::mojom::KeystoreError::kMojoUnavailable);
    return;
  }

  StartOrQueueTask(std::make_unique<SignTask>(
      token_id, std::move(data), std::move(public_key_spki_der),
      /*key_type=*/platform_keys::KeyType::kRsassaPkcs1V15,
      platform_keys::HASH_ALGORITHM_NONE, std::move(extension_id),
      std::move(callback), this));
}

void ExtensionPlatformKeysService::SelectClientCertificates(
    const platform_keys::ClientCertificateRequest& request,
    std::unique_ptr<net::CertificateList> client_certificates,
    bool interactive,
    std::string extension_id,
    SelectCertificatesCallback callback,
    content::WebContents* web_contents) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!keystore_service_) [[unlikely]] {
    std::move(callback).Run(/*matches=*/nullptr,
                            crosapi::mojom::KeystoreError::kMojoUnavailable);
    return;
  }

  StartOrQueueTask(std::make_unique<SelectTask>(
      request, std::move(client_certificates), interactive,
      std::move(extension_id), std::move(callback), web_contents, this));
}

void ExtensionPlatformKeysService::SetKeyTag(
    platform_keys::TokenId token_id,
    std::vector<uint8_t> tag,
    std::vector<uint8_t> public_key_spki_der,
    std::string extension_id,
    SetKeyTagCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  if (!keystore_service_) [[unlikely]] {
    std::move(callback).Run(crosapi::mojom::KeystoreError::kMojoUnavailable);
    return;
  }

  StartOrQueueTask(std::make_unique<SetKeyTagTask>(
      token_id, std::move(tag), std::move(public_key_spki_der),
      std::move(extension_id), std::move(callback), this));
}

void ExtensionPlatformKeysService::StartOrQueueTask(
    std::unique_ptr<Task> task) {
  tasks_.push(std::move(task));
  if (tasks_.size() == 1) {
    tasks_.front()->Start();
  }
}

void ExtensionPlatformKeysService::TaskFinished(Task* task) {
  DCHECK(!tasks_.empty());
  DCHECK(task == tasks_.front().get());
  // Remove all finished tasks from the queue (should be at most one).
  while (!tasks_.empty() && tasks_.front()->IsDone()) {
    tasks_.pop();
  }

  // Now either the queue is empty or the next task is not finished yet and it
  // can be started.
  if (!tasks_.empty()) {
    tasks_.front()->Start();
  }
}

}  // namespace chromeos