File: platform_keys_service_nss.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 (2695 lines) | stat: -rw-r--r-- 100,375 bytes parent folder | download | duplicates (5)
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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include <cert.h>
#include <certdb.h>
#include <cryptohi.h>
#include <keyhi.h>
#include <pk11pub.h>
#include <pkcs11t.h>
#include <secder.h>
#include <secerr.h>
#include <stddef.h>
#include <stdint.h>

#include <memory>
#include <optional>
#include <string_view>
#include <utility>

#include "base/compiler_specific.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/ash/net/client_cert_store_ash.h"
#include "chrome/browser/ash/platform_keys/platform_keys_service.h"
#include "chrome/browser/chromeos/platform_keys/platform_keys.h"
#include "chromeos/ash/components/chaps_util/chaps_util.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "crypto/nss_key_util.h"
#include "crypto/openssl_util.h"
#include "crypto/scoped_nss_types.h"
#include "net/base/net_errors.h"
#include "net/cert/asn1_util.h"
#include "net/cert/cert_database.h"
#include "net/cert/nss_cert_database.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "net/cert/x509_util_nss.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h"
#include "third_party/cros_system_api/constants/pkcs11_custom_attributes.h"

namespace ash::platform_keys {

void RunCallBackIfCallableElseRunCleanUp(base::OnceCallback<void()> callback,
                                         base::OnceCallback<void()> cleanup) {
  if (!callback.IsCancelled()) {
    return std::move(callback).Run();
  }
  if (!cleanup.IsCancelled()) {
    return std::move(cleanup).Run();
  }
  // else: TODO(b/280048774): Handle RemoveKey case when PlatformService
  // is not here.
}

namespace {

using ServiceWeakPtr = ::base::WeakPtr<PlatformKeysServiceImpl>;
using ::chromeos::platform_keys::HashAlgorithm;
using ::chromeos::platform_keys::KeyAttributeType;
using ::chromeos::platform_keys::KeyType;
using ::chromeos::platform_keys::OperationType;
using ::chromeos::platform_keys::Status;
using ::chromeos::platform_keys::SymKeyType;
using ::chromeos::platform_keys::TokenId;
using ::content::BrowserContext;
using ::content::BrowserThread;

// The current maximal RSA modulus length that ChromeOS's TPM supports for key
// generation.
const unsigned int kMaxRSAModulusLengthBits = 2048;

// Default constants for symmetric keys.
const int kDefaultSymKeySize = 32;
const int kDefaultSymSignatureLength = 32;

// Returns a vector containing bytes from `value` or an empty vector if `value`
// is nullptr.
std::vector<uint8_t> ScopedSECItemToBytes(const crypto::ScopedSECItem& value) {
  return value ? std::vector<uint8_t>(value->data, value->data + value->len)
               : std::vector<uint8_t>();
}

// Base class to store state that is common to all NSS database operations and
// to provide convenience methods to call back.
// Keeps track of the originating task runner.
class NSSOperationState {
 public:
  explicit NSSOperationState(ServiceWeakPtr weak_ptr)
      : service_weak_ptr_(weak_ptr) {}

  NSSOperationState(const NSSOperationState&) = delete;
  NSSOperationState& operator=(const NSSOperationState&) = delete;

  virtual ~NSSOperationState() = default;

  // Called if an error occurred during the execution of the NSS operation
  // described by this object.
  virtual void OnError(const base::Location& from, Status status) = 0;

  static void RunCallback(base::OnceClosure callback, ServiceWeakPtr weak_ptr) {
    if (weak_ptr) {
      std::move(callback).Run();
    }
  }
  crypto::ScopedPK11Slot slot_;

  // Weak pointer to the PlatformKeysServiceImpl that created this state. Used
  // to check if the callback should be still called.
  ServiceWeakPtr service_weak_ptr_;
};

using GetCertDBCallback =
    base::OnceCallback<void(net::NSSCertDatabase* cert_db)>;

// Called on the UI thread with certificate database.
void DidGetCertDbOnUiThread(std::optional<TokenId> token_id,
                            GetCertDBCallback callback,
                            NSSOperationState* state,
                            net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!cert_db) {
    LOG(ERROR) << "Couldn't get NSSCertDatabase.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  if (token_id) {
    switch (token_id.value()) {
      case TokenId::kUser:
        state->slot_ = cert_db->GetPrivateSlot();
        break;
      case TokenId::kSystem:
        state->slot_ = cert_db->GetSystemSlot();
        break;
    }

    if (!state->slot_) {
      LOG(ERROR) << "Slot for token id '" << static_cast<int>(token_id.value())
                 << "' not available.";
      state->OnError(FROM_HERE, Status::kErrorInternal);
      return;
    }
  }

  // Sets |slot_| of |state| accordingly and calls |callback| on the IO thread
  // if the database was successfully retrieved.
  content::GetIOThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(std::move(callback), cert_db));
}

// Asynchronously fetches the NSSCertDatabase using |delegate| and, if
// |token_id| is not empty, the slot for |token_id|. Stores the slot in |state|
// and passes the database to |callback|. Will run |callback| on the IO thread.
void GetCertDatabase(std::optional<TokenId> token_id,
                     GetCertDBCallback callback,
                     PlatformKeysServiceImplDelegate* delegate,
                     NSSOperationState* state) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  delegate->GetNSSCertDatabase(base::BindOnce(&DidGetCertDbOnUiThread, token_id,
                                              std::move(callback), state));
}

class GenerateRSAKeyState : public NSSOperationState {
 public:
  GenerateRSAKeyState(ServiceWeakPtr weak_ptr,
                      unsigned int modulus_length_bits,
                      bool sw_backed,
                      TokenId token_id,
                      GenerateKeyCallback callback)
      : NSSOperationState(weak_ptr),
        modulus_length_bits_(modulus_length_bits),
        sw_backed_(sw_backed),
        token_id_(token_id),
        callback_(std::move(callback)) {}

  ~GenerateRSAKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*public_key_spki_der=*/std::vector<uint8_t>(), status);
  }

  void OnSuccess(const base::Location& from,
                 std::vector<uint8_t> public_key_spki_der) {
    CallBack(from, std::move(public_key_spki_der), Status::kSuccess);
  }

  const unsigned int modulus_length_bits_;
  const bool sw_backed_;
  TokenId token_id_;

 private:
  void CallBack(const base::Location& from,
                std::vector<uint8_t> public_key_spki_der,
                Status status) {
    auto success_callback =
        base::BindOnce(std::move(callback_), public_key_spki_der, status);
    // cleanup_callback will be called in case the main callback (callback_) is
    // canceled.
    auto cleanup_callback =
        base::BindOnce(&PlatformKeysServiceImpl::RemoveKey, service_weak_ptr_,
                       token_id_, public_key_spki_der, base::DoNothing());
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&RunCallBackIfCallableElseRunCleanUp,
                             std::move(success_callback),
                             std::move(cleanup_callback)));
  }

  // Must be called on origin thread, therefore use CallBack().
  GenerateKeyCallback callback_;
};

class GenerateECKeyState : public NSSOperationState {
 public:
  GenerateECKeyState(ServiceWeakPtr weak_ptr,
                     const std::string& named_curve,
                     TokenId token_id,
                     GenerateKeyCallback callback)
      : NSSOperationState(weak_ptr),
        named_curve_(std::move(named_curve)),
        token_id_(token_id),
        callback_(std::move(callback)) {}

  ~GenerateECKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*public_key_spki_der=*/std::vector<uint8_t>(), status);
  }

  void OnSuccess(const base::Location& from,
                 std::vector<uint8_t> public_key_spki_der) {
    CallBack(from, std::move(public_key_spki_der), Status::kSuccess);
  }

  const std::string named_curve_;
  TokenId token_id_;

 private:
  void CallBack(const base::Location& from,
                std::vector<uint8_t> public_key_spki_der,
                Status status) {
    auto success_callback =
        base::BindOnce(std::move(callback_), public_key_spki_der, status);
    // cleanup_callback will be called in case the main callback (callback_) is
    // canceled.
    auto cleanup_callback =
        base::BindOnce(&PlatformKeysServiceImpl::RemoveKey, service_weak_ptr_,
                       token_id_, public_key_spki_der, base::DoNothing());
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&RunCallBackIfCallableElseRunCleanUp,
                             std::move(success_callback),
                             std::move(cleanup_callback)));
  }

  // Must be called on origin thread, therefore use CallBack().
  GenerateKeyCallback callback_;
};

class GenerateSymKeyState : public NSSOperationState {
 public:
  GenerateSymKeyState(ServiceWeakPtr weak_ptr,
                      std::vector<uint8_t> key_id,
                      int key_size,
                      SymKeyType key_type,
                      GenerateKeyCallback callback)
      : NSSOperationState(weak_ptr),
        key_id_(std::move(key_id)),
        key_size_(key_size),
        key_type_(key_type),
        callback_(std::move(callback)) {}

  ~GenerateSymKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*key_id=*/std::vector<uint8_t>(), status);
  }

  void OnSuccess(const base::Location& from) {
    CallBack(from, key_id_, Status::kSuccess);
  }

  // This id is assigned to the newly created symmetric key.
  const std::vector<uint8_t> key_id_;

  const int key_size_;

  // Type of the key that determines which operations are allowed for it.
  const SymKeyType key_type_;

 private:
  void CallBack(const base::Location& from,
                std::vector<uint8_t> key_id,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(key_id), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  GenerateKeyCallback callback_;
};

class EncryptDecryptState : public NSSOperationState {
 public:
  EncryptDecryptState(ServiceWeakPtr weak_ptr,
                      std::vector<uint8_t> input_data,
                      std::vector<uint8_t> key_id,
                      std::string algorithm,
                      std::vector<uint8_t> init_vector,
                      const OperationType operation_type,
                      EncryptDecryptCallback callback)
      : NSSOperationState(weak_ptr),
        input_data_(std::move(input_data)),
        key_id_(std::move(key_id)),
        algorithm_(std::move(algorithm)),
        init_vector_(std::move(init_vector)),
        operation_type_(operation_type),
        callback_(std::move(callback)) {}

  ~EncryptDecryptState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*output_data=*/std::vector<uint8_t>(), status);
  }

  void OnSuccess(const base::Location& from, std::vector<uint8_t> output_data) {
    CallBack(from, std::move(output_data), Status::kSuccess);
  }

  // The data that will be encrypted/decrypted.
  const std::vector<uint8_t> input_data_;

  // Symmetric key id.
  const std::vector<uint8_t> key_id_;

  // Determines the algorithm that is used to encrypt/decrypt.
  const std::string algorithm_;

  // Initialization vector that is required for encryption/decryption.
  // Must have a length of 16 bytes.
  const std::vector<uint8_t> init_vector_;

  // Specifies the operation, i.e. encryption or decryption.
  const OperationType operation_type_;

 private:
  void CallBack(const base::Location& from,
                std::vector<uint8_t> output_data,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(output_data), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  EncryptDecryptCallback callback_;
};

class DeriveSymKeyState : public NSSOperationState {
 public:
  DeriveSymKeyState(ServiceWeakPtr weak_ptr,
                    std::vector<uint8_t> base_key_id,
                    std::vector<uint8_t> derived_key_id,
                    std::vector<uint8_t> label,
                    std::vector<uint8_t> context,
                    chromeos::platform_keys::SymKeyType derived_key_type,
                    DeriveKeyCallback callback,
                    bool kdf_counter_for_testing = false)
      : NSSOperationState(weak_ptr),
        base_key_id_(std::move(base_key_id)),
        derived_key_id_(std::move(derived_key_id)),
        label_(std::move(label)),
        context_(std::move(context)),
        derived_key_type_(derived_key_type),
        kdf_counter_for_testing_(kdf_counter_for_testing),
        callback_(std::move(callback)) {}

  ~DeriveSymKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*key_id=*/std::vector<uint8_t>(), status);
  }

  void OnSuccess(const base::Location& from) {
    CallBack(from, derived_key_id_, Status::kSuccess);
  }

  // Id of the base key.
  const std::vector<uint8_t> base_key_id_;
  // Id of the new derived key.
  const std::vector<uint8_t> derived_key_id_;

  // Context and label are input parameters required for the derivation
  // algorithm.
  const std::vector<uint8_t> label_;
  const std::vector<uint8_t> context_;

  // Type of the key that determines which operations are allowed for it.
  const SymKeyType derived_key_type_;

  // Testing requires an additional parameter in form of kdf_counter.
  const bool kdf_counter_for_testing_ = false;

 private:
  void CallBack(const base::Location& from,
                std::vector<uint8_t> key_id,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(key_id), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  DeriveKeyCallback callback_;
};

class SignState : public NSSOperationState {
 public:
  SignState(ServiceWeakPtr weak_ptr,
            std::vector<uint8_t> data,
            std::vector<uint8_t> public_key_spki_der,
            HashAlgorithm hash_algorithm,
            const KeyType key_type,
            SignCallback callback)
      : NSSOperationState(weak_ptr),
        data_(std::move(data)),
        public_key_spki_der_(std::move(public_key_spki_der)),
        hash_algorithm_(hash_algorithm),
        key_type_(key_type),
        callback_(std::move(callback)) {}

  ~SignState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*signature=*/std::vector<uint8_t>(), status);
  }

  void OnSuccess(const base::Location& from, std::vector<uint8_t> signature) {
    CallBack(from, std::move(signature), Status::kSuccess);
  }

  // The data that will be signed.
  const std::vector<uint8_t> data_;

  // Must be the DER encoding of a SubjectPublicKeyInfo.
  const std::vector<uint8_t> public_key_spki_der_;

  // Determines the hash algorithm that is used to digest |data| before signing.
  const HashAlgorithm hash_algorithm_;

  // Determines the type of the key that should be used for signing. This is
  // specified by the state creator.
  // Note: This can be different from the type of |public_key_spki_der|. In such
  // case, a runtime error should be thrown.
  const KeyType key_type_;

 private:
  void CallBack(const base::Location& from,
                std::vector<uint8_t> signature,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(signature), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  SignCallback callback_;
};

class SignSymState : public NSSOperationState {
 public:
  SignSymState(ServiceWeakPtr weak_ptr,
               std::vector<uint8_t> data,
               std::vector<uint8_t> key_id,
               SignCallback callback)
      : NSSOperationState(weak_ptr),
        data_(std::move(data)),
        key_id_(std::move(key_id)),
        callback_(std::move(callback)) {}

  ~SignSymState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*signature=*/std::vector<uint8_t>(), status);
  }

  void OnSuccess(const base::Location& from, std::vector<uint8_t> signature) {
    CallBack(from, std::move(signature), Status::kSuccess);
  }

  // The data that will be signed.
  const std::vector<uint8_t> data_;

  // Symmetric key id.
  const std::vector<uint8_t> key_id_;

 private:
  void CallBack(const base::Location& from,
                std::vector<uint8_t> signature,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(signature), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  SignCallback callback_;
};

class SelectCertificatesState : public NSSOperationState {
 public:
  SelectCertificatesState(
      ServiceWeakPtr weak_ptr,
      const scoped_refptr<net::SSLCertRequestInfo>& cert_request_info,
      SelectCertificatesCallback callback)
      : NSSOperationState(weak_ptr),
        cert_request_info_(cert_request_info),
        callback_(std::move(callback)) {}

  ~SelectCertificatesState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, std::unique_ptr<net::CertificateList>() /* no matches */,
             status);
  }

  void OnSuccess(const base::Location& from,
                 std::unique_ptr<net::CertificateList> matches) {
    CallBack(from, std::move(matches), Status::kSuccess);
  }

  scoped_refptr<net::SSLCertRequestInfo> cert_request_info_;
  std::unique_ptr<net::ClientCertStore> cert_store_;

 private:
  void CallBack(const base::Location& from,
                std::unique_ptr<net::CertificateList> matches,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(matches), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  SelectCertificatesCallback callback_;
};

class GetCertificatesState : public NSSOperationState {
 public:
  GetCertificatesState(ServiceWeakPtr weak_ptr,
                       GetCertificatesCallback callback)
      : NSSOperationState(weak_ptr), callback_(std::move(callback)) {}

  ~GetCertificatesState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from,
             std::unique_ptr<net::CertificateList>() /* no certificates */,
             status);
  }

  void OnSuccess(const base::Location& from,
                 std::unique_ptr<net::CertificateList> certs) {
    CallBack(from, std::move(certs), Status::kSuccess);
  }

  net::ScopedCERTCertificateList certs_;

 private:
  void CallBack(const base::Location& from,
                std::unique_ptr<net::CertificateList> certs,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(certs), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  GetCertificatesCallback callback_;
};

class GetAllKeysState : public NSSOperationState {
 public:
  GetAllKeysState(ServiceWeakPtr weak_ptr, GetAllKeysCallback callback)
      : NSSOperationState(weak_ptr), callback_(std::move(callback)) {}

  ~GetAllKeysState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from,
             /*public_key_spki_der_list=*/std::vector<std::vector<uint8_t>>(),
             status);
  }

  void OnSuccess(const base::Location& from,
                 std::vector<std::vector<uint8_t>> public_key_spki_der_list) {
    CallBack(from, std::move(public_key_spki_der_list), Status::kSuccess);
  }

 private:
  void CallBack(const base::Location& from,
                std::vector<std::vector<uint8_t>> public_key_spki_der_list,
                Status status) {
    auto bound_callback = base::BindOnce(
        std::move(callback_), std::move(public_key_spki_der_list), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  GetAllKeysCallback callback_;
};

class ImportCertificateState : public NSSOperationState {
 public:
  ImportCertificateState(ServiceWeakPtr weak_ptr,
                         const scoped_refptr<net::X509Certificate>& certificate,
                         ImportCertificateCallback callback)
      : NSSOperationState(weak_ptr),
        certificate_(certificate),
        callback_(std::move(callback)) {}

  ~ImportCertificateState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, status);
  }

  void OnSuccess(const base::Location& from) {
    CallBack(from, Status::kSuccess);
  }

  scoped_refptr<net::X509Certificate> certificate_;

 private:
  void CallBack(const base::Location& from, Status status) {
    auto bound_callback = base::BindOnce(std::move(callback_), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  ImportCertificateCallback callback_;
};

class RemoveCertificateState : public NSSOperationState {
 public:
  RemoveCertificateState(ServiceWeakPtr weak_ptr,
                         const scoped_refptr<net::X509Certificate>& certificate,
                         RemoveCertificateCallback callback)
      : NSSOperationState(weak_ptr),
        certificate_(certificate),
        callback_(std::move(callback)) {}

  ~RemoveCertificateState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, status);
  }

  void OnSuccess(const base::Location& from) {
    CallBack(from, Status::kSuccess);
  }

  scoped_refptr<net::X509Certificate> certificate_;

 private:
  void CallBack(const base::Location& from, Status status) {
    auto bound_callback = base::BindOnce(std::move(callback_), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  RemoveCertificateCallback callback_;
};

class RemoveKeyState : public NSSOperationState {
 public:
  RemoveKeyState(ServiceWeakPtr weak_ptr,
                 std::vector<uint8_t> public_key_spki_der,
                 RemoveKeyCallback callback)
      : NSSOperationState(weak_ptr),
        public_key_spki_der_(std::move(public_key_spki_der)),
        callback_(std::move(callback)) {}

  ~RemoveKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, status);
  }

  void OnSuccess(const base::Location& from) {
    CallBack(from, Status::kSuccess);
  }

  // Must be a DER encoding of a SubjectPublicKeyInfo.
  const std::vector<uint8_t> public_key_spki_der_;

 private:
  void CallBack(const base::Location& from, Status status) {
    auto bound_callback = base::BindOnce(std::move(callback_), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  RemoveKeyCallback callback_;
};

class RemoveSymKeyState : public NSSOperationState {
 public:
  RemoveSymKeyState(ServiceWeakPtr weak_ptr,
                    std::vector<uint8_t> key_id,
                    RemoveKeyCallback callback)
      : NSSOperationState(weak_ptr),
        key_id_(std::move(key_id)),
        callback_(std::move(callback)) {}

  ~RemoveSymKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, status);
  }

  void OnSuccess(const base::Location& from) {
    CallBack(from, Status::kSuccess);
  }

  // Symmetric key id.
  const std::vector<uint8_t> key_id_;

 private:
  void CallBack(const base::Location& from, Status status) {
    auto bound_callback = base::BindOnce(std::move(callback_), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  RemoveKeyCallback callback_;
};

class GetTokensState : public NSSOperationState {
 public:
  GetTokensState(ServiceWeakPtr weak_ptr, GetTokensCallback callback)
      : NSSOperationState(weak_ptr), callback_(std::move(callback)) {}

  ~GetTokensState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, std::vector<TokenId>() /* no token ids */, status);
  }

  void OnSuccess(const base::Location& from, std::vector<TokenId> token_ids) {
    CallBack(from, std::move(token_ids), Status::kSuccess);
  }

 private:
  void CallBack(const base::Location& from,
                std::vector<TokenId> token_ids,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), std::move(token_ids), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  GetTokensCallback callback_;
};

class GetKeyLocationsState : public NSSOperationState {
 public:
  GetKeyLocationsState(ServiceWeakPtr weak_ptr,
                       std::vector<uint8_t> public_key_spki_der,
                       GetKeyLocationsCallback callback)
      : NSSOperationState(weak_ptr),
        public_key_spki_der_(std::move(public_key_spki_der)),
        callback_(std::move(callback)) {}

  ~GetKeyLocationsState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*token_ids=*/std::vector<TokenId>(), status);
  }

  void OnSuccess(const base::Location& from,
                 const std::vector<TokenId>& token_ids) {
    CallBack(from, token_ids, Status::kSuccess);
  }

  // Must be a DER encoding of a SubjectPublicKeyInfo.
  const std::vector<uint8_t> public_key_spki_der_;

 private:
  void CallBack(const base::Location& from,
                const std::vector<TokenId>& token_ids,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), token_ids, status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  GetKeyLocationsCallback callback_;
};

class SetAttributeForKeyState : public NSSOperationState {
 public:
  SetAttributeForKeyState(ServiceWeakPtr weak_ptr,
                          std::vector<uint8_t> public_key_spki_der,
                          CK_ATTRIBUTE_TYPE attribute_type,
                          std::vector<uint8_t> attribute_value,
                          SetAttributeForKeyCallback callback)
      : NSSOperationState(weak_ptr),
        public_key_spki_der_(public_key_spki_der),
        attribute_type_(attribute_type),
        attribute_value_(std::move(attribute_value)),
        callback_(std::move(callback)) {}

  ~SetAttributeForKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, status);
  }

  void OnSuccess(const base::Location& from) {
    CallBack(from, Status::kSuccess);
  }

  // Must be a DER encoding of a SubjectPublicKeyInfo.
  const std::vector<uint8_t> public_key_spki_der_;
  const CK_ATTRIBUTE_TYPE attribute_type_;
  const std::vector<uint8_t> attribute_value_;

 private:
  void CallBack(const base::Location& from, Status status) {
    auto bound_callback = base::BindOnce(std::move(callback_), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  SetAttributeForKeyCallback callback_;
};

class GetAttributeForKeyState : public NSSOperationState {
 public:
  GetAttributeForKeyState(ServiceWeakPtr weak_ptr,
                          std::vector<uint8_t> public_key_spki_der,
                          CK_ATTRIBUTE_TYPE attribute_type,
                          GetAttributeForKeyCallback callback)
      : NSSOperationState(weak_ptr),
        public_key_spki_der_(public_key_spki_der),
        attribute_type_(attribute_type),
        callback_(std::move(callback)) {}

  ~GetAttributeForKeyState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*attribute_value=*/std::nullopt, status);
  }

  void OnSuccess(const base::Location& from,
                 std::optional<std::vector<uint8_t>> attribute_value) {
    CallBack(from, std::move(attribute_value), Status::kSuccess);
  }

  // Must be a DER encoding of a SubjectPublicKeyInfo.
  const std::vector<uint8_t> public_key_spki_der_;
  const CK_ATTRIBUTE_TYPE attribute_type_;

 private:
  void CallBack(const base::Location& from,
                std::optional<std::vector<uint8_t>> attribute_value,
                Status status) {
    auto bound_callback = base::BindOnce(std::move(callback_),
                                         std::move(attribute_value), status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  GetAttributeForKeyCallback callback_;
};

class IsKeyOnTokenState : public NSSOperationState {
 public:
  IsKeyOnTokenState(ServiceWeakPtr weak_ptr,
                    std::vector<uint8_t> public_key_spki_der,
                    IsKeyOnTokenCallback callback)
      : NSSOperationState(weak_ptr),
        public_key_spki_der_(std::move(public_key_spki_der)),
        callback_(std::move(callback)) {}

  ~IsKeyOnTokenState() override = default;

  void OnError(const base::Location& from, Status status) override {
    CallBack(from, /*on_token=*/std::nullopt, status);
  }

  void OnSuccess(const base::Location& from, bool on_token) {
    CallBack(from, on_token, Status::kSuccess);
  }

  // Must be a DER encoding of a SubjectPublicKeyInfo.
  const std::vector<uint8_t> public_key_spki_der_;

 private:
  void CallBack(const base::Location& from,
                std::optional<bool> on_token,
                Status status) {
    auto bound_callback =
        base::BindOnce(std::move(callback_), on_token, status);
    content::GetUIThreadTaskRunner({})->PostTask(
        from, base::BindOnce(&NSSOperationState::RunCallback,
                             std::move(bound_callback), service_weak_ptr_));
  }

  // Must be called on origin thread, therefore use CallBack().
  IsKeyOnTokenCallback callback_;
};

// Returns the private key corresponding to the der-encoded
// |public_key_spki_der| if found in |slot|. If |slot| is nullptr, the private
// key will be searched in all slots.
crypto::ScopedSECKEYPrivateKey GetPrivateKey(
    const std::vector<uint8_t>& public_key_spki_der,
    PK11SlotInfo* slot) {
  if (slot) {
    return crypto::FindNSSKeyFromPublicKeyInfoInSlot(public_key_spki_der, slot);
  }
  return crypto::FindNSSKeyFromPublicKeyInfo(public_key_spki_der);
}

CK_MECHANISM_TYPE GetSymMechanismFromKeyType(const SymKeyType key_type) {
  switch (key_type) {
    case SymKeyType::kAesCbc:
      return CKM_AES_CBC_PAD;
    case SymKeyType::kHmac:
      return CKM_SHA256_HMAC;
    case SymKeyType::kSp800Kdf:
      return CKM_SP800_108_COUNTER_KDF;
  }
}

CK_ATTRIBUTE_TYPE GetSymOperationFromKeyType(const SymKeyType key_type) {
  switch (key_type) {
    case SymKeyType::kAesCbc:
      return CKA_ENCRYPT | CKA_DECRYPT;
    case SymKeyType::kHmac:
      return CKA_SIGN;
    case SymKeyType::kSp800Kdf:
      return CKA_DERIVE;
  }
}

// Returns the symmetric key with CKA_ID equal to |key_id|
// found in |slot|. |type| specifies the type of the key.
crypto::ScopedPK11SymKey GetSymKey(std::vector<uint8_t> key_id,
                                   PK11SlotInfo* slot,
                                   std::optional<SymKeyType> key_type) {
  SECItem sec_key_id{siUTF8String, key_id.data(),
                     static_cast<unsigned int>(key_id.size())};
  CK_MECHANISM_TYPE mechanism_type;
  if (!key_type) {
    mechanism_type = CKM_GENERIC_SECRET_KEY_GEN;
  } else {
    mechanism_type = GetSymMechanismFromKeyType(*key_type);
  }
  return crypto::ScopedPK11SymKey(PK11_FindFixedKey(slot, mechanism_type,
                                                    &sec_key_id,
                                                    /*wincx=*/nullptr));
}

// Does the actual symmetric key generation on a worker thread. Used by
// GenerateSymKeyWithDB().
void GenerateSymKeyOnWorkerThread(std::unique_ptr<GenerateSymKeyState> state) {
  if (!state->slot_) {
    LOG(ERROR) << "No slot.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  if (state->key_size_ != kDefaultSymKeySize) {
    LOG(ERROR) << "Only " << kDefaultSymKeySize << "-byte keys are supported.";
    state->OnError(FROM_HERE, Status::kErrorAlgorithmNotSupported);
    return;
  }

  crypto::ScopedPK11SymKey key =
      GetSymKey(state->key_id_, state->slot_.get(), std::nullopt);
  if (key) {
    LOG(ERROR)
        << "Cannot generate key because a key with given id already exists";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  std::vector<uint8_t> key_id = state->key_id_;
  SECItem sec_key_id{siUTF8String, key_id.data(),
                     static_cast<unsigned int>(key_id.size())};
  CK_FLAGS op_flags;
  CK_MECHANISM_TYPE key_type;

  switch (state->key_type_) {
    case SymKeyType::kAesCbc:
      op_flags = CKF_ENCRYPT | CKF_DECRYPT;
      key_type = CKM_AES_KEY_GEN;
      break;
    case SymKeyType::kHmac:
      op_flags = CKF_SIGN;
      key_type = CKM_SHA256_HMAC;
      break;
    case SymKeyType::kSp800Kdf:
      op_flags = CKF_DERIVE;
      key_type = CKM_SP800_108_COUNTER_KDF;
      break;
  }

  if (!PK11_TokenKeyGenWithFlags(
          state->slot_.get(), key_type,
          /*param=*/nullptr, state->key_size_, &sec_key_id, op_flags,
          /*attr_flags=*/PK11_ATTR_TOKEN | PK11_ATTR_PRIVATE,
          /*wincx=*/nullptr)) {
    LOG(ERROR) << "Couldn't generate symmetric key.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }
  state->OnSuccess(FROM_HERE);
}

// Continues generating a symmetric key with the obtained NSSCertDatabase. Used
// by GenerateSymKey().
void GenerateSymKeyWithDB(std::unique_ptr<GenerateSymKeyState> state,
                          net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&GenerateSymKeyOnWorkerThread, std::move(state)));
}

// Does the actual RSA key generation on a worker thread. Used by
// GenerateRSAKeyWithDB().
void GenerateRSAKeyOnWorkerThread(std::unique_ptr<GenerateRSAKeyState> state) {
  if (!state->slot_) {
    LOG(ERROR) << "No slot.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  crypto::ScopedSECKEYPublicKey public_key;
  crypto::ScopedSECKEYPrivateKey private_key;

  bool key_gen_success;
  if (state->sw_backed_) {
    auto chaps_util = chromeos::ChapsUtil::Create();
    key_gen_success = chaps_util->GenerateSoftwareBackedRSAKey(
        state->slot_.get(), state->modulus_length_bits_, &public_key,
        &private_key);
  } else {
    key_gen_success = crypto::GenerateRSAKeyPairNSS(
        state->slot_.get(), state->modulus_length_bits_, true /* permanent */,
        &public_key, &private_key);
  }
  if (!key_gen_success) {
    LOG(ERROR) << "Couldn't create key, sw_backed=" << state->sw_backed_;
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  crypto::ScopedSECItem public_key_der(
      SECKEY_EncodeDERSubjectPublicKeyInfo(public_key.get()));
  if (!public_key_der) {
    // TODO(crbug.com/40115571): Remove private_key and public_key from
    // storage.
    LOG(ERROR) << "Couldn't export public key.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }
  state->OnSuccess(FROM_HERE, ScopedSECItemToBytes(public_key_der));
}

// Does the actual EC key generation on a worker thread. Used by
// GenerateECKeyWithDB().
void GenerateECKeyOnWorkerThread(std::unique_ptr<GenerateECKeyState> state) {
  if (!state->slot_) {
    LOG(ERROR) << "No slot.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  if (state->named_curve_ != "P-256") {
    LOG(ERROR) << "Only P-256 named curve is supported.";
    state->OnError(FROM_HERE, Status::kErrorAlgorithmNotSupported);
  }

  crypto::ScopedSECKEYPublicKey public_key;
  crypto::ScopedSECKEYPrivateKey private_key;
  if (!crypto::GenerateECKeyPairNSS(
          state->slot_.get(), SEC_OID_ANSIX962_EC_PRIME256V1,
          true /* permanent */, &public_key, &private_key)) {
    LOG(ERROR) << "Couldn't create key.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  crypto::ScopedSECItem public_key_der(
      SECKEY_EncodeDERSubjectPublicKeyInfo(public_key.get()));
  if (!public_key_der) {
    // TODO(crbug.com/40115571): Remove private_key and public_key from
    // storage.
    LOG(ERROR) << "Couldn't export public key.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }
  state->OnSuccess(FROM_HERE, ScopedSECItemToBytes(public_key_der));
}

// Continues generating a RSA key with the obtained NSSCertDatabase. Used by
// GenerateRSAKey().
void GenerateRSAKeyWithDB(std::unique_ptr<GenerateRSAKeyState> state,
                          net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&GenerateRSAKeyOnWorkerThread, std::move(state)));
}

// Continues generating an EC key with the obtained NSSCertDatabase. Used by
// GenerateECKey().
void GenerateECKeyWithDB(std::unique_ptr<GenerateECKeyState> state,
                         net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&GenerateECKeyOnWorkerThread, std::move(state)));
}

// Does the actual AES encryption/decryption on a worker thread.
// Used by EncryptDecryptAESWithDB().
void EncryptDecryptAESOnWorkerThread(
    std::unique_ptr<EncryptDecryptState> state) {
  if (!state->slot_) {
    LOG(ERROR) << "No slot.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  if (state->algorithm_ != "AES-CBC") {
    LOG(ERROR) << "Only AES-CBC encryption is supported.";
    state->OnError(FROM_HERE, Status::kErrorAlgorithmNotSupported);
    return;
  }

  std::vector<uint8_t> iv = state->init_vector_;
  if (iv.size() != 16) {
    LOG(ERROR) << "Initialization vector's length should be equal to 16.";
    state->OnError(FROM_HERE, Status::kErrorAlgorithmNotSupported);
    return;
  }

  crypto::ScopedPK11SymKey key =
      GetSymKey(state->key_id_, state->slot_.get(), SymKeyType::kAesCbc);
  if (!key) {
    LOG(ERROR) << "Couldn't find the symmetric key.";
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  SECItem sec_iv{siUTF8String, iv.data(), static_cast<unsigned int>(iv.size())};
  // Input string might be padded so its length would be a multiple of 16, which
  // means the encrypted string could be larger than the initial one.
  std::vector<uint8_t> result(state->input_data_.size() + 16);
  unsigned int result_len = 0;

  switch (state->operation_type_) {
    case OperationType::kEncrypt:
      if (PK11_Encrypt(key.get(), PK11_GetMechanism(key.get()), &sec_iv,
                       result.data(), &result_len, result.size(),
                       state->input_data_.data(),
                       state->input_data_.size()) != SECSuccess) {
        LOG(ERROR) << "Encryption failed.";
        state->OnError(FROM_HERE, Status::kErrorInternal);
        return;
      }
      break;
    case OperationType::kDecrypt:
      if (PK11_Decrypt(key.get(), PK11_GetMechanism(key.get()), &sec_iv,
                       result.data(), &result_len, result.size(),
                       state->input_data_.data(),
                       state->input_data_.size()) != SECSuccess) {
        LOG(ERROR) << "Decryption failed.";
        state->OnError(FROM_HERE, Status::kErrorInternal);
        return;
      }
      break;
  }

  result.resize(result_len);
  state->OnSuccess(FROM_HERE, std::move(result));
}

// Continues AES encryption/decryption with the obtained NSSCertDatabase.
// Used by EncryptDecryptAES().
void EncryptDecryptAESWithDB(std::unique_ptr<EncryptDecryptState> state,
                             net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&EncryptDecryptAESOnWorkerThread, std::move(state)));
}

// Does the actual key derivation on a worker thread.
// Used by DeriveSymKeyWithDB.
void DeriveSymKeyOnWorkerThread(std::unique_ptr<DeriveSymKeyState> state) {
  if (!state->slot_) {
    LOG(ERROR) << "No slot.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  crypto::ScopedPK11SymKey base_key =
      GetSymKey(state->base_key_id_, state->slot_.get(), SymKeyType::kSp800Kdf);
  if (!base_key) {
    LOG(ERROR) << "Couldn't find the symmetric base key.";
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  std::vector<uint8_t> derived_key_id = state->derived_key_id_;
  if (crypto::ScopedPK11SymKey key =
          GetSymKey(derived_key_id, state->slot_.get(), std::nullopt);
      key) {
    LOG(ERROR)
        << "Cannot derive key because a key with given id already exists";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  std::vector<uint8_t> label = state->label_;
  std::vector<uint8_t> context = state->context_;
  std::vector<CK_PRF_DATA_PARAM> data_params{
      {CK_SP800_108_BYTE_ARRAY, label.data(),
       static_cast<unsigned int>(label.size())},
      {CK_SP800_108_BYTE_ARRAY, context.data(),
       static_cast<unsigned int>(context.size())}};
  // Derivation algorithm used in testing accepts slightly different parameters.
  CK_SP800_108_COUNTER_FORMAT ck_counter{CK_TRUE, 16};
  if (state->kdf_counter_for_testing_) {
    data_params.push_back(
        {CK_SP800_108_ITERATION_VARIABLE, &ck_counter, sizeof(ck_counter)});
  }
  // prfType specifies the deriving algorithm and only CKM_SHA256_HMAC is
  // currently implemented in chaps.
  CK_SP800_108_KDF_PARAMS kdf_params = {
      /*prfType=*/CKM_SHA256_HMAC, data_params.size(), data_params.data(),
      /*ulAdditionalDerivedKeys=*/0, /*pAdditionalDerivedKeys=*/nullptr};
  SECItem param{siUTF8String, reinterpret_cast<uint8_t*>(&kdf_params),
                static_cast<unsigned int>(sizeof(CK_SP800_108_KDF_PARAMS))};

  CK_BBOOL ck_true = CK_TRUE;
  std::vector<CK_ATTRIBUTE> attrs = {
      {CKA_ID, derived_key_id.data(),
       static_cast<unsigned int>(derived_key_id.size())},
      {CKA_TOKEN, &ck_true, sizeof(ck_true)}};

  if (!PK11_DeriveWithTemplate(
          base_key.get(), PK11_GetMechanism(base_key.get()), &param,
          GetSymMechanismFromKeyType(state->derived_key_type_),
          GetSymOperationFromKeyType(state->derived_key_type_),
          kDefaultSymKeySize, attrs.data(), attrs.size(), /*isPerm=*/PR_TRUE)) {
    LOG(ERROR) << "Couldn't derive symmetric key.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }
  state->OnSuccess(FROM_HERE);
}

// Continues key derivation with the obtained NSSCertDatabase.
// Used by DeriveSymKey().
void DeriveSymKeyWithDB(std::unique_ptr<DeriveSymKeyState> state,
                        net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&DeriveSymKeyOnWorkerThread, std::move(state)));
}

// Checks whether |input_length| is lower or equal to the maximum input length
// for a RSA PKCS#1 v1.5 signature generated using |private_key| with PK11_Sign.
// Returns false if |input_length| is too large.
// If the maximum input length can not be determined (which is possible because
// it queries the PKCS#11 module), returns true and logs a warning.
bool CheckRSAPKCS1SignRawInputLength(SECKEYPrivateKey* private_key,
                                     size_t input_length) {
  // For RSA keys, PK11_Sign will perform PKCS#1 v1.5 padding, which needs at
  // least 11 bytes. RSA Sign can process an input of max. modulus length.
  // Thus the maximum input length for the sign operation is
  // |modulus_length - 11|.
  int modulus_length_bytes = PK11_GetPrivateModulusLen(private_key);
  if (modulus_length_bytes <= 0) {
    LOG(WARNING) << "Could not determine modulus length";
    return true;
  }
  size_t max_input_length_after_padding =
      static_cast<size_t>(modulus_length_bytes);
  // PKCS#1 v1.5 Padding needs at least this many bytes.
  size_t kMinPaddingLength = 11u;
  return input_length + kMinPaddingLength <= max_input_length_after_padding;
}

// Performs "raw" PKCS1 v1.5 padding + signing by calling PK11_Sign on
// |rsa_key|.
void SignRSAPKCS1RawOnWorkerThread(std::unique_ptr<SignState> state,
                                   crypto::ScopedSECKEYPrivateKey rsa_key) {
  static_assert(
      sizeof(*state->data_.data()) == sizeof(char),
      "Can't reinterpret data if it's characters are not 8 bit large.");
  SECItem input = {siBuffer, const_cast<unsigned char*>(state->data_.data()),
                   static_cast<unsigned int>(state->data_.size())};

  // Compute signature of hash.
  int signature_len = PK11_SignatureLen(rsa_key.get());
  if (signature_len <= 0) {
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  std::vector<unsigned char> signature(signature_len);
  SECItem signature_output = {siBuffer, signature.data(),
                              static_cast<unsigned int>(signature.size())};
  if (PK11_Sign(rsa_key.get(), &signature_output, &input) != SECSuccess) {
    // Input size is checked after a failure - obtaining max input size
    // involves extracting key modulus length which is not a free operation, so
    // don't bother if signing succeeded.
    // Note: It would be better if this could be determined from some library
    // return code (e.g. PORT_GetError), but this was not possible with
    // NSS+chaps at this point.
    if (!CheckRSAPKCS1SignRawInputLength(rsa_key.get(), state->data_.size())) {
      LOG(ERROR) << "Couldn't sign - input too long.";
      state->OnError(FROM_HERE, Status::kErrorInputTooLong);
      return;
    }
    LOG(ERROR) << "Couldn't sign.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }
  state->OnSuccess(FROM_HERE, std::move(signature));
}

// Does the actual RSA signing on a worker thread.
void SignRSAOnWorkerThread(std::unique_ptr<SignState> state) {
  crypto::ScopedSECKEYPrivateKey rsa_key =
      GetPrivateKey(state->public_key_spki_der_, state->slot_.get());

  // Fail if the key was not found or is of the wrong type.
  if (!rsa_key || SECKEY_GetPrivateKeyType(rsa_key.get()) != rsaKey) {
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  if (state->hash_algorithm_ == HashAlgorithm::HASH_ALGORITHM_NONE) {
    SignRSAPKCS1RawOnWorkerThread(std::move(state), std::move(rsa_key));
    return;
  }

  SECOidTag sign_alg_tag = SEC_OID_UNKNOWN;
  switch (state->hash_algorithm_) {
    case HashAlgorithm::HASH_ALGORITHM_SHA1:
      sign_alg_tag = SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION;
      break;
    case HashAlgorithm::HASH_ALGORITHM_SHA256:
      sign_alg_tag = SEC_OID_PKCS1_SHA256_WITH_RSA_ENCRYPTION;
      break;
    case HashAlgorithm::HASH_ALGORITHM_SHA384:
      sign_alg_tag = SEC_OID_PKCS1_SHA384_WITH_RSA_ENCRYPTION;
      break;
    case HashAlgorithm::HASH_ALGORITHM_SHA512:
      sign_alg_tag = SEC_OID_PKCS1_SHA512_WITH_RSA_ENCRYPTION;
      break;
    case HashAlgorithm::HASH_ALGORITHM_NONE:
      NOTREACHED();
  }

  crypto::ScopedSECItem sign_result(SECITEM_AllocItem(nullptr, nullptr, 0));
  if (SEC_SignData(sign_result.get(),
                   reinterpret_cast<const unsigned char*>(state->data_.data()),
                   state->data_.size(), rsa_key.get(),
                   sign_alg_tag) != SECSuccess) {
    LOG(ERROR) << "Couldn't sign.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  state->OnSuccess(FROM_HERE, ScopedSECItemToBytes(sign_result));
}

// Does the actual EC Signing on a worker thread.
void SignECOnWorkerThread(std::unique_ptr<SignState> state) {
  crypto::ScopedSECKEYPrivateKey ec_key =
      GetPrivateKey(state->public_key_spki_der_, state->slot_.get());

  // Fail if the key was not found or is of the wrong type.
  if (!ec_key || SECKEY_GetPrivateKeyType(ec_key.get()) != ecKey) {
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  DCHECK(state->hash_algorithm_ != HashAlgorithm::HASH_ALGORITHM_NONE);

  // Only SHA-256 algorithm is supported for ECDSA.
  if (state->hash_algorithm_ != HashAlgorithm::HASH_ALGORITHM_SHA256) {
    state->OnError(FROM_HERE, Status::kErrorAlgorithmNotSupported);
    return;
  }

  std::string signature_str;
  SECOidTag sign_alg_tag = SEC_OID_ANSIX962_ECDSA_SHA256_SIGNATURE;
  crypto::ScopedSECItem sign_result(SECITEM_AllocItem(nullptr, nullptr, 0));
  if (SEC_SignData(sign_result.get(),
                   reinterpret_cast<const unsigned char*>(state->data_.data()),
                   state->data_.size(), ec_key.get(),
                   sign_alg_tag) != SECSuccess) {
    LOG(ERROR) << "Couldn't sign using elliptic curve key.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  int signature_len = PK11_SignatureLen(ec_key.get());
  crypto::ScopedSECItem web_crypto_signature(
      DSAU_DecodeDerSigToLen(sign_result.get(), signature_len));

  if (!web_crypto_signature || web_crypto_signature->len == 0) {
    LOG(ERROR) << "Couldn't convert signature to WebCrypto format.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  state->OnSuccess(FROM_HERE, ScopedSECItemToBytes(web_crypto_signature));
}

// Decides which signing algorithm will be used. Used by SignWithDB().
void SignOnWorkerThread(std::unique_ptr<SignState> state) {
  crypto::ScopedSECKEYPrivateKey key =
      GetPrivateKey(state->public_key_spki_der_, state->slot_.get());

  if (!key) {
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  switch (state->key_type_) {
    case KeyType::kRsassaPkcs1V15:
      SignRSAOnWorkerThread(std::move(state));
      break;
    case KeyType::kEcdsa:
      SignECOnWorkerThread(std::move(state));
      break;
    case KeyType::kRsaOaep:
      NOTREACHED();
  }
}

// Continues signing with the obtained NSSCertDatabase. Used by Sign().
void SignWithDB(std::unique_ptr<SignState> state,
                net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&SignOnWorkerThread, std::move(state)));
}

// Does the actual SHA-256 HMAC signing on a worker thread.
// Used by SignSymWithDB().
void SignSymOnWorkerThread(std::unique_ptr<SignSymState> state) {
  if (!state->slot_) {
    LOG(ERROR) << "No slot.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  crypto::ScopedPK11SymKey key =
      GetSymKey(state->key_id_, state->slot_.get(), SymKeyType::kHmac);
  if (!key) {
    LOG(ERROR) << "Couldn't find the symmetric key.";
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  std::vector<uint8_t> signature(kDefaultSymSignatureLength);
  std::vector<uint8_t> data = state->data_;
  SECItem sec_signature{siUTF8String, signature.data(),
                        static_cast<unsigned int>(signature.size())};
  SECItem sec_data{siUTF8String, data.data(),
                   static_cast<unsigned int>(data.size())};

  if (PK11_SignWithSymKey(key.get(), PK11_GetMechanism(key.get()),
                          /*param=*/nullptr, &sec_signature,
                          &sec_data) != SECSuccess) {
    LOG(ERROR) << "Signing failed.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  state->OnSuccess(FROM_HERE, std::move(signature));
}

// Continues signing with the obtained NSSCertDatabase. Used by
// SignWithSymKey().
void SignSymWithDB(std::unique_ptr<SignSymState> state,
                   net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&SignSymOnWorkerThread, std::move(state)));
}

// Called when `ClientCertStoreAsh::GetClientCerts` is done. Builds the list of
// `net::CertificateList` and calls back. Used by `SelectCertificates()`.
void DidSelectCertificates(std::unique_ptr<SelectCertificatesState> state,
                           net::ClientCertIdentityList identities) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  // Convert the ClientCertIdentityList to a CertificateList since returning
  // ClientCertIdentities would require changing the platformKeys extension
  // api. This assumes that the necessary keys can be found later with
  // crypto::FindNSSKeyFromPublicKeyInfo.
  auto certs = std::make_unique<net::CertificateList>();
  for (const std::unique_ptr<net::ClientCertIdentity>& identity : identities) {
    certs->push_back(identity->certificate());
  }
  // DidSelectCertificates() may be called synchronously, so run the callback on
  // a separate event loop iteration to avoid potential reentrancy bugs.
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&SelectCertificatesState::OnSuccess,
                                std::move(state), FROM_HERE, std::move(certs)));
}

// Filters the obtained certificates on a worker thread. Used by
// DidGetCertificates().
void FilterCertificatesOnWorkerThread(
    std::unique_ptr<GetCertificatesState> state) {
  std::unique_ptr<net::CertificateList> client_certs(new net::CertificateList);
  for (net::ScopedCERTCertificateList::const_iterator it =
           state->certs_.begin();
       it != state->certs_.end(); ++it) {
    CERTCertificate* cert_handle = it->get();
    crypto::ScopedPK11Slot cert_slot(PK11_KeyForCertExists(cert_handle,
                                                           nullptr,    // keyPtr
                                                           nullptr));  // wincx

    // Keep only user certificates, i.e. certs for which the private key is
    // present and stored in the queried slot.
    if (cert_slot != state->slot_) {
      continue;
    }

    // Allow UTF-8 inside PrintableStrings in client certificates. See
    // crbug.com/770323 and crbug.com/788655.
    net::X509Certificate::UnsafeCreateOptions options;
    options.printable_string_is_utf8 = true;
    scoped_refptr<net::X509Certificate> cert =
        net::x509_util::CreateX509CertificateFromCERTCertificate(cert_handle,
                                                                 {}, options);
    if (!cert) {
      continue;
    }

    client_certs->push_back(std::move(cert));
  }

  state->OnSuccess(FROM_HERE, std::move(client_certs));
}

// Passes the obtained certificates to the worker thread for filtering. Used by
// GetCertificatesWithDB().
void DidGetCertificates(std::unique_ptr<GetCertificatesState> state,
                        net::ScopedCERTCertificateList all_certs) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  state->certs_ = std::move(all_certs);
  // This task interacts with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&FilterCertificatesOnWorkerThread, std::move(state)));
}

// Continues getting certificates with the obtained NSSCertDatabase. Used by
// GetCertificates().
void GetCertificatesWithDB(std::unique_ptr<GetCertificatesState> state,
                           net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // Get the pointer to slot before transferring ownership of |state| to the
  // callback's bound arguments.
  PK11SlotInfo* slot = state->slot_.get();
  cert_db->ListCertsInSlot(
      base::BindOnce(&DidGetCertificates, std::move(state)), slot);
}

// Returns true if |public_key| is relevant as a "platform key" that should be
// visible to chrome extensions / subsystems.
bool ShouldIncludePublicKey(SECKEYPublicKey* public_key) {
  crypto::ScopedSECItem cka_id(SECITEM_AllocItem(/*arena=*/nullptr,
                                                 /*item=*/nullptr,
                                                 /*len=*/0));
  if (PK11_ReadRawAttribute(
          /*objType=*/PK11_TypePubKey, public_key, CKA_ID, cka_id.get()) !=
      SECSuccess) {
    return false;
  }

  std::string_view cka_id_str(reinterpret_cast<char*>(cka_id->data),
                              cka_id->len);

  // Only keys generated/stored by extensions/Chrome should be visible to
  // extensions. Oemcrypto stores its key in the TPM, but that should not
  // be exposed. Look at exposing additional attributes or changing the slot
  // that Oemcrypto stores keys, so that it can be done based on properties
  // of the key. See https://crbug/com/1136396
  if (cka_id_str == "arc-oemcrypto") {
    VLOG(0) << "Filtered out arc-oemcrypto public key.";
    return false;
  }
  return true;
}

// Does the actual retrieval of the SubjectPublicKeyInfo string on a worker
// thread. Used by GetAllKeysWithDb().
void GetAllKeysOnWorkerThread(std::unique_ptr<GetAllKeysState> state) {
  DCHECK(state->slot_.get());

  std::vector<std::vector<uint8_t>> public_key_spki_der_list;

  // This assumes that there might be a public key on a slot that
  // does not have a corresponding private key. The key is then considered
  // partially deleted and should be treated as deleted (it eventually will be).
  crypto::ScopedSECKEYPublicKeyList public_keys(
      PK11_ListPublicKeysInSlot(state->slot_.get(), /*nickname=*/nullptr));

  if (!public_keys) {
    state->OnSuccess(FROM_HERE, std::move(public_key_spki_der_list));
    return;
  }

  for (SECKEYPublicKeyListNode* node = PUBKEY_LIST_HEAD(public_keys);
       !PUBKEY_LIST_END(node, public_keys); node = PUBKEY_LIST_NEXT(node)) {
    if (!ShouldIncludePublicKey(node->key)) {
      continue;
    }

    crypto::ScopedSECItem subject_public_key_info(
        SECKEY_EncodeDERSubjectPublicKeyInfo(node->key));
    if (!subject_public_key_info) {
      LOG(WARNING) << "Could not encode subject public key info.";
      continue;
    }
    if (subject_public_key_info->len == 0) {
      continue;
    }
    const std::vector<uint8_t> pubkey =
        ScopedSECItemToBytes(subject_public_key_info);
    crypto::ScopedSECKEYPrivateKey rsa_key =
        crypto::FindNSSKeyFromPublicKeyInfoInSlot(pubkey, state->slot_.get());
    if (rsa_key) {
      public_key_spki_der_list.push_back(pubkey);
    }
  }

  state->OnSuccess(FROM_HERE, std::move(public_key_spki_der_list));
}

// Continues the retrieval of the SubjectPublicKeyInfo list with |cert_db|.
// Used by GetAllKeys().
void GetAllKeysWithDb(std::unique_ptr<GetAllKeysState> state,
                      net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&GetAllKeysOnWorkerThread, std::move(state)));
}

// Does the actual certificate importing on the IO thread. Used by
// ImportCertificate().
void ImportCertificateWithDB(std::unique_ptr<ImportCertificateState> state,
                             net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  if (!state->certificate_) {
    state->OnError(FROM_HERE, Status::kNetErrorCertificateInvalid);
    return;
  }
  if (state->certificate_->HasExpired()) {
    state->OnError(FROM_HERE, Status::kNetErrorCertificateDateInvalid);
    return;
  }

  net::ScopedCERTCertificate nss_cert =
      net::x509_util::CreateCERTCertificateFromX509Certificate(
          state->certificate_.get());
  if (!nss_cert) {
    state->OnError(FROM_HERE, Status::kNetErrorCertificateInvalid);
    return;
  }

  // Check that the private key is in the correct slot.
  crypto::ScopedPK11Slot slot(
      PK11_KeyForCertExists(nss_cert.get(), nullptr, nullptr));
  if (slot.get() != state->slot_.get()) {
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  const net::Error import_status =
      static_cast<net::Error>(cert_db->ImportUserCert(nss_cert.get()));
  if (import_status != net::OK) {
    LOG(ERROR) << "Could not import certificate: "
               << net::ErrorToString(import_status);
    state->OnError(FROM_HERE, Status::kNetErrorAddUserCertFailed);
    return;
  }

  state->OnSuccess(FROM_HERE);
}

// Called on IO thread after the certificate removal is finished.
void DidRemoveCertificate(std::unique_ptr<RemoveCertificateState> state,
                          bool certificate_found,
                          bool success) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  // CertificateNotFound error has precedence over an internal error.
  if (!certificate_found) {
    state->OnError(FROM_HERE, Status::kErrorCertificateNotFound);
    return;
  }
  if (!success) {
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  state->OnSuccess(FROM_HERE);
}

// Does the actual certificate removal on the IO thread. Used by
// RemoveCertificate().
void RemoveCertificateWithDB(std::unique_ptr<RemoveCertificateState> state,
                             net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  PRBool certificate_found;
  net::ScopedCERTCertificate nss_cert =
      net::x509_util::CreateCERTCertificateFromX509Certificate(
          state->certificate_.get());
  if (!nss_cert ||
      CERT_GetCertIsPerm(nss_cert.get(), &certificate_found) != SECSuccess) {
    state->OnError(FROM_HERE, Status::kNetErrorCertificateInvalid);
    return;
  }

  cert_db->DeleteCertAndKeyAsync(
      std::move(nss_cert),
      base::BindOnce(&DidRemoveCertificate, std::move(state),
                     certificate_found != PR_FALSE));
}

// Does the actual key pair removal on a worker thread. Used by
// RemoveKeyWithDb().
void RemoveKeyOnWorkerThread(std::unique_ptr<RemoveKeyState> state) {
  DCHECK(state->slot_.get());

  crypto::ScopedSECKEYPrivateKey private_key =
      GetPrivateKey(state->public_key_spki_der_, state->slot_.get());

  if (!private_key) {
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  crypto::ScopedSECKEYPublicKey public_key(
      SECKEY_ConvertToPublicKey(private_key.get()));

  // PK11_DeleteTokenPrivateKey function frees the privKey structure
  // unconditionally, and thus releasing the ownership of the passed private
  // key.
  // |force| is set to false so as not to delete the key if there are any
  // matching certificates.
  if (PK11_DeleteTokenPrivateKey(/*privKey=*/private_key.release(),
                                 /*force=*/false) != SECSuccess) {
    LOG(ERROR) << "Cannot delete private key";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  // PK11_DeleteTokenPublicKey function frees the pubKey structure
  // unconditionally, and thus releasing the ownership of the passed private
  // key.
  if (PK11_DeleteTokenPublicKey(/*pubKey=*/public_key.release()) !=
      SECSuccess) {
    LOG(WARNING) << "Cannot delete public key";
  }

  state->OnSuccess(FROM_HERE);
}

// Continues removing the key pair with the obtained |cert_db|. Called by
// RemoveKey().
void RemoveKeyWithDb(std::unique_ptr<RemoveKeyState> state,
                     net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&RemoveKeyOnWorkerThread, std::move(state)));
}

// Does the actual symmetric key removal on a worker thread. Used by
// RemoveSymKeyWithDb().
void RemoveSymKeyOnWorkerThread(std::unique_ptr<RemoveSymKeyState> state) {
  if (!state->slot_) {
    LOG(ERROR) << "No slot.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  crypto::ScopedPK11SymKey key =
      GetSymKey(state->key_id_, state->slot_.get(), std::nullopt);
  if (!key) {
    LOG(ERROR) << "Couldn't find the symmetric key.";
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  if (PK11_DeleteTokenSymKey(key.get()) != SECSuccess) {
    LOG(ERROR) << "Failed to delete key.";
    state->OnError(FROM_HERE, Status::kErrorInternal);
    return;
  }

  state->OnSuccess(FROM_HERE);
}

// Continues removing the symmetric key with the obtained |cert_db|. Called by
// RemoveSymKey().
void RemoveSymKeyWithDb(std::unique_ptr<RemoveSymKeyState> state,
                        net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&RemoveSymKeyOnWorkerThread, std::move(state)));
}

// Does the actual work to determine which tokens are available.
void GetTokensWithDB(std::unique_ptr<GetTokensState> state,
                     net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  std::vector<TokenId> token_ids;

  // The user token will be unavailable in case of no logged in user in this
  // profile.
  if (cert_db->GetPrivateSlot()) {
    token_ids.push_back(TokenId::kUser);
  }

  if (cert_db->GetSystemSlot()) {
    token_ids.push_back(TokenId::kSystem);
  }

  DCHECK(!token_ids.empty());

  state->OnSuccess(FROM_HERE, std::move(token_ids));
}

// Does the actual work to determine which key is on which token.
void GetKeyLocationsWithDB(std::unique_ptr<GetKeyLocationsState> state,
                           net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  std::vector<TokenId> token_ids;

  const uint8_t* public_key_uint8 =
      reinterpret_cast<const uint8_t*>(state->public_key_spki_der_.data());
  std::vector<uint8_t> public_key_vector(
      public_key_uint8, public_key_uint8 + state->public_key_spki_der_.size());

  if (cert_db->GetPrivateSlot().get()) {
    crypto::ScopedSECKEYPrivateKey rsa_key =
        crypto::FindNSSKeyFromPublicKeyInfoInSlot(
            public_key_vector, cert_db->GetPrivateSlot().get());
    if (rsa_key) {
      token_ids.push_back(TokenId::kUser);
    }
  }

  // The "system" NSSCertDatabaseChromeOS instance reuses its "system slot" as
  // "public slot", but that doesn't mean it's a user-specific slot.
  if (token_ids.empty() && cert_db->GetPublicSlot().get() &&
      cert_db->GetPublicSlot().get() != cert_db->GetSystemSlot().get()) {
    crypto::ScopedSECKEYPrivateKey rsa_key =
        crypto::FindNSSKeyFromPublicKeyInfoInSlot(
            public_key_vector, cert_db->GetPublicSlot().get());
    if (rsa_key) {
      token_ids.push_back(TokenId::kUser);
    }
  }

  if (cert_db->GetSystemSlot().get()) {
    crypto::ScopedSECKEYPrivateKey rsa_key =
        crypto::FindNSSKeyFromPublicKeyInfoInSlot(
            public_key_vector, cert_db->GetSystemSlot().get());
    if (rsa_key) {
      token_ids.push_back(TokenId::kSystem);
    }
  }

  state->OnSuccess(FROM_HERE, std::move(token_ids));
}

// Translates |type| to one of the NSS softoken module's predefined key
// attributes which are used in tests.
CK_ATTRIBUTE_TYPE TranslateKeyAttributeTypeForSoftoken(KeyAttributeType type) {
  switch (type) {
    case KeyAttributeType::kCertificateProvisioningId:
      return CKA_START_DATE;
    case KeyAttributeType::kKeyPermissions:
      return CKA_END_DATE;
    case KeyAttributeType::kPlatformKeysTag:
      return CKA_OTP_TIME;
  }
}

// If |map_to_softoken_attrs| is true, translates |type| to one of the softoken
// module predefined key attributes. Otherwise, applies normal translation.
CK_ATTRIBUTE_TYPE TranslateKeyAttributeType(KeyAttributeType type,
                                            bool map_to_softoken_attrs) {
  if (map_to_softoken_attrs) {
    return TranslateKeyAttributeTypeForSoftoken(type);
  }

  switch (type) {
    case KeyAttributeType::kCertificateProvisioningId:
      return pkcs11_custom_attributes::kCkaChromeOsBuiltinProvisioningProfileId;
    case KeyAttributeType::kKeyPermissions:
      return pkcs11_custom_attributes::kCkaChromeOsKeyPermissions;
    case KeyAttributeType::kPlatformKeysTag:
      return pkcs11_custom_attributes::kCkaChromeOsPlatformKeysTag;
  }
}

// Does the actual attribute value setting. Called by
// SetAttributeForKeyWithDb().
void SetAttributeForKeyWithDbOnWorkerThread(
    std::unique_ptr<SetAttributeForKeyState> state) {
  DCHECK(state->slot_.get());

  crypto::ScopedSECKEYPrivateKey private_key =
      GetPrivateKey(state->public_key_spki_der_, state->slot_.get());
  if (!private_key) {
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  // This SECItem will point to data owned by |state| so it is not necessary to
  // use ScopedSECItem.
  SECItem attribute_value;
  attribute_value.data = const_cast<uint8_t*>(state->attribute_value_.data());
  attribute_value.len = state->attribute_value_.size();
  if (PK11_WriteRawAttribute(
          /*objType=*/PK11_TypePrivKey, private_key.get(),
          state->attribute_type_, &attribute_value) != SECSuccess) {
    state->OnError(FROM_HERE, Status::kErrorKeyAttributeSettingFailed);
    return;
  }

  state->OnSuccess(FROM_HERE);
}

// Continues setting the attribute with the obtained NSSCertDatabase.
// Called by SetAttributeForKey().
void SetAttributeForKeyWithDb(std::unique_ptr<SetAttributeForKeyState> state,
                              net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task could interact with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&SetAttributeForKeyWithDbOnWorkerThread,
                     std::move(state)));
}

// Does the actual attribute value retrieval. Called by
// GetAttributeForKeyWithDb().
void GetAttributeForKeyWithDbOnWorkerThread(
    std::unique_ptr<GetAttributeForKeyState> state) {
  DCHECK(state->slot_.get());

  crypto::ScopedSECKEYPrivateKey private_key =
      GetPrivateKey(state->public_key_spki_der_, state->slot_.get());

  if (!private_key) {
    state->OnError(FROM_HERE, Status::kErrorKeyNotFound);
    return;
  }

  crypto::ScopedSECItem attribute_value(SECITEM_AllocItem(/*arena=*/nullptr,
                                                          /*item=*/nullptr,
                                                          /*len=*/0));
  DCHECK(attribute_value.get());

  if (PK11_ReadRawAttribute(
          /*objType=*/PK11_TypePrivKey, private_key.get(),
          state->attribute_type_, attribute_value.get()) != SECSuccess) {
    // CKR_ATTRIBUTE_TYPE_INVALID is a cryptoki function return value which is
    // returned by Chaps if the attribute was not set before for the key. NSS
    // maps this error to SEC_ERROR_BAD_DATA. This error is captured here so as
    // not to return an |error| in cases of retrieving unset key attributes and
    // to return nullopt |attribute_value| instead.
    int error = PORT_GetError();
    if (error == SEC_ERROR_BAD_DATA) {
      state->OnSuccess(FROM_HERE, /*attribute_value=*/std::nullopt);
      return;
    }

    state->OnError(FROM_HERE, Status::kErrorKeyAttributeRetrievalFailed);
    return;
  }

  std::string attribute_value_str;
  if (attribute_value->len > 0) {
    attribute_value_str.assign(attribute_value->data,
                               attribute_value->data + attribute_value->len);
  }

  state->OnSuccess(FROM_HERE, ScopedSECItemToBytes(attribute_value));
}

// Continues retrieving the attribute with the obtained NSSCertDatabase.
// Called by GetAttributeForKey().
void GetAttributeForKeyWithDb(std::unique_ptr<GetAttributeForKeyState> state,
                              net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);

  // Only the slot and not the NSSCertDatabase is required. Ignore |cert_db|.
  // This task could interact with the TPM, hence MayBlock().
  base::ThreadPool::PostTask(
      FROM_HERE,
      {base::MayBlock(), base::TaskPriority::BEST_EFFORT,
       base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
      base::BindOnce(&GetAttributeForKeyWithDbOnWorkerThread,
                     std::move(state)));
}

void IsKeyOnTokenWithDb(std::unique_ptr<IsKeyOnTokenState> state,
                        net::NSSCertDatabase* cert_db) {
  DCHECK_CURRENTLY_ON(BrowserThread::IO);
  DCHECK(state->slot_.get());

  bool key_on_slot =
      GetPrivateKey(state->public_key_spki_der_, state->slot_.get()) != nullptr;
  state->OnSuccess(FROM_HERE, key_on_slot);
}

}  // namespace

void PlatformKeysServiceImpl::GenerateSymKey(TokenId token_id,
                                             std::vector<uint8_t> key_id,
                                             int key_size,
                                             SymKeyType key_type,
                                             GenerateKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<GenerateSymKeyState>(
      weak_factory_.GetWeakPtr(), std::move(key_id), key_size, key_type,
      std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();
  GetCertDatabase(token_id,
                  base::BindOnce(&GenerateSymKeyWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::GenerateRSAKey(TokenId token_id,
                                             unsigned int modulus_length_bits,
                                             bool sw_backed,
                                             GenerateKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<GenerateRSAKeyState>(
      weak_factory_.GetWeakPtr(), modulus_length_bits, sw_backed, token_id,
      std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }
  if (modulus_length_bits > kMaxRSAModulusLengthBits) {
    state->OnError(FROM_HERE, Status::kErrorAlgorithmNotSupported);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();
  GetCertDatabase(token_id,
                  base::BindOnce(&GenerateRSAKeyWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::GenerateECKey(TokenId token_id,
                                            const std::string named_curve,
                                            GenerateKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<GenerateECKeyState>(
      weak_factory_.GetWeakPtr(), std::move(named_curve), token_id,
      std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }
  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();
  GetCertDatabase(token_id,
                  base::BindOnce(&GenerateECKeyWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::EncryptDecryptAES(
    chromeos::platform_keys::TokenId token_id,
    std::vector<uint8_t>& input_data,
    std::vector<uint8_t>& key_id,
    std::string& algorithm,
    std::vector<uint8_t>& init_vector,
    EncryptDecryptCallback callback,
    OperationType operation_type) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<EncryptDecryptState>(
      weak_factory_.GetWeakPtr(), std::move(input_data), std::move(key_id),
      std::move(algorithm), std::move(init_vector), operation_type,
      std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes and we can double check that we
  // use a key of the correct token.
  GetCertDatabase(token_id,
                  base::BindOnce(&EncryptDecryptAESWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::DecryptAES(
    chromeos::platform_keys::TokenId token_id,
    std::vector<uint8_t> encrypted_data,
    std::vector<uint8_t> key_id,
    std::string decrypt_algorithm,
    std::vector<uint8_t> init_vector,
    EncryptDecryptCallback callback) {
  EncryptDecryptAES(token_id, encrypted_data, key_id, decrypt_algorithm,
                    init_vector, std::move(callback), OperationType::kDecrypt);
}

void PlatformKeysServiceImpl::EncryptAES(
    chromeos::platform_keys::TokenId token_id,
    std::vector<uint8_t> data,
    std::vector<uint8_t> key_id,
    std::string encrypt_algorithm,
    std::vector<uint8_t> init_vector,
    EncryptDecryptCallback callback) {
  EncryptDecryptAES(token_id, data, key_id, encrypt_algorithm, init_vector,
                    std::move(callback), OperationType::kEncrypt);
}

void PlatformKeysServiceImpl::DeriveSymKey(
    chromeos::platform_keys::TokenId token_id,
    std::vector<uint8_t> base_key_id,
    std::vector<uint8_t> derived_key_id,
    std::vector<uint8_t> label,
    std::vector<uint8_t> context,
    chromeos::platform_keys::SymKeyType derived_key_type,
    DeriveKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  std::unique_ptr<DeriveSymKeyState> state;
  state = std::make_unique<DeriveSymKeyState>(
      weak_factory_.GetWeakPtr(), std::move(base_key_id),
      std::move(derived_key_id), std::move(label), std::move(context),
      derived_key_type, std::move(callback),
      GetAllowAlternativeParamsForTesting());

  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes and we can double check that we
  // use a key of the correct token.
  GetCertDatabase(token_id,
                  base::BindOnce(&DeriveSymKeyWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::SignRsaPkcs1(
    std::optional<TokenId> token_id,
    std::vector<uint8_t> data,
    std::vector<uint8_t> public_key_spki_der,
    HashAlgorithm hash_algorithm,
    SignCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<SignState>(
      weak_factory_.GetWeakPtr(), std::move(data),
      std::move(public_key_spki_der), hash_algorithm,
      /*key_type=*/KeyType::kRsassaPkcs1V15, std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes and we can double check that we
  // use a key of the correct token.
  GetCertDatabase(token_id, base::BindOnce(&SignWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::SignRSAPKCS1Raw(
    std::optional<TokenId> token_id,
    std::vector<uint8_t> data,
    std::vector<uint8_t> public_key_spki_der,
    SignCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<SignState>(
      weak_factory_.GetWeakPtr(), std::move(data),
      std::move(public_key_spki_der), HashAlgorithm::HASH_ALGORITHM_NONE,
      /*key_type=*/KeyType::kRsassaPkcs1V15, std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes and we can double check that we
  // use a key of the correct token.
  GetCertDatabase(token_id, base::BindOnce(&SignWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::SignEcdsa(
    std::optional<TokenId> token_id,
    std::vector<uint8_t> data,
    std::vector<uint8_t> public_key_spki_der,
    HashAlgorithm hash_algorithm,
    SignCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<SignState>(
      weak_factory_.GetWeakPtr(), std::move(data),
      std::move(public_key_spki_der), hash_algorithm,
      /*key_type=*/KeyType::kEcdsa, std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes and we can double check that we
  // use a key of the correct token.
  GetCertDatabase(token_id, base::BindOnce(&SignWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::SignWithSymKey(std::optional<TokenId> token_id,
                                             std::vector<uint8_t> data,
                                             std::vector<uint8_t> key_id,
                                             SignCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<SignSymState>(
      weak_factory_.GetWeakPtr(), std::move(data), std::move(key_id),
      std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes and we can double check that we
  // use a key of the correct token.
  GetCertDatabase(token_id, base::BindOnce(&SignSymWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::SelectClientCertificates(
    std::vector<std::string> certificate_authorities,
    SelectCertificatesCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  auto cert_request_info = base::MakeRefCounted<net::SSLCertRequestInfo>();

  // Currently we do not pass down the requested certificate type to the net
  // layer, as it does not support filtering certificates by type. Rather, we
  // do not constrain the certificate type here, instead the caller has to apply
  // filtering afterwards.
  cert_request_info->cert_authorities = std::move(certificate_authorities);

  auto state = std::make_unique<SelectCertificatesState>(
      weak_factory_.GetWeakPtr(), cert_request_info, std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  state->cert_store_ = delegate_->CreateClientCertStore();

  // Note DidSelectCertificates() may be called synchronously.
  SelectCertificatesState* state_ptr = state.get();
  state_ptr->cert_store_->GetClientCerts(
      state_ptr->cert_request_info_,
      base::BindOnce(&DidSelectCertificates, std::move(state)));
}

void PlatformKeysServiceImpl::GetCertificates(
    TokenId token_id,
    GetCertificatesCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<GetCertificatesState>(
      weak_factory_.GetWeakPtr(), std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }
  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();
  GetCertDatabase(token_id,
                  base::BindOnce(&GetCertificatesWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::GetAllKeys(TokenId token_id,
                                         GetAllKeysCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  auto state = std::make_unique<GetAllKeysState>(weak_factory_.GetWeakPtr(),
                                                 std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();
  GetCertDatabase(token_id, base::BindOnce(&GetAllKeysWithDb, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::ImportCertificate(
    TokenId token_id,
    const scoped_refptr<net::X509Certificate>& certificate,
    ImportCertificateCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<ImportCertificateState>(
      weak_factory_.GetWeakPtr(), certificate, std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }
  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes and we can double check that we
  // use a key of the correct token.
  GetCertDatabase(token_id,
                  base::BindOnce(&ImportCertificateWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::RemoveCertificate(
    TokenId token_id,
    const scoped_refptr<net::X509Certificate>& certificate,
    RemoveCertificateCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<RemoveCertificateState>(
      weak_factory_.GetWeakPtr(), certificate, std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }
  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes.
  GetCertDatabase(token_id,
                  base::BindOnce(&RemoveCertificateWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::RemoveKey(
    TokenId token_id,
    std::vector<uint8_t> public_key_spki_der,
    RemoveKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  auto state = std::make_unique<RemoveKeyState>(weak_factory_.GetWeakPtr(),
                                                std::move(public_key_spki_der),
                                                std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes.
  GetCertDatabase(token_id, base::BindOnce(&RemoveKeyWithDb, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::RemoveSymKey(TokenId token_id,
                                           std::vector<uint8_t> key_id,
                                           RemoveKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  auto state = std::make_unique<RemoveSymKeyState>(
      weak_factory_.GetWeakPtr(), std::move(key_id), std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. But in case it's not available
  // we would get more informative status codes.
  GetCertDatabase(token_id,
                  base::BindOnce(&RemoveSymKeyWithDb, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::GetTokens(GetTokensCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<GetTokensState>(weak_factory_.GetWeakPtr(),
                                                std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }
  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();
  GetCertDatabase(/*token_id=*/std::nullopt /* don't get any specific slot */,
                  base::BindOnce(&GetTokensWithDB, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::GetKeyLocations(
    std::vector<uint8_t> public_key_spki_der,
    GetKeyLocationsCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto state = std::make_unique<GetKeyLocationsState>(
      weak_factory_.GetWeakPtr(), std::move(public_key_spki_der),
      std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }
  NSSOperationState* state_ptr = state.get();

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  GetCertDatabase(
      /*token_id=*/std::nullopt /* don't get any specific slot */,
      base::BindOnce(&GetKeyLocationsWithDB, std::move(state)), delegate_.get(),
      state_ptr);
}

void PlatformKeysServiceImpl::SetAttributeForKey(
    TokenId token_id,
    std::vector<uint8_t> public_key_spki_der,
    KeyAttributeType attribute_type,
    std::vector<uint8_t> attribute_value,
    SetAttributeForKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  CK_ATTRIBUTE_TYPE ck_attribute_type = TranslateKeyAttributeType(
      attribute_type,
      /*map_to_softoken_attrs=*/IsSetMapToSoftokenAttrsForTesting());

  auto state = std::make_unique<SetAttributeForKeyState>(
      weak_factory_.GetWeakPtr(), std::move(public_key_spki_der),
      ck_attribute_type, std::move(attribute_value), std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. Only setting the state slot is
  // required.
  GetCertDatabase(token_id,
                  base::BindOnce(&SetAttributeForKeyWithDb, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::GetAttributeForKey(
    TokenId token_id,
    std::vector<uint8_t> public_key_spki_der,
    KeyAttributeType attribute_type,
    GetAttributeForKeyCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  CK_ATTRIBUTE_TYPE ck_attribute_type = TranslateKeyAttributeType(
      attribute_type,
      /*map_to_softoken_attrs=*/IsSetMapToSoftokenAttrsForTesting());

  auto state = std::make_unique<GetAttributeForKeyState>(
      weak_factory_.GetWeakPtr(), std::move(public_key_spki_der),
      ck_attribute_type, std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. Only setting the state slot is
  // required.
  GetCertDatabase(token_id,
                  base::BindOnce(&GetAttributeForKeyWithDb, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::IsKeyOnToken(
    TokenId token_id,
    std::vector<uint8_t> public_key_spki_der,
    IsKeyOnTokenCallback callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  auto state = std::make_unique<IsKeyOnTokenState>(
      weak_factory_.GetWeakPtr(), std::move(public_key_spki_der),
      std::move(callback));
  if (delegate_->IsShutDown()) {
    state->OnError(FROM_HERE, Status::kErrorShutDown);
    return;
  }

  // Get the pointer to |state| before transferring ownership of |state| to the
  // callback's bound arguments.
  NSSOperationState* state_ptr = state.get();

  // The NSSCertDatabase object is not required. Only setting the state slot is
  // required.
  GetCertDatabase(token_id,
                  base::BindOnce(&IsKeyOnTokenWithDb, std::move(state)),
                  delegate_.get(), state_ptr);
}

void PlatformKeysServiceImpl::SetMapToSoftokenAttrsForTesting(
    bool map_to_softoken_attrs_for_testing) {
  map_to_softoken_attrs_for_testing_ = map_to_softoken_attrs_for_testing;
}

bool PlatformKeysServiceImpl::IsSetMapToSoftokenAttrsForTesting() {
  return map_to_softoken_attrs_for_testing_;
}

void PlatformKeysServiceImpl::SetAllowAlternativeParamsForTesting(
    bool allow_alternative_params_for_testing) {
  allow_alternative_params_for_testing_ = allow_alternative_params_for_testing;
}

bool PlatformKeysServiceImpl::GetAllowAlternativeParamsForTesting() {
  return allow_alternative_params_for_testing_;
}
}  // namespace ash::platform_keys