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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Functionality related to certificates.

use {
    crate::{apple_certificates::KnownCertificate, error::AppleCodesignError},
    bcder::{
        encode::{PrimitiveContent, Values},
        ConstOid, Oid,
    },
    bytes::Bytes,
    std::{convert::TryFrom, str::FromStr},
    x509_certificate::{
        certificate::KeyUsage, rfc4519::OID_COUNTRY_NAME, CapturedX509Certificate,
        InMemorySigningKeyPair, KeyAlgorithm, X509CertificateBuilder,
    },
};

/// Extended Key Usage extension.
///
/// 2.5.29.37
const OID_EXTENDED_KEY_USAGE: ConstOid = Oid(&[85, 29, 37]);

/// Extended Key Usage purpose for code signing.
///
/// 1.3.6.1.5.5.7.3.3
const OID_EKU_PURPOSE_CODE_SIGNING: ConstOid = Oid(&[43, 6, 1, 5, 5, 7, 3, 3]);

/// Extended Key Usage for purpose of `Safari Developer`.
///
/// 1.2.840.113635.100.4.8
const OID_EKU_PURPOSE_SAFARI_DEVELOPER: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 4, 8]);

/// Extended Key Usage for purpose of `3rd Party Mac Developer Installer`.
///
/// 1.2.840.113635.100.4.9
const OID_EKU_PURPOSE_3RD_PARTY_MAC_DEVELOPER_INSTALLER: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 4, 9]);

/// Extended Key Usage for purpose of `Developer ID Installer`.
///
/// 1.2.840.113635.100.4.13
const OID_EKU_PURPOSE_DEVELOPER_ID_INSTALLER: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 4, 13]);

/// All OIDs known for extended key usage.
const ALL_OID_EKUS: &[&ConstOid; 4] = &[
    &OID_EKU_PURPOSE_CODE_SIGNING,
    &OID_EKU_PURPOSE_SAFARI_DEVELOPER,
    &OID_EKU_PURPOSE_3RD_PARTY_MAC_DEVELOPER_INSTALLER,
    &OID_EKU_PURPOSE_DEVELOPER_ID_INSTALLER,
];

/// Extension for `Apple Signing`.
///
/// 1.2.840.113635.100.6.1.1
const OID_EXTENSION_APPLE_SIGNING: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 1]);

/// Extension for `iPhone Developer`.
///
/// 1.2.840.113635.100.6.1.2
const OID_EXTENSION_IPHONE_DEVELOPER: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 2]);

/// Extension for `Apple iPhone OS Application Signing`
///
/// 1.2.840.113635.100.6.1.3
const OID_EXTENSION_IPHONE_OS_APPLICATION_SIGNING: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 3]);

/// Extension for `Apple Developer Certificate (Submission)`.
///
/// May also be referred to as `iPhone Distribution`.
///
/// 1.2.840.113635.100.6.1.4
const OID_EXTENSION_APPLE_DEVELOPER_CERTIFICATE_SUBMISSION: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 4]);

/// Extension for `Safari Developer`.
///
/// 1.2.840.113635.100.6.1.5
const OID_EXTENSION_SAFARI_DEVELOPER: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 5]);

/// Extension for `Apple iPhone OS VPN Signing`
///
/// 1.2.840.113635.100.6.1.6
const OID_EXTENSION_IPHONE_OS_VPN_SIGNING: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 6]);

/// Extension for `Apple Mac App Signing (Development)`.
///
/// May also appear as `3rd Party Mac Developer Application`.
///
/// 1.2.840.113635.100.6.1.7
const OID_EXTENSION_APPLE_MAC_APP_SIGNING_DEVELOPMENT: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 7]);

/// Extension for `Apple Mac App Signing Submission`.
///
/// 1.2.840.113635.100.6.1.8
const OID_EXTENSION_APPLE_MAC_APP_SIGNING_SUBMISSION: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 8]);

/// Extension for `Mac App Store Code Signing`.
///
/// 1.2.840.113635.100.6.1.9
const OID_EXTENSION_APPLE_MAC_APP_STORE_CODE_SIGNING: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 9]);

/// Extension for `Mac App Store Installer Signing`.
///
/// 1.2.840.113635.100.6.1.10
const OID_EXTENSION_APPLE_MAC_APP_STORE_INSTALLER_SIGNING: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 10]);

// 1.2.840.113635.100.6.1.11 is unknown.

/// Extension for `Mac Developer`.
///
/// 1.2.840.113635.100.6.1.12
const OID_EXTENSION_MAC_DEVELOPER: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 12]);

/// Extension for `Developer ID Application`.
///
/// 1.2.840.113635.100.6.1.13
const OID_EXTENSION_DEVELOPER_ID_APPLICATION: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 13]);

/// Extension for `Developer ID Installer`.
///
/// 1.2.840.113635.100.6.1.14
const OID_EXTENSION_DEVELOPER_ID_INSTALLER: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 14]);

// 1.2.840.113635.100.6.1.15 looks to have something to do with core OS functionality,
// as it appears in search results for hacking Apple OS booting.

/// Extension for `Apple Pay Passbook Signing`
///
/// 1.2.840.113635.100.6.1.16
const OID_EXTENSION_PASSBOOK_SIGNING: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 16]);

/// Extension for `Web Site Push Notifications Signing`
///
/// 1.2.840.113635.100.6.1.17
const OID_EXTENSION_WEBSITE_PUSH_NOTIFICATION_SIGNING: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 17]);

/// Extension for `Developer ID Kernel`.
///
/// 1.2.840.113635.100.6.1.18
const OID_EXTENSION_DEVELOPER_ID_KERNEL: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 18]);

/// Extension for `Developer ID Date`.
///
/// This OID doesn't have a description in Apple tooling. But it
/// holds a UtcDate (with hours, minutes, and seconds all set to 0) and seems to
/// denote a date constraint to apply to validation. This is likely used
/// to validating timestamping constrains for certificate validity.
///
/// 1.2.840.113635.100.6.1.33
const OID_EXTENSION_DEVELOPER_ID_DATE: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 33]);

/// Extension for `TestFlight`.
///
/// 1.2.840.113635.100.6.1.25.1
const OID_EXTENSION_TEST_FLIGHT: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 1, 25, 1]);

/// All OIDs associated with non Certificate Authority extensions.
const ALL_OID_NON_CA_EXTENSIONS: &[&ConstOid; 18] = &[
    &OID_EXTENSION_APPLE_SIGNING,
    &OID_EXTENSION_IPHONE_DEVELOPER,
    &OID_EXTENSION_IPHONE_OS_APPLICATION_SIGNING,
    &OID_EXTENSION_APPLE_DEVELOPER_CERTIFICATE_SUBMISSION,
    &OID_EXTENSION_SAFARI_DEVELOPER,
    &OID_EXTENSION_IPHONE_OS_VPN_SIGNING,
    &OID_EXTENSION_APPLE_MAC_APP_SIGNING_DEVELOPMENT,
    &OID_EXTENSION_APPLE_MAC_APP_SIGNING_SUBMISSION,
    &OID_EXTENSION_APPLE_MAC_APP_STORE_CODE_SIGNING,
    &OID_EXTENSION_APPLE_MAC_APP_STORE_INSTALLER_SIGNING,
    &OID_EXTENSION_MAC_DEVELOPER,
    &OID_EXTENSION_DEVELOPER_ID_APPLICATION,
    &OID_EXTENSION_DEVELOPER_ID_INSTALLER,
    &OID_EXTENSION_PASSBOOK_SIGNING,
    &OID_EXTENSION_WEBSITE_PUSH_NOTIFICATION_SIGNING,
    &OID_EXTENSION_DEVELOPER_ID_KERNEL,
    &OID_EXTENSION_DEVELOPER_ID_DATE,
    &OID_EXTENSION_TEST_FLIGHT,
];

/// UserID.
///
/// 0.9.2342.19200300.100.1.1
pub const OID_USER_ID: ConstOid = Oid(&[9, 146, 38, 137, 147, 242, 44, 100, 1, 1]);

/// OID used for email address in RDN in Apple generated code signing certificates.
const OID_EMAIL_ADDRESS: ConstOid = Oid(&[42, 134, 72, 134, 247, 13, 1, 9, 1]);

/// Apple Worldwide Developer Relations.
///
/// 1.2.840.113635.100.6.2.1
const OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 1]);

/// Apple Application Integration.
///
/// 1.2.840.113635.100.6.2.3
const OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 3]);

/// Developer ID Certification Authority
///
/// 1.2.840.113635.100.6.2.6
const OID_CA_EXTENSION_DEVELOPER_ID: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 6]);

/// Apple Timestamp.
///
/// 1.2.840.113635.100.6.2.9
const OID_CA_EXTENSION_APPLE_TIMESTAMP: ConstOid = Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 9]);

/// Developer Authentication Certification Authority.
///
/// 1.2.840.113635.100.6.2.11
const OID_CA_EXTENSION_DEVELOPER_AUTHENTICATION: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 11]);

/// Apple Application Integration CA - G3
///
/// 1.2.840.113635.100.6.2.14
const OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION_G3: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 14]);

/// Apple Worldwide Developer Relations CA - G2
///
/// 1.2.840.113635.100.6.2.15
const OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS_G2: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 15]);

/// Apple Software Update Certification.
///
/// 1.2.840.113635.100.6.2.19
const OID_CA_EXTENSION_APPLE_SOFTWARE_UPDATE_CERTIFICATION: ConstOid =
    Oid(&[42, 134, 72, 134, 247, 99, 100, 6, 2, 19]);

const ALL_OID_CA_EXTENSIONS: &[&ConstOid; 8] = &[
    &OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS,
    &OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION,
    &OID_CA_EXTENSION_DEVELOPER_ID,
    &OID_CA_EXTENSION_APPLE_TIMESTAMP,
    &OID_CA_EXTENSION_DEVELOPER_AUTHENTICATION,
    &OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION_G3,
    &OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS_G2,
    &OID_CA_EXTENSION_APPLE_SOFTWARE_UPDATE_CERTIFICATION,
];

/// Describes the type of code signing that a certificate is authorized to perform.
///
/// Code signing certificates are issued with extended key usage (EKU) attributes
/// denoting what that certificate will be used for. They basically say *I'm authorized
/// to sign X*.
///
/// This type describes the different code signing key usages defined on Apple
/// platforms.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExtendedKeyUsagePurpose {
    /// Code signing.
    CodeSigning,

    /// Safari Developer.
    SafariDeveloper,

    /// 3rd Party Mac Developer Installer Packaging Signing.
    ///
    /// The certificate can be used to sign Mac installer packages.
    ThirdPartyMacDeveloperInstaller,

    /// Developer ID Installer.
    DeveloperIdInstaller,
}

impl ExtendedKeyUsagePurpose {
    pub fn all_oids() -> &'static [&'static ConstOid] {
        ALL_OID_EKUS
    }

    pub fn as_oid(&self) -> ConstOid {
        match self {
            Self::CodeSigning => OID_EKU_PURPOSE_CODE_SIGNING,
            Self::SafariDeveloper => OID_EKU_PURPOSE_SAFARI_DEVELOPER,
            Self::ThirdPartyMacDeveloperInstaller => {
                OID_EKU_PURPOSE_3RD_PARTY_MAC_DEVELOPER_INSTALLER
            }
            Self::DeveloperIdInstaller => OID_EKU_PURPOSE_DEVELOPER_ID_INSTALLER,
        }
    }
}

impl TryFrom<&Oid> for ExtendedKeyUsagePurpose {
    type Error = AppleCodesignError;

    fn try_from(oid: &Oid) -> Result<Self, Self::Error> {
        // Surely there is a way to use `match`. But the `Oid` type is a bit wonky.
        if oid.as_ref() == OID_EKU_PURPOSE_CODE_SIGNING.as_ref() {
            Ok(Self::CodeSigning)
        } else if oid.as_ref() == OID_EKU_PURPOSE_SAFARI_DEVELOPER.as_ref() {
            Ok(Self::SafariDeveloper)
        } else if oid.as_ref() == OID_EKU_PURPOSE_3RD_PARTY_MAC_DEVELOPER_INSTALLER.as_ref() {
            Ok(Self::ThirdPartyMacDeveloperInstaller)
        } else if oid.as_ref() == OID_EKU_PURPOSE_DEVELOPER_ID_INSTALLER.as_ref() {
            Ok(Self::DeveloperIdInstaller)
        } else {
            Err(AppleCodesignError::OidIsntCertificateAuthority)
        }
    }
}

/// Describes one of the many X.509 certificate extensions found on Apple code signing certificates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CodeSigningCertificateExtension {
    /// Apple Signing.
    ///
    /// (Appears to be deprecated).
    AppleSigning,

    /// iPhone Developer.
    IPhoneDeveloper,

    /// Apple iPhone OS Application Signing.
    IPhoneOsApplicationSigning,

    /// Apple Developer Certificate (Submission).
    ///
    /// May also be referred to as `iPhone Distribution`.
    AppleDeveloperCertificateSubmission,

    /// Safari Developer.
    SafariDeveloper,

    /// Apple iPhone OS VPN Signing.
    IPhoneOsVpnSigning,

    /// Apple Mac App Signing (Development).
    ///
    /// Also known as `3rd Party Mac Developer Application`.
    AppleMacAppSigningDevelopment,

    /// Apple Mac App Signing Submission.
    AppleMacAppSigningSubmission,

    /// Mac App Store Code Signing.
    AppleMacAppStoreCodeSigning,

    /// Mac App Store Installer Signing.
    AppleMacAppStoreInstallerSigning,

    /// Mac Developer.
    MacDeveloper,

    /// Developer ID Application.
    DeveloperIdApplication,

    /// Developer ID Date.
    DeveloperIdDate,

    /// Developer ID Installer.
    DeveloperIdInstaller,

    /// Apple Pay Passbook Signing.
    ApplePayPassbookSigning,

    /// Web Site Push Notifications Signing.
    WebsitePushNotificationSigning,

    /// Developer ID Kernel.
    DeveloperIdKernel,

    /// TestFlight.
    TestFlight,
}

impl CodeSigningCertificateExtension {
    /// All OIDs known to be extensions in code signing certificates.
    pub fn all_oids() -> &'static [&'static ConstOid] {
        ALL_OID_NON_CA_EXTENSIONS
    }

    pub fn as_oid(&self) -> ConstOid {
        match self {
            Self::AppleSigning => OID_EXTENSION_APPLE_SIGNING,
            Self::IPhoneDeveloper => OID_EXTENSION_IPHONE_DEVELOPER,
            Self::IPhoneOsApplicationSigning => OID_EXTENSION_IPHONE_OS_APPLICATION_SIGNING,
            Self::AppleDeveloperCertificateSubmission => {
                OID_EXTENSION_APPLE_DEVELOPER_CERTIFICATE_SUBMISSION
            }
            Self::SafariDeveloper => OID_EXTENSION_SAFARI_DEVELOPER,
            Self::IPhoneOsVpnSigning => OID_EXTENSION_IPHONE_OS_VPN_SIGNING,
            Self::AppleMacAppSigningDevelopment => OID_EXTENSION_APPLE_MAC_APP_SIGNING_DEVELOPMENT,
            Self::AppleMacAppSigningSubmission => OID_EXTENSION_APPLE_MAC_APP_SIGNING_SUBMISSION,
            Self::AppleMacAppStoreCodeSigning => OID_EXTENSION_APPLE_MAC_APP_STORE_CODE_SIGNING,
            Self::AppleMacAppStoreInstallerSigning => {
                OID_EXTENSION_APPLE_MAC_APP_STORE_INSTALLER_SIGNING
            }
            Self::MacDeveloper => OID_EXTENSION_MAC_DEVELOPER,
            Self::DeveloperIdApplication => OID_EXTENSION_DEVELOPER_ID_APPLICATION,
            Self::DeveloperIdDate => OID_EXTENSION_DEVELOPER_ID_DATE,
            Self::DeveloperIdInstaller => OID_EXTENSION_DEVELOPER_ID_INSTALLER,
            Self::ApplePayPassbookSigning => OID_EXTENSION_PASSBOOK_SIGNING,
            Self::WebsitePushNotificationSigning => OID_EXTENSION_WEBSITE_PUSH_NOTIFICATION_SIGNING,
            Self::DeveloperIdKernel => OID_EXTENSION_DEVELOPER_ID_KERNEL,
            Self::TestFlight => OID_EXTENSION_TEST_FLIGHT,
        }
    }
}

impl TryFrom<&Oid> for CodeSigningCertificateExtension {
    type Error = AppleCodesignError;

    fn try_from(oid: &Oid) -> Result<Self, Self::Error> {
        // Surely there is a way to use `match`. But the `Oid` type is a bit wonky.
        let o = oid.as_ref();

        if o == OID_EXTENSION_APPLE_SIGNING.as_ref() {
            Ok(Self::AppleSigning)
        } else if o == OID_EXTENSION_IPHONE_DEVELOPER.as_ref() {
            Ok(Self::IPhoneDeveloper)
        } else if o == OID_EXTENSION_IPHONE_OS_APPLICATION_SIGNING.as_ref() {
            Ok(Self::IPhoneOsApplicationSigning)
        } else if o == OID_EXTENSION_APPLE_DEVELOPER_CERTIFICATE_SUBMISSION.as_ref() {
            Ok(Self::AppleDeveloperCertificateSubmission)
        } else if o == OID_EXTENSION_SAFARI_DEVELOPER.as_ref() {
            Ok(Self::SafariDeveloper)
        } else if o == OID_EXTENSION_IPHONE_OS_VPN_SIGNING.as_ref() {
            Ok(Self::IPhoneOsVpnSigning)
        } else if o == OID_EXTENSION_APPLE_MAC_APP_SIGNING_DEVELOPMENT.as_ref() {
            Ok(Self::AppleMacAppSigningDevelopment)
        } else if o == OID_EXTENSION_APPLE_MAC_APP_SIGNING_SUBMISSION.as_ref() {
            Ok(Self::AppleMacAppSigningSubmission)
        } else if o == OID_EXTENSION_APPLE_MAC_APP_STORE_CODE_SIGNING.as_ref() {
            Ok(Self::AppleMacAppStoreCodeSigning)
        } else if o == OID_EXTENSION_APPLE_MAC_APP_STORE_INSTALLER_SIGNING.as_ref() {
            Ok(Self::AppleMacAppStoreInstallerSigning)
        } else if o == OID_EXTENSION_MAC_DEVELOPER.as_ref() {
            Ok(Self::MacDeveloper)
        } else if o == OID_EXTENSION_DEVELOPER_ID_APPLICATION.as_ref() {
            Ok(Self::DeveloperIdApplication)
        } else if o == OID_EXTENSION_DEVELOPER_ID_INSTALLER.as_ref() {
            Ok(Self::DeveloperIdInstaller)
        } else if o == OID_EXTENSION_PASSBOOK_SIGNING.as_ref() {
            Ok(Self::ApplePayPassbookSigning)
        } else if o == OID_EXTENSION_WEBSITE_PUSH_NOTIFICATION_SIGNING.as_ref() {
            Ok(Self::WebsitePushNotificationSigning)
        } else if o == OID_EXTENSION_DEVELOPER_ID_KERNEL.as_ref() {
            Ok(Self::DeveloperIdKernel)
        } else if o == OID_EXTENSION_DEVELOPER_ID_DATE.as_ref() {
            Ok(Self::DeveloperIdDate)
        } else if o == OID_EXTENSION_TEST_FLIGHT.as_ref() {
            Ok(Self::TestFlight)
        } else {
            Err(AppleCodesignError::OidIsntCodeSigningExtension)
        }
    }
}

/// Denotes specific certificate extensions on Apple certificate authority certificates.
///
/// Apple's CA certificates have extensions that appear to identify the role of
/// that CA. This enumeration defines those.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CertificateAuthorityExtension {
    /// Apple Worldwide Developer Relations.
    ///
    /// An intermediate CA.
    AppleWorldwideDeveloperRelations,

    /// Apple Application Integration.
    AppleApplicationIntegration,

    /// Developer ID Certification Authority.
    DeveloperId,

    /// Apple Timestamp.
    AppleTimestamp,

    /// Developer Authentication Certification Authority.
    DeveloperAuthentication,

    /// Application Application Integration CA - G3.
    AppleApplicationIntegrationG3,

    /// Apple Worldwide Developer Relations CA - G2.
    AppleWorldwideDeveloperRelationsG2,

    /// Apple Software Update Certification.
    AppleSoftwareUpdateCertification,
}

impl CertificateAuthorityExtension {
    /// All the known OIDs constituting Apple CA extensions.
    pub fn all_oids() -> &'static [&'static ConstOid] {
        ALL_OID_CA_EXTENSIONS
    }

    pub fn as_oid(&self) -> ConstOid {
        match self {
            Self::AppleWorldwideDeveloperRelations => {
                OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS
            }
            Self::AppleApplicationIntegration => OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION,
            Self::DeveloperId => OID_CA_EXTENSION_DEVELOPER_ID,
            Self::AppleTimestamp => OID_CA_EXTENSION_APPLE_TIMESTAMP,
            Self::DeveloperAuthentication => OID_CA_EXTENSION_DEVELOPER_AUTHENTICATION,
            Self::AppleApplicationIntegrationG3 => {
                OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION_G3
            }
            Self::AppleWorldwideDeveloperRelationsG2 => {
                OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS_G2
            }
            Self::AppleSoftwareUpdateCertification => {
                OID_CA_EXTENSION_APPLE_SOFTWARE_UPDATE_CERTIFICATION
            }
        }
    }
}

impl TryFrom<&Oid> for CertificateAuthorityExtension {
    type Error = AppleCodesignError;

    fn try_from(oid: &Oid) -> Result<Self, Self::Error> {
        // Surely there is a way to use `match`. But the `Oid` type is a bit wonky.
        if oid.as_ref() == OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS.as_ref() {
            Ok(Self::AppleWorldwideDeveloperRelations)
        } else if oid.as_ref() == OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION.as_ref() {
            Ok(Self::AppleApplicationIntegration)
        } else if oid.as_ref() == OID_CA_EXTENSION_DEVELOPER_ID.as_ref() {
            Ok(Self::DeveloperId)
        } else if oid.as_ref() == OID_CA_EXTENSION_APPLE_TIMESTAMP.as_ref() {
            Ok(Self::AppleTimestamp)
        } else if oid.as_ref() == OID_CA_EXTENSION_DEVELOPER_AUTHENTICATION.as_ref() {
            Ok(Self::DeveloperAuthentication)
        } else if oid.as_ref() == OID_CA_EXTENSION_APPLE_APPLICATION_INTEGRATION_G3.as_ref() {
            Ok(Self::AppleApplicationIntegrationG3)
        } else if oid.as_ref() == OID_CA_EXTENSION_APPLE_WORLDWIDE_DEVELOPER_RELATIONS_G2.as_ref() {
            Ok(Self::AppleWorldwideDeveloperRelationsG2)
        } else if oid.as_ref() == OID_CA_EXTENSION_APPLE_SOFTWARE_UPDATE_CERTIFICATION.as_ref() {
            Ok(Self::AppleSoftwareUpdateCertification)
        } else {
            Err(AppleCodesignError::OidIsntCertificateAuthority)
        }
    }
}

/// Describes combinations of certificate extensions for Apple code signing certificates.
///
/// Code signing certificates contain various X.509 extensions denoting them for
/// code signing.
///
/// This type represents various common extensions as used on Apple platforms.
///
/// Typically, you'll want to apply at most one of these extensions to a
/// new certificate in order to mark it as compatible for code signing.
///
/// This type essentially encapsulates the logic for handling of different
/// "profiles" attached to the different code signing certificates that Apple
/// issues.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CertificateProfile {
    /// Mac Installer Distribution.
    ///
    /// In `Keychain Access.app`, this might render as `3rd Party Mac Developer Installer`.
    ///
    /// Certificates are marked for EKU with `3rd Party Developer Installer Package
    /// Signing`.
    ///
    /// They also have the `Apple Mac App Signing (Submission)` extension.
    ///
    /// Typically issued by `Apple Worldwide Developer Relations Certificate
    /// Authority`.
    MacInstallerDistribution,

    /// Apple Distribution.
    ///
    /// Certificates are marked for EKU with `Code Signing`. They also have
    /// extensions `Apple Mac App Signing (Development)` and
    /// `Apple Developer Certificate (Submission)`.
    ///
    /// Typically issued by `Apple Worldwide Developer Relations Certificate Authority`.
    AppleDistribution,

    /// Apple Development.
    ///
    /// Certificates are marked for EKU with `Code Signing`. They also have
    /// extensions `Apple Developer Certificate (Development)` and
    /// `Mac Developer`.
    ///
    /// Typically issued by `Apple Worldwide Developer Relations Certificate
    /// Authority`.
    AppleDevelopment,

    /// Developer ID Application.
    ///
    /// Certificates are marked for EKU with `Code Signing`. They also have
    /// extensions for `Developer ID Application` and `Developer ID Date`.
    DeveloperIdApplication,

    /// Developer ID Installer.
    ///
    /// Certificates are marked for EKU with `Developer ID Application`. They also
    /// have extensions `Developer ID Installer` and `Developer ID Date`.
    DeveloperIdInstaller,
}

impl CertificateProfile {
    pub fn all() -> &'static [Self] {
        &[
            Self::MacInstallerDistribution,
            Self::AppleDistribution,
            Self::AppleDevelopment,
            Self::DeveloperIdApplication,
            Self::DeveloperIdInstaller,
        ]
    }

    /// Obtain the string values that variants are recognized as.
    pub fn str_names() -> &'static [&'static str] {
        &[
            "mac-installer-distribution",
            "apple-distribution",
            "apple-development",
            "developer-id-application",
            "developer-id-installer",
        ]
    }
}

impl FromStr for CertificateProfile {
    type Err = AppleCodesignError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "apple-distribution" => Ok(Self::AppleDistribution),
            "apple-development" => Ok(Self::AppleDevelopment),
            "developer-id-application" => Ok(Self::DeveloperIdApplication),
            "developer-id-installer" => Ok(Self::DeveloperIdInstaller),
            "mac-installer-distribution" => Ok(Self::MacInstallerDistribution),
            _ => Err(AppleCodesignError::UnknownCertificateProfile(s.to_string())),
        }
    }
}

/// Extends functionality of [CapturedX509Certificate] with Apple specific certificate knowledge.
pub trait AppleCertificate: Sized {
    /// Whether this is a known Apple root certificate authority.
    ///
    /// We define this criteria as a certificate in our built-in list of known
    /// Apple certificates that has the same subject and issuer Names.
    fn is_apple_root_ca(&self) -> bool;

    /// Whether this is a known Apple intermediate certificate authority.
    ///
    /// This is similar to [Self::is_apple_root_ca] except it doesn't match against
    /// known self-signed Apple certificates.
    fn is_apple_intermediate_ca(&self) -> bool;

    /// Find a [CertificateAuthorityExtension] present on this certificate.
    ///
    /// If this returns Some(T), the certificate says it is an Apple certificate
    /// whose role is issuing other certificates using for signing things.
    ///
    /// This function does not perform trust validation that the underlying
    /// certificate is a legitimate Apple issued certificate: just that it has
    /// the desired property.
    fn apple_ca_extension(&self) -> Option<CertificateAuthorityExtension>;

    /// Obtain all of Apple's [ExtendedKeyUsagePurpose] in this certificate.
    fn apple_extended_key_usage_purposes(&self) -> Vec<ExtendedKeyUsagePurpose>;

    /// Obtain all of Apple's [CodeSigningCertificateExtension] in this certificate.
    fn apple_code_signing_extensions(&self) -> Vec<CodeSigningCertificateExtension>;

    /// Attempt to guess the [CertificateProfile] associated with this certificate.
    ///
    /// This keys off present certificate extensions to guess which profile it
    /// belongs to. Incorrect guesses are possible, which is why *guess* is in the
    /// function name.
    ///
    /// Returns `None` if we don't think a [CertificateProfile] is associated with
    /// this extension.
    fn apple_guess_profile(&self) -> Option<CertificateProfile>;

    /// Attempt to resolve the certificate issuer chain back to [AppleCertificate].
    ///
    /// This is a glorified wrapper around [CapturedX509Certificate::resolve_signing_chain]
    /// that filters matches against certificates in our known set of Apple
    /// certificates and maps them back to our [KnownCertificate] Rust enumeration.
    ///
    /// False negatives (read: missing certificates) can be encountered if
    /// we don't know about an Apple CA certificate.
    fn apple_issuing_chain(&self) -> Vec<KnownCertificate>;

    /// Whether this certificate chains back to a known Apple root certificate authority.
    ///
    /// This is true if the resolved certificate issuance chain (which is
    /// confirmed via verifying the cryptographic signatures on certificates)
    /// ands in a certificate that is known to be an Apple root CA.
    fn chains_to_apple_root_ca(&self) -> bool;

    /// Obtain the chain of issuing certificates, back to a known Apple root.
    ///
    /// The returned chain starts with this certificate and ends with a known
    /// Apple root certificate authority. None is returned if this certificate
    /// doesn't appear to chain to a known Apple root CA.
    fn apple_root_certificate_chain(&self) -> Option<Vec<CapturedX509Certificate>>;

    /// Attempt to resolve the *team id* of an Apple issued certificate.
    ///
    /// The *team id* is a value like `AB42XYZ789` that is attached to your
    /// Apple Developer account. It seems to always be embedded in signing
    /// certificates as the Organizational Unit field of the subject. So this
    /// function is just a shortcut for retrieving that.
    fn apple_team_id(&self) -> Option<String>;
}

impl AppleCertificate for CapturedX509Certificate {
    fn is_apple_root_ca(&self) -> bool {
        KnownCertificate::all_roots().contains(&self)
    }

    fn is_apple_intermediate_ca(&self) -> bool {
        KnownCertificate::all().contains(&self) && !KnownCertificate::all_roots().contains(&self)
    }

    fn apple_ca_extension(&self) -> Option<CertificateAuthorityExtension> {
        let cert: &x509_certificate::rfc5280::Certificate = self.as_ref();

        cert.iter_extensions().find_map(|extension| {
            if let Ok(value) = CertificateAuthorityExtension::try_from(&extension.id) {
                Some(value)
            } else {
                None
            }
        })
    }

    fn apple_extended_key_usage_purposes(&self) -> Vec<ExtendedKeyUsagePurpose> {
        let cert: &x509_certificate::rfc5280::Certificate = self.as_ref();

        cert.iter_extensions()
            .filter_map(|extension| {
                if extension.id.as_ref() == OID_EXTENDED_KEY_USAGE.as_ref() {
                    if let Some(oid) = extension.try_decode_sequence_single_oid() {
                        if let Ok(purpose) = ExtendedKeyUsagePurpose::try_from(&oid) {
                            Some(purpose)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    }

    fn apple_code_signing_extensions(&self) -> Vec<CodeSigningCertificateExtension> {
        let cert: &x509_certificate::rfc5280::Certificate = self.as_ref();

        cert.iter_extensions()
            .filter_map(|extension| {
                if let Ok(value) = CodeSigningCertificateExtension::try_from(&extension.id) {
                    Some(value)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    }

    fn apple_guess_profile(&self) -> Option<CertificateProfile> {
        let ekus = self.apple_extended_key_usage_purposes();
        let signing = self.apple_code_signing_extensions();

        // Some EKUs uniquely identify the certificate profile. We don't yet handle
        // all EKUs because we don't have profiles defined for them.
        //
        // Ideally this logic stays in sync with apple_certificate_profile().
        if ekus.contains(&ExtendedKeyUsagePurpose::DeveloperIdInstaller) {
            Some(CertificateProfile::DeveloperIdInstaller)
        } else if ekus.contains(&ExtendedKeyUsagePurpose::ThirdPartyMacDeveloperInstaller) {
            Some(CertificateProfile::MacInstallerDistribution)
            // That's all the EKUs that have a 1:1 to CertificateProfile. Now look at
            // code signing extensions.
        } else if signing.contains(&CodeSigningCertificateExtension::DeveloperIdApplication) {
            Some(CertificateProfile::DeveloperIdApplication)
        } else if signing.contains(&CodeSigningCertificateExtension::IPhoneDeveloper)
            && signing.contains(&CodeSigningCertificateExtension::MacDeveloper)
        {
            Some(CertificateProfile::AppleDevelopment)
        } else if signing.contains(&CodeSigningCertificateExtension::AppleMacAppSigningDevelopment)
            && signing
                .contains(&CodeSigningCertificateExtension::AppleDeveloperCertificateSubmission)
        {
            Some(CertificateProfile::AppleDistribution)
        } else {
            None
        }
    }

    fn apple_issuing_chain(&self) -> Vec<KnownCertificate> {
        self.resolve_signing_chain(KnownCertificate::all().iter().copied())
            .into_iter()
            .filter_map(|cert| KnownCertificate::try_from(cert).ok())
            .collect::<Vec<_>>()
    }

    fn chains_to_apple_root_ca(&self) -> bool {
        if self.is_apple_root_ca() {
            true
        } else {
            self.resolve_signing_chain(KnownCertificate::all().iter().copied())
                .into_iter()
                .any(|cert| cert.is_apple_root_ca())
        }
    }

    fn apple_root_certificate_chain(&self) -> Option<Vec<CapturedX509Certificate>> {
        let mut chain = vec![self.clone()];

        for cert in self.resolve_signing_chain(KnownCertificate::all().iter().copied()) {
            chain.push(cert.clone());

            if cert.is_apple_root_ca() {
                break;
            }
        }

        if chain.last().unwrap().is_apple_root_ca() {
            Some(chain)
        } else {
            None
        }
    }

    fn apple_team_id(&self) -> Option<String> {
        self.subject_name()
            .find_first_attribute_string(Oid(
                x509_certificate::rfc4519::OID_ORGANIZATIONAL_UNIT_NAME
                    .as_ref()
                    .into(),
            ))
            .unwrap_or(None)
    }
}

/// Extensions to [X509CertificateBuilder] specializing in Apple certificate behavior.
///
/// Most callers should call [Self::apple_certificate_profile] to configure
/// a preset profile for the certificate being generated. After that - and it is
/// important it is after - call [Self::apple_subject] to define the subject
/// field. If you call this after registering code signing extensions, it
/// detects the appropriate format for the Common Name field.
pub trait AppleCertificateBuilder: Sized {
    /// This functions defines common attributes on the certificate subject.
    ///
    /// `team_id` is your Apple team id. It is a short alphanumeric string. You
    /// can find this at https://developer.apple.com/account/#/membership/.
    fn apple_subject(
        &mut self,
        team_id: &str,
        person_name: &str,
        country: &str,
    ) -> Result<(), AppleCodesignError>;

    /// Add an email address to the certificate's subject name.
    fn apple_email_address(&mut self, address: &str) -> Result<(), AppleCodesignError>;

    /// Add an [ExtendedKeyUsagePurpose] to this certificate.
    fn apple_extended_key_usage(
        &mut self,
        usage: ExtendedKeyUsagePurpose,
    ) -> Result<(), AppleCodesignError>;

    /// Add a certificate extension as defined by a [CodeSigningCertificateExtension] instance.
    fn apple_code_signing_certificate_extension(
        &mut self,
        extension: CodeSigningCertificateExtension,
    ) -> Result<(), AppleCodesignError>;

    /// Add a [CertificateProfile] to this builder.
    ///
    /// All certificate extensions relevant to this profile are added.
    ///
    /// This should be the first function you call after creating an instance
    /// because other functions rely on the state that it sets.
    fn apple_certificate_profile(
        &mut self,
        profile: CertificateProfile,
    ) -> Result<(), AppleCodesignError>;

    /// Find code signing extensions that are currently registered.
    fn apple_code_signing_extensions(&self) -> Vec<CodeSigningCertificateExtension>;
}

impl AppleCertificateBuilder for X509CertificateBuilder {
    fn apple_subject(
        &mut self,
        team_id: &str,
        person_name: &str,
        country: &str,
    ) -> Result<(), AppleCodesignError> {
        // TODO the subject schema here isn't totally accurate. While OU does always
        // appear to be the team id, the user id attribute can be something else.
        // For example, for Apple Development, there are a similarly formatted yet
        // different value. But the team id does still appear.
        self.subject()
            .append_utf8_string(Oid(OID_USER_ID.as_ref().into()), team_id)
            .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{:?}", e)))?;

        // Common Name is derived from the profile in use.

        let extensions = self.apple_code_signing_extensions();

        let common_name =
            if extensions.contains(&CodeSigningCertificateExtension::DeveloperIdApplication) {
                format!("Developer ID Application: {} ({})", person_name, team_id)
            } else if extensions.contains(&CodeSigningCertificateExtension::DeveloperIdInstaller) {
                format!("Developer ID Installer: {} ({})", person_name, team_id)
            } else if extensions
                .contains(&CodeSigningCertificateExtension::AppleDeveloperCertificateSubmission)
            {
                format!("Apple Distribution: {} ({})", person_name, team_id)
            } else if extensions
                .contains(&CodeSigningCertificateExtension::AppleMacAppSigningSubmission)
            {
                format!(
                    "3rd Party Mac Developer Installer: {} ({})",
                    person_name, team_id
                )
            } else if extensions.contains(&CodeSigningCertificateExtension::MacDeveloper) {
                format!("Apple Development: {} ({})", person_name, team_id)
            } else {
                format!("{} ({})", person_name, team_id)
            };

        self.subject()
            .append_common_name_utf8_string(&common_name)
            .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{:?}", e)))?;

        self.subject()
            .append_organizational_unit_utf8_string(team_id)
            .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{:?}", e)))?;

        self.subject()
            .append_organization_utf8_string(person_name)
            .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{:?}", e)))?;

        self.subject()
            .append_printable_string(Oid(OID_COUNTRY_NAME.as_ref().into()), country)
            .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{:?}", e)))?;

        Ok(())
    }

    fn apple_email_address(&mut self, address: &str) -> Result<(), AppleCodesignError> {
        self.subject()
            .append_utf8_string(Oid(OID_EMAIL_ADDRESS.as_ref().into()), address)
            .map_err(|e| AppleCodesignError::CertificateBuildError(format!("{:?}", e)))?;

        Ok(())
    }

    fn apple_extended_key_usage(
        &mut self,
        usage: ExtendedKeyUsagePurpose,
    ) -> Result<(), AppleCodesignError> {
        let payload =
            bcder::encode::sequence(Oid(Bytes::copy_from_slice(usage.as_oid().as_ref())).encode())
                .to_captured(bcder::Mode::Der);

        self.add_extension_der_data(
            Oid(OID_EXTENDED_KEY_USAGE.as_ref().into()),
            true,
            payload.as_slice(),
        );

        Ok(())
    }

    fn apple_code_signing_certificate_extension(
        &mut self,
        extension: CodeSigningCertificateExtension,
    ) -> Result<(), AppleCodesignError> {
        let (critical, payload) = match extension {
            CodeSigningCertificateExtension::IPhoneDeveloper => {
                // SEQUENCE (3 elem)
                //   OBJECT IDENTIFIER 1.2.840.113635.100.6.1.2
                //   BOOLEAN true
                //   OCTET STRING (2 byte) 0500
                //     NULL
                (true, Bytes::copy_from_slice(&[0x05, 0x00]))
            }
            CodeSigningCertificateExtension::AppleDeveloperCertificateSubmission => {
                // SEQUENCE (3 elem)
                //   OBJECT IDENTIFIER 1.2.840.113635.100.6.1.4
                //   BOOLEAN true
                //   OCTET STRING (2 byte) 0500
                //     NULL
                (true, Bytes::copy_from_slice(&[0x05, 0x00]))
            }
            CodeSigningCertificateExtension::AppleMacAppSigningDevelopment => {
                // SEQUENCE (3 elem)
                //   OBJECT IDENTIFIER 1.2.840.113635.100.6.1.7
                //   BOOLEAN true
                //   OCTET STRING (2 byte) 0500
                //     NULL
                (true, Bytes::copy_from_slice(&[0x05, 0x00]))
            }
            CodeSigningCertificateExtension::AppleMacAppSigningSubmission => {
                // SEQUENCE (3 elem)
                //   OBJECT IDENTIFIER 1.2.840.113635.100.6.1.8
                //   BOOLEAN true
                //   OCTET STRING (2 byte) 0500
                //   NULL
                (true, Bytes::copy_from_slice(&[0x05, 0x00]))
            }
            CodeSigningCertificateExtension::MacDeveloper => {
                // SEQUENCE (3 elem)
                //   OBJECT IDENTIFIER 1.2.840.113635.100.6.1.12
                //   BOOLEAN true
                //   OCTET STRING (2 byte) 0500
                //     NULL
                (true, Bytes::copy_from_slice(&[0x05, 0x00]))
            }
            CodeSigningCertificateExtension::DeveloperIdApplication => {
                // SEQUENCE (3 elem)
                //   OBJECT IDENTIFIER 1.2.840.113635.100.6.1.13
                //   BOOLEAN true
                //   OCTET STRING (2 byte) 0500
                //     NULL
                (true, Bytes::copy_from_slice(&[0x05, 0x00]))
            }
            CodeSigningCertificateExtension::DeveloperIdInstaller => {
                // SEQUENCE (3 elem)
                //   OBJECT IDENTIFIER 1.2.840.113635.100.6.1.14
                //   BOOLEAN true
                //   OCTET STRING (2 byte) 0500
                //   NULL
                (true, Bytes::copy_from_slice(&[0x05, 0x00]))
            }

            // The rest of these probably have the same payload. But until we see
            // them, don't take chances.
            _ => {
                return Err(AppleCodesignError::CertificateBuildError(format!(
                    "don't know how to handle code signing extension {:?}",
                    extension
                )));
            }
        };

        self.add_extension_der_data(
            Oid(Bytes::copy_from_slice(extension.as_oid().as_ref())),
            critical,
            payload,
        );

        Ok(())
    }

    fn apple_certificate_profile(
        &mut self,
        profile: CertificateProfile,
    ) -> Result<(), AppleCodesignError> {
        // Try to keep this logic in sync with apple_guess_profile().
        match profile {
            CertificateProfile::DeveloperIdApplication => {
                self.constraint_not_ca();
                self.apple_extended_key_usage(ExtendedKeyUsagePurpose::CodeSigning)?;
                self.key_usage(KeyUsage::DigitalSignature);

                // OID_EXTENSION_DEVELOPER_ID_DATE comes next. But we don't know what
                // that should be. It is a UTF8String instead of an ASN.1 time type
                // because who knows.

                self.apple_code_signing_certificate_extension(
                    CodeSigningCertificateExtension::DeveloperIdApplication,
                )?;
            }
            CertificateProfile::DeveloperIdInstaller => {
                self.constraint_not_ca();
                self.apple_extended_key_usage(ExtendedKeyUsagePurpose::DeveloperIdInstaller)?;
                self.key_usage(KeyUsage::DigitalSignature);

                // OID_EXTENSION_DEVELOPER_ID_DATE comes next.

                self.apple_code_signing_certificate_extension(
                    CodeSigningCertificateExtension::DeveloperIdInstaller,
                )?;
            }
            CertificateProfile::AppleDevelopment => {
                self.constraint_not_ca();
                self.apple_extended_key_usage(ExtendedKeyUsagePurpose::CodeSigning)?;
                self.key_usage(KeyUsage::DigitalSignature);
                self.apple_code_signing_certificate_extension(
                    CodeSigningCertificateExtension::IPhoneDeveloper,
                )?;
                self.apple_code_signing_certificate_extension(
                    CodeSigningCertificateExtension::MacDeveloper,
                )?;
            }
            CertificateProfile::AppleDistribution => {
                self.constraint_not_ca();
                self.apple_extended_key_usage(ExtendedKeyUsagePurpose::CodeSigning)?;
                self.key_usage(KeyUsage::DigitalSignature);

                // OID_EXTENSION_DEVELOPER_ID_DATE comes next.

                self.apple_code_signing_certificate_extension(
                    CodeSigningCertificateExtension::AppleMacAppSigningDevelopment,
                )?;
                self.apple_code_signing_certificate_extension(
                    CodeSigningCertificateExtension::AppleDeveloperCertificateSubmission,
                )?;
            }
            CertificateProfile::MacInstallerDistribution => {
                self.constraint_not_ca();
                self.apple_extended_key_usage(
                    ExtendedKeyUsagePurpose::ThirdPartyMacDeveloperInstaller,
                )?;
                self.key_usage(KeyUsage::DigitalSignature);

                self.apple_code_signing_certificate_extension(
                    CodeSigningCertificateExtension::AppleMacAppSigningSubmission,
                )?;
            }
        }

        Ok(())
    }

    fn apple_code_signing_extensions(&self) -> Vec<CodeSigningCertificateExtension> {
        self.extensions()
            .iter()
            .filter_map(|ext| {
                if let Ok(e) = CodeSigningCertificateExtension::try_from(&ext.id) {
                    Some(e)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    }
}

fn bmp_string(s: &str) -> Vec<u8> {
    let utf16: Vec<u16> = s.encode_utf16().collect();

    let mut bytes = Vec::with_capacity(utf16.len() * 2 + 2);
    for c in utf16 {
        bytes.push((c / 256) as u8);
        bytes.push((c % 256) as u8);
    }
    bytes.push(0x00);
    bytes.push(0x00);

    bytes
}

/// Parse PFX data into a key pair.
///
/// PFX data is commonly encountered in `.p12` files, such as those created
/// when exporting certificates from Apple's `Keychain Access` application.
///
/// The contents of the PFX file require a password to decrypt. However, if
/// no password was provided to create the PFX data, this password may be the
/// empty string.
pub fn parse_pfx_data(
    data: &[u8],
    password: &str,
) -> Result<(CapturedX509Certificate, InMemorySigningKeyPair), AppleCodesignError> {
    let pfx = p12::PFX::parse(data).map_err(|e| {
        AppleCodesignError::PfxParseError(format!("data does not appear to be PFX: {:?}", e))
    })?;

    if !pfx.verify_mac(password) {
        return Err(AppleCodesignError::PfxBadPassword);
    }

    // Apple's certificate export format consists of regular data content info
    // with inner ContentInfo components holding the key and certificate.
    let data = match pfx.auth_safe {
        p12::ContentInfo::Data(data) => data,
        _ => {
            return Err(AppleCodesignError::PfxParseError(
                "unexpected PFX content info".to_string(),
            ));
        }
    };

    let content_infos = yasna::parse_der(&data, |reader| {
        reader.collect_sequence_of(p12::ContentInfo::parse)
    })
    .map_err(|e| {
        AppleCodesignError::PfxParseError(format!("failed parsing inner ContentInfo: {:?}", e))
    })?;

    let bmp_password = bmp_string(password);

    let mut certificate = None;
    let mut signing_key = None;

    for content in content_infos {
        let bags_data = match content {
            p12::ContentInfo::Data(inner) => inner,
            p12::ContentInfo::EncryptedData(encrypted) => {
                encrypted.data(&bmp_password).ok_or_else(|| {
                    AppleCodesignError::PfxParseError(
                        "failed decrypting inner EncryptedData".to_string(),
                    )
                })?
            }
            p12::ContentInfo::OtherContext(_) => {
                return Err(AppleCodesignError::PfxParseError(
                    "unexpected OtherContent content in inner PFX data".to_string(),
                ));
            }
        };

        let bags = yasna::parse_ber(&bags_data, |reader| {
            reader.collect_sequence_of(p12::SafeBag::parse)
        })
        .map_err(|e| {
            AppleCodesignError::PfxParseError(format!(
                "failed parsing SafeBag within inner Data: {:?}",
                e
            ))
        })?;

        for bag in bags {
            match bag.bag {
                p12::SafeBagKind::CertBag(cert_bag) => match cert_bag {
                    p12::CertBag::X509(cert_data) => {
                        certificate = Some(CapturedX509Certificate::from_der(cert_data)?);
                    }
                    p12::CertBag::SDSI(_) => {
                        return Err(AppleCodesignError::PfxParseError(
                            "unexpected SDSI certificate data".to_string(),
                        ));
                    }
                },
                p12::SafeBagKind::Pkcs8ShroudedKeyBag(key_bag) => {
                    let decrypted = key_bag.decrypt(&bmp_password).ok_or_else(|| {
                        AppleCodesignError::PfxParseError(
                            "error decrypting PKCS8 shrouded key bag; is the password correct?"
                                .to_string(),
                        )
                    })?;

                    signing_key = Some(InMemorySigningKeyPair::from_pkcs8_der(&decrypted)?);
                }
                p12::SafeBagKind::OtherBagKind(_) => {
                    return Err(AppleCodesignError::PfxParseError(
                        "unexpected bag type in inner PFX content".to_string(),
                    ));
                }
            }
        }
    }

    match (certificate, signing_key) {
        (Some(certificate), Some(signing_key)) => Ok((certificate, signing_key)),
        (None, Some(_)) => Err(AppleCodesignError::PfxParseError(
            "failed to find x509 certificate in PFX data".to_string(),
        )),
        (_, None) => Err(AppleCodesignError::PfxParseError(
            "failed to find signing key in PFX data".to_string(),
        )),
    }
}

/// Create a new self-signed X.509 certificate suitable for signing code.
///
/// The created certificate contains all the extensions needed to convey
/// that it is used for code signing and should resemble certificates.
///
/// However, because the certificate isn't signed by Apple or another
/// trusted certificate authority, binaries signed with the certificate
/// may not pass Apple's verification requirements and the OS may refuse
/// to proceed. Needless to say, only use certificates generated with this
/// function for testing purposes only.
pub fn create_self_signed_code_signing_certificate(
    algorithm: KeyAlgorithm,
    profile: CertificateProfile,
    team_id: &str,
    person_name: &str,
    country: &str,
    validity_duration: chrono::Duration,
) -> Result<
    (
        CapturedX509Certificate,
        InMemorySigningKeyPair,
        ring::pkcs8::Document,
    ),
    AppleCodesignError,
> {
    let mut builder = X509CertificateBuilder::new(algorithm);

    builder.apple_certificate_profile(profile)?;
    builder.apple_subject(team_id, person_name, country)?;
    builder.validity_duration(validity_duration);

    Ok(builder.create_with_random_keypair()?)
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        cryptographic_message_syntax::{SignedData, SignedDataBuilder, SignerBuilder},
        x509_certificate::EcdsaCurve,
    };

    #[test]
    fn parse_keychain_p12_export() {
        let data = include_bytes!("apple-codesign-testuser.p12");

        let err = parse_pfx_data(data, "bad-password").unwrap_err();
        assert!(matches!(err, AppleCodesignError::PfxBadPassword));

        parse_pfx_data(data, "password123").unwrap();
    }

    #[test]
    fn generate_self_signed_certificate_ecdsa() {
        for curve in EcdsaCurve::all() {
            create_self_signed_code_signing_certificate(
                KeyAlgorithm::Ecdsa(*curve),
                CertificateProfile::DeveloperIdInstaller,
                "team1",
                "Joe Developer",
                "US",
                chrono::Duration::hours(1),
            )
            .unwrap();
        }
    }

    #[test]
    fn generate_self_signed_certificate_ed25519() {
        create_self_signed_code_signing_certificate(
            KeyAlgorithm::Ed25519,
            CertificateProfile::DeveloperIdInstaller,
            "team2",
            "Joe Developer",
            "US",
            chrono::Duration::hours(1),
        )
        .unwrap();
    }

    #[test]
    fn generate_all_profiles() {
        for profile in CertificateProfile::all() {
            create_self_signed_code_signing_certificate(
                KeyAlgorithm::Ed25519,
                *profile,
                "team",
                "Joe Developer",
                "Wakanda",
                chrono::Duration::hours(1),
            )
            .unwrap();
        }
    }

    #[test]
    fn cms_self_signed_certificate_signing_ecdsa() {
        for curve in EcdsaCurve::all() {
            let (cert, signing_key, _) = create_self_signed_code_signing_certificate(
                KeyAlgorithm::Ecdsa(*curve),
                CertificateProfile::DeveloperIdInstaller,
                "team",
                "Joe Developer",
                "US",
                chrono::Duration::hours(1),
            )
            .unwrap();

            let plaintext = "hello, world";

            let cms = SignedDataBuilder::default()
                .certificate(cert.clone())
                .signed_content(plaintext.as_bytes().to_vec())
                .signer(SignerBuilder::new(&signing_key, cert.clone()))
                .build_der()
                .unwrap();

            let signed_data = SignedData::parse_ber(&cms).unwrap();

            for signer in signed_data.signers() {
                signer
                    .verify_signature_with_signed_data(&signed_data)
                    .unwrap();
            }
        }
    }

    #[test]
    fn cms_self_signed_certificate_signing_ed25519() {
        let (cert, signing_key, _) = create_self_signed_code_signing_certificate(
            KeyAlgorithm::Ed25519,
            CertificateProfile::DeveloperIdInstaller,
            "team",
            "Joe Developer",
            "US",
            chrono::Duration::hours(1),
        )
        .unwrap();

        let plaintext = "hello, world";

        let cms = SignedDataBuilder::default()
            .certificate(cert.clone())
            .signed_content(plaintext.as_bytes().to_vec())
            .signer(SignerBuilder::new(&signing_key, cert))
            .build_der()
            .unwrap();

        let signed_data = SignedData::parse_ber(&cms).unwrap();

        for signer in signed_data.signers() {
            signer
                .verify_signature_with_signed_data(&signed_data)
                .unwrap();
        }
    }

    #[test]
    fn third_mac_mac() {
        let der = include_bytes!("testdata/apple-signed-3rd-party-mac.cer");
        let cert = CapturedX509Certificate::from_der(der.to_vec()).unwrap();

        assert_eq!(
            cert.apple_extended_key_usage_purposes(),
            vec![ExtendedKeyUsagePurpose::ThirdPartyMacDeveloperInstaller]
        );
        assert_eq!(
            cert.apple_code_signing_extensions(),
            vec![CodeSigningCertificateExtension::AppleMacAppSigningSubmission]
        );
        assert_eq!(
            cert.apple_guess_profile(),
            Some(CertificateProfile::MacInstallerDistribution)
        );
        assert_eq!(
            cert.apple_issuing_chain(),
            vec![
                KnownCertificate::Wwdr2030,
                KnownCertificate::AppleRootCa,
                KnownCertificate::AppleComputerIncRoot
            ]
        );
        assert!(cert.chains_to_apple_root_ca());
        assert_eq!(
            cert.apple_root_certificate_chain(),
            Some(vec![
                cert.clone(),
                (*KnownCertificate::Wwdr2030).clone(),
                (*KnownCertificate::AppleRootCa).clone()
            ])
        );
        assert_eq!(cert.apple_team_id(), Some("MK22MZP987".into()));

        let mut builder = X509CertificateBuilder::new(KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1));
        builder
            .apple_certificate_profile(CertificateProfile::MacInstallerDistribution)
            .unwrap();

        let built = builder.create_with_random_keypair().unwrap().0;

        assert_eq!(
            built.apple_extended_key_usage_purposes(),
            cert.apple_extended_key_usage_purposes()
        );
        assert_eq!(
            built.apple_code_signing_extensions(),
            cert.apple_code_signing_extensions()
        );
        assert_eq!(built.apple_guess_profile(), cert.apple_guess_profile());
        assert_eq!(built.apple_issuing_chain(), vec![]);
        assert!(!built.chains_to_apple_root_ca());
        assert!(built.apple_root_certificate_chain().is_none());
    }

    #[test]
    fn apple_development() {
        let der = include_bytes!("testdata/apple-signed-apple-development.cer");
        let cert = CapturedX509Certificate::from_der(der.to_vec()).unwrap();

        assert_eq!(
            cert.apple_extended_key_usage_purposes(),
            vec![ExtendedKeyUsagePurpose::CodeSigning]
        );
        assert_eq!(
            cert.apple_code_signing_extensions(),
            vec![
                CodeSigningCertificateExtension::IPhoneDeveloper,
                CodeSigningCertificateExtension::MacDeveloper
            ]
        );
        assert_eq!(
            cert.apple_guess_profile(),
            Some(CertificateProfile::AppleDevelopment)
        );
        assert_eq!(
            cert.apple_issuing_chain(),
            vec![
                KnownCertificate::Wwdr2030,
                KnownCertificate::AppleRootCa,
                KnownCertificate::AppleComputerIncRoot
            ],
        );
        assert!(cert.chains_to_apple_root_ca());
        assert_eq!(
            cert.apple_root_certificate_chain(),
            Some(vec![
                cert.clone(),
                (*KnownCertificate::Wwdr2030).clone(),
                (*KnownCertificate::AppleRootCa).clone()
            ])
        );
        assert_eq!(cert.apple_team_id(), Some("MK22MZP987".into()));

        let mut builder = X509CertificateBuilder::new(KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1));
        builder
            .apple_certificate_profile(CertificateProfile::AppleDevelopment)
            .unwrap();

        let built = builder.create_with_random_keypair().unwrap().0;

        assert_eq!(
            built.apple_extended_key_usage_purposes(),
            cert.apple_extended_key_usage_purposes()
        );
        assert_eq!(
            built.apple_code_signing_extensions(),
            cert.apple_code_signing_extensions()
        );
        assert_eq!(built.apple_guess_profile(), cert.apple_guess_profile());
        assert_eq!(built.apple_issuing_chain(), vec![]);
        assert!(!built.chains_to_apple_root_ca());
        assert!(built.apple_root_certificate_chain().is_none());
    }

    #[test]
    fn apple_distribution() {
        let der = include_bytes!("testdata/apple-signed-apple-distribution.cer");
        let cert = CapturedX509Certificate::from_der(der.to_vec()).unwrap();

        assert_eq!(
            cert.apple_extended_key_usage_purposes(),
            vec![ExtendedKeyUsagePurpose::CodeSigning]
        );
        assert_eq!(
            cert.apple_code_signing_extensions(),
            vec![
                CodeSigningCertificateExtension::AppleMacAppSigningDevelopment,
                CodeSigningCertificateExtension::AppleDeveloperCertificateSubmission
            ]
        );
        assert_eq!(
            cert.apple_guess_profile(),
            Some(CertificateProfile::AppleDistribution)
        );
        assert_eq!(
            cert.apple_issuing_chain(),
            vec![
                KnownCertificate::Wwdr2030,
                KnownCertificate::AppleRootCa,
                KnownCertificate::AppleComputerIncRoot
            ],
        );
        assert!(cert.chains_to_apple_root_ca());
        assert_eq!(
            cert.apple_root_certificate_chain(),
            Some(vec![
                cert.clone(),
                (*KnownCertificate::Wwdr2030).clone(),
                (*KnownCertificate::AppleRootCa).clone()
            ])
        );
        assert_eq!(cert.apple_team_id(), Some("MK22MZP987".into()));

        let mut builder = X509CertificateBuilder::new(KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1));
        builder
            .apple_certificate_profile(CertificateProfile::AppleDistribution)
            .unwrap();

        let built = builder.create_with_random_keypair().unwrap().0;

        assert_eq!(
            built.apple_extended_key_usage_purposes(),
            cert.apple_extended_key_usage_purposes()
        );
        assert_eq!(
            built.apple_code_signing_extensions(),
            cert.apple_code_signing_extensions()
        );
        assert_eq!(built.apple_guess_profile(), cert.apple_guess_profile());
        assert_eq!(built.apple_issuing_chain(), vec![]);
        assert!(!built.chains_to_apple_root_ca());
        assert!(built.apple_root_certificate_chain().is_none());
    }

    #[test]
    fn apple_developer_id_application() {
        let der = include_bytes!("testdata/apple-signed-developer-id-application.cer");
        let cert = CapturedX509Certificate::from_der(der.to_vec()).unwrap();

        assert_eq!(
            cert.apple_extended_key_usage_purposes(),
            vec![ExtendedKeyUsagePurpose::CodeSigning]
        );
        assert_eq!(
            cert.apple_code_signing_extensions(),
            vec![
                CodeSigningCertificateExtension::DeveloperIdDate,
                CodeSigningCertificateExtension::DeveloperIdApplication
            ]
        );
        assert_eq!(
            cert.apple_guess_profile(),
            Some(CertificateProfile::DeveloperIdApplication)
        );
        assert_eq!(
            cert.apple_issuing_chain(),
            vec![
                KnownCertificate::DeveloperId,
                KnownCertificate::AppleRootCa,
                KnownCertificate::AppleComputerIncRoot
            ]
        );
        assert!(cert.chains_to_apple_root_ca());
        assert_eq!(
            cert.apple_root_certificate_chain(),
            Some(vec![
                cert.clone(),
                (*KnownCertificate::DeveloperId).clone(),
                (*KnownCertificate::AppleRootCa).clone()
            ])
        );
        assert_eq!(cert.apple_team_id(), Some("MK22MZP987".into()));

        let mut builder = X509CertificateBuilder::new(KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1));
        builder
            .apple_certificate_profile(CertificateProfile::DeveloperIdApplication)
            .unwrap();

        let built = builder.create_with_random_keypair().unwrap().0;

        assert_eq!(
            built.apple_extended_key_usage_purposes(),
            cert.apple_extended_key_usage_purposes()
        );
        assert_eq!(
            built.apple_code_signing_extensions(),
            // We don't write out the date extension.
            cert.apple_code_signing_extensions()
                .into_iter()
                .filter(|e| !matches!(e, CodeSigningCertificateExtension::DeveloperIdDate))
                .collect::<Vec<_>>()
        );
        assert_eq!(built.apple_guess_profile(), cert.apple_guess_profile());
        assert_eq!(built.apple_issuing_chain(), vec![]);
        assert!(!built.chains_to_apple_root_ca());
        assert!(built.apple_root_certificate_chain().is_none());
    }

    #[test]
    fn apple_developer_id_installer() {
        let der = include_bytes!("testdata/apple-signed-developer-id-installer.cer");
        let cert = CapturedX509Certificate::from_der(der.to_vec()).unwrap();

        assert_eq!(
            cert.apple_extended_key_usage_purposes(),
            vec![ExtendedKeyUsagePurpose::DeveloperIdInstaller]
        );
        assert_eq!(
            cert.apple_code_signing_extensions(),
            vec![
                CodeSigningCertificateExtension::DeveloperIdDate,
                CodeSigningCertificateExtension::DeveloperIdInstaller
            ]
        );
        assert_eq!(
            cert.apple_guess_profile(),
            Some(CertificateProfile::DeveloperIdInstaller)
        );
        assert_eq!(
            cert.apple_issuing_chain(),
            vec![
                KnownCertificate::DeveloperId,
                KnownCertificate::AppleRootCa,
                KnownCertificate::AppleComputerIncRoot
            ]
        );
        assert!(cert.chains_to_apple_root_ca());
        assert_eq!(
            cert.apple_root_certificate_chain(),
            Some(vec![
                cert.clone(),
                (*KnownCertificate::DeveloperId).clone(),
                (*KnownCertificate::AppleRootCa).clone()
            ])
        );
        assert_eq!(cert.apple_team_id(), Some("MK22MZP987".into()));

        let mut builder = X509CertificateBuilder::new(KeyAlgorithm::Ecdsa(EcdsaCurve::Secp256r1));
        builder
            .apple_certificate_profile(CertificateProfile::DeveloperIdInstaller)
            .unwrap();

        let built = builder.create_with_random_keypair().unwrap().0;

        assert_eq!(
            built.apple_extended_key_usage_purposes(),
            cert.apple_extended_key_usage_purposes()
        );
        assert_eq!(
            built.apple_code_signing_extensions(),
            // We don't write out the date extension.
            cert.apple_code_signing_extensions()
                .into_iter()
                .filter(|e| !matches!(e, CodeSigningCertificateExtension::DeveloperIdDate))
                .collect::<Vec<_>>()
        );
        assert_eq!(built.apple_guess_profile(), cert.apple_guess_profile());
        assert_eq!(built.apple_issuing_chain(), vec![]);
        assert!(!built.chains_to_apple_root_ca());
        assert!(built.apple_root_certificate_chain().is_none());
    }
}