rustferry-apple 0.1.0

Generated Xcode host and iOS artifact backend for RustFerry
Documentation
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
//! Cross-platform validation for user-supplied Apple manual-signing assets.

use std::{
    cmp::Ordering,
    error::Error,
    fmt, str,
    time::{SystemTime, UNIX_EPOCH},
};

use openssl::{
    asn1::{Asn1Time, Asn1TimeRef},
    cms::{CMSOptions, CmsContentInfo},
    hash::MessageDigest,
    nid::Nid,
    pkcs12::Pkcs12,
    pkey::{PKeyRef, Private},
    provider::Provider,
    stack::{Stack, StackRef},
    x509::{
        X509, X509PurposeId, X509StoreContext,
        store::{X509Store, X509StoreBuilder},
        verify::X509VerifyParam,
    },
};
use rustferry_remote::{
    DevelopmentTeam, ProvisioningProfile, ProvisioningProfileParseError, SecretBytes,
    SigningCertificate, parse_decoded_provisioning_profile,
};

/// Maximum accepted PKCS#12 archive size.
pub const MAX_MANUAL_SIGNING_PKCS12_BYTES: usize = 64 * 1024 * 1024;
/// Maximum accepted PKCS#12 password size.
pub const MAX_MANUAL_SIGNING_PASSWORD_BYTES: usize = 4 * 1024;
/// Maximum accepted CMS provisioning-profile size.
pub const MAX_MANUAL_SIGNING_PROFILE_BYTES: usize = 8 * 1024 * 1024;

/// SHA-256 fingerprint of Apple's original Apple Root CA.
pub const APPLE_ROOT_CA_SHA256: &str =
    "B0B1730ECBC7FF4505142C49F1295E6EDA6BCAED7E2C68C5BE91B5A11001F024";
/// SHA-256 fingerprint of Apple Root CA - G2.
pub const APPLE_ROOT_CA_G2_SHA256: &str =
    "C2B9B042DD57830E7D117DAC55AC8AE19407D38E41D88F3215BC3A890444A050";
/// SHA-256 fingerprint of Apple Root CA - G3.
pub const APPLE_ROOT_CA_G3_SHA256: &str =
    "63343ABFB89A6A03EBB57E9B3F5FA7BE7C4F5C756F3017B3A8C488C3653E9179";

const APPLE_DEVELOPMENT_PREFIX: &str = "Apple Development: ";
const IPHONE_DEVELOPER_PREFIX: &str = "iPhone Developer: ";
const MAX_CERTIFICATE_CHAIN_DEPTH: i32 = 8;

const APPLE_ROOT_CA_PEM: &[u8] = include_bytes!("../assets/apple-root-ca.crt");
const APPLE_ROOT_CA_G2_PEM: &[u8] = include_bytes!("../assets/apple-root-ca-g2.crt");
const APPLE_ROOT_CA_G3_PEM: &[u8] = include_bytes!("../assets/apple-root-ca-g3.crt");

const PRODUCTION_TRUST_ANCHORS: [TrustAnchor<'static>; 3] = [
    TrustAnchor {
        pem: APPLE_ROOT_CA_PEM,
        sha256: APPLE_ROOT_CA_SHA256,
    },
    TrustAnchor {
        pem: APPLE_ROOT_CA_G2_PEM,
        sha256: APPLE_ROOT_CA_G2_SHA256,
    },
    TrustAnchor {
        pem: APPLE_ROOT_CA_G3_PEM,
        sha256: APPLE_ROOT_CA_G3_SHA256,
    },
];

/// One secret input field rejected before cryptographic parsing.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ManualSigningAssetField {
    /// PKCS#12 archive.
    CertificatePkcs12,
    /// PKCS#12 password.
    CertificatePassword,
    /// CMS provisioning profile.
    ProvisioningProfile,
}

impl fmt::Display for ManualSigningAssetField {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::CertificatePkcs12 => "certificate PKCS#12",
            Self::CertificatePassword => "certificate password",
            Self::ProvisioningProfile => "provisioning profile",
        })
    }
}

/// Structural reason an input was rejected before cryptographic parsing.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ManualSigningAssetInputError {
    /// Required binary input was empty.
    Empty,
    /// Input exceeded its fixed byte limit.
    TooLarge,
    /// Password was not valid UTF-8.
    PasswordEncoding,
    /// Password contained a NUL byte unsupported by OpenSSL's string API.
    PasswordContainsNul,
}

impl fmt::Display for ManualSigningAssetInputError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Empty => "is empty",
            Self::TooLarge => "exceeds its byte limit",
            Self::PasswordEncoding => "is not UTF-8",
            Self::PasswordContainsNul => "contains a NUL byte",
        })
    }
}

/// Secret, bounded inputs for one manual-signing identity and profile.
///
/// This type deliberately implements neither `Clone`, `Debug`, serialization,
/// nor field accessors. All three byte buffers are overwritten by
/// [`SecretBytes`] when cleared or dropped.
pub struct ManualSigningAssetsInput {
    certificate_pkcs12: SecretBytes,
    certificate_password: SecretBytes,
    provisioning_profile: SecretBytes,
}

/// Secret, bounded PKCS#12 identity input retained for one remote upload.
///
/// This separates the identity from target profiles so multi-target validation
/// never duplicates the private key or password in memory.
pub struct ManualSigningIdentityInput {
    certificate_pkcs12: SecretBytes,
    certificate_password: SecretBytes,
}

impl ManualSigningIdentityInput {
    /// Validate structural bounds and take ownership of one signing identity.
    ///
    /// # Errors
    ///
    /// Returns a field-only error without retaining caller-controlled content.
    pub fn new(
        certificate_pkcs12: SecretBytes,
        certificate_password: SecretBytes,
    ) -> Result<Self, ManualSigningAssetError> {
        validate_identity_input(&certificate_pkcs12, &certificate_password)?;
        Ok(Self {
            certificate_pkcs12,
            certificate_password,
        })
    }

    /// Consume the identity into its exact secret buffers.
    pub fn into_parts(self) -> (SecretBytes, SecretBytes) {
        (self.certificate_pkcs12, self.certificate_password)
    }
}

impl ManualSigningAssetsInput {
    /// Validate input bounds and take ownership of all secret buffers.
    ///
    /// Empty PKCS#12 passwords are supported.
    ///
    /// # Errors
    ///
    /// Returns a field-only error for empty, oversized, non-UTF-8, or
    /// NUL-containing input. No input content is retained in the error.
    pub fn new(
        certificate_pkcs12: SecretBytes,
        certificate_password: SecretBytes,
        provisioning_profile: SecretBytes,
    ) -> Result<Self, ManualSigningAssetError> {
        validate_identity_input(&certificate_pkcs12, &certificate_password)?;
        validate_nonempty_size(
            &provisioning_profile,
            MAX_MANUAL_SIGNING_PROFILE_BYTES,
            ManualSigningAssetField::ProvisioningProfile,
        )?;
        Ok(Self {
            certificate_pkcs12,
            certificate_password,
            provisioning_profile,
        })
    }

    /// Consume the input into the exact secret buffers supplied by the caller.
    ///
    /// This is intended for forwarding already-validated assets to a remote
    /// worker without rereading or duplicating them. Each returned buffer
    /// remains protected by [`SecretBytes`] and is overwritten when dropped.
    pub fn into_parts(self) -> (SecretBytes, SecretBytes, SecretBytes) {
        (
            self.certificate_pkcs12,
            self.certificate_password,
            self.provisioning_profile,
        )
    }
}

fn validate_identity_input(
    certificate_pkcs12: &SecretBytes,
    certificate_password: &SecretBytes,
) -> Result<(), ManualSigningAssetError> {
    validate_nonempty_size(
        certificate_pkcs12,
        MAX_MANUAL_SIGNING_PKCS12_BYTES,
        ManualSigningAssetField::CertificatePkcs12,
    )?;
    if certificate_password.len() > MAX_MANUAL_SIGNING_PASSWORD_BYTES {
        return Err(ManualSigningAssetError::InvalidInput {
            field: ManualSigningAssetField::CertificatePassword,
            reason: ManualSigningAssetInputError::TooLarge,
        });
    }
    if str::from_utf8(certificate_password.expose_secret_bytes()).is_err() {
        return Err(ManualSigningAssetError::InvalidInput {
            field: ManualSigningAssetField::CertificatePassword,
            reason: ManualSigningAssetInputError::PasswordEncoding,
        });
    }
    if certificate_password.expose_secret_bytes().contains(&0) {
        return Err(ManualSigningAssetError::InvalidInput {
            field: ManualSigningAssetField::CertificatePassword,
            reason: ManualSigningAssetInputError::PasswordContainsNul,
        });
    }
    Ok(())
}

/// Public metadata proven by PKCS#12, X.509, CMS, and profile validation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ValidatedManualSigningAssets {
    /// Public signing-certificate metadata. No private key is retained.
    pub certificate: SigningCertificate,
    /// Public provisioning-profile metadata. Raw profile bytes are not retained.
    pub profile: ProvisioningProfile,
}

/// Secret-free manual-signing asset validation failure.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ManualSigningAssetError {
    /// Input failed a fixed structural bound.
    InvalidInput {
        /// Input category; never caller data.
        field: ManualSigningAssetField,
        /// Structural reason; never caller data.
        reason: ManualSigningAssetInputError,
    },
    /// The system clock cannot supply a supported validation time.
    Clock,
    /// Required cryptographic functionality or pinned trust data was unavailable.
    CryptoUnavailable,
    /// PKCS#12 bytes were malformed.
    Pkcs12Malformed,
    /// PKCS#12 decryption or integrity verification failed.
    Pkcs12Decrypt,
    /// PKCS#12 archive contained no private key.
    MissingPrivateKey,
    /// PKCS#12 archive contained no certificate corresponding to its private key.
    MissingCertificate,
    /// Certificate public key did not match the PKCS#12 private key.
    PrivateKeyMismatch,
    /// Certificate subject did not describe an Apple development identity.
    CertificateIdentity,
    /// Certificate is not yet valid.
    CertificateNotYetValid,
    /// Certificate is expired at validation time.
    CertificateExpired,
    /// Certificate did not chain to a pinned Apple root for code signing.
    CertificateUntrusted,
    /// CMS provisioning-profile bytes were malformed.
    ProvisioningProfileCmsMalformed,
    /// CMS signature, signed content, attributes, or signer trust failed.
    ProvisioningProfileSignature,
    /// Verified CMS content was not a valid bounded provisioning-profile plist.
    ProvisioningProfileParse(ProvisioningProfileParseError),
    /// Provisioning profile creation time is in the future.
    ProvisioningProfileNotYetValid,
    /// Provisioning profile is expired at validation time.
    ProvisioningProfileExpired,
    /// Provisioning profile belongs to another development team.
    ProvisioningProfileTeamMismatch,
    /// Provisioning profile does not include the supplied signing certificate.
    ProvisioningProfileCertificateMismatch,
}

impl fmt::Display for ManualSigningAssetError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidInput { field, reason } => write!(formatter, "{field} {reason}"),
            Self::Clock => formatter.write_str("validation clock is unavailable"),
            Self::CryptoUnavailable => {
                formatter.write_str("required cryptographic validation is unavailable")
            }
            Self::Pkcs12Malformed => formatter.write_str("certificate PKCS#12 is malformed"),
            Self::Pkcs12Decrypt => {
                formatter.write_str("certificate PKCS#12 integrity or decryption failed")
            }
            Self::MissingPrivateKey => {
                formatter.write_str("certificate PKCS#12 has no private key")
            }
            Self::MissingCertificate => formatter
                .write_str("certificate PKCS#12 has no certificate matching its private key"),
            Self::PrivateKeyMismatch => {
                formatter.write_str("certificate and private key do not match")
            }
            Self::CertificateIdentity => {
                formatter.write_str("certificate is not an Apple development identity")
            }
            Self::CertificateNotYetValid => formatter.write_str("certificate is not yet valid"),
            Self::CertificateExpired => formatter.write_str("certificate is expired"),
            Self::CertificateUntrusted => {
                formatter.write_str("certificate is not trusted for Apple code signing")
            }
            Self::ProvisioningProfileCmsMalformed => {
                formatter.write_str("provisioning profile CMS is malformed")
            }
            Self::ProvisioningProfileSignature => {
                formatter.write_str("provisioning profile CMS signature or signer trust is invalid")
            }
            Self::ProvisioningProfileParse(source) => write!(formatter, "{source}"),
            Self::ProvisioningProfileNotYetValid => {
                formatter.write_str("provisioning profile is not yet valid")
            }
            Self::ProvisioningProfileExpired => {
                formatter.write_str("provisioning profile is expired")
            }
            Self::ProvisioningProfileTeamMismatch => {
                formatter.write_str("certificate and provisioning profile teams differ")
            }
            Self::ProvisioningProfileCertificateMismatch => {
                formatter.write_str("provisioning profile does not include the signing certificate")
            }
        }
    }
}

impl Error for ManualSigningAssetError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::ProvisioningProfileParse(source) => Some(source),
            _ => None,
        }
    }
}

/// Validate a PKCS#12 signing identity and Apple CMS provisioning profile.
///
/// Validation uses the current wall-clock time and exactly three pinned Apple
/// roots. It verifies the PKCS#12 integrity/decryption, key-to-certificate
/// match, code-signing certificate chain and identity, CMS signer chain and
/// signature, decoded plist bounds, expiration, team, and profile certificate
/// membership. On success it returns public metadata plus ownership of the
/// exact validated secret buffers for forwarding to a worker. On failure the
/// input is dropped and overwritten.
///
/// # Errors
///
/// Returns [`ManualSigningAssetError`] without preserving OpenSSL diagnostics
/// or caller-controlled secret content.
pub fn validate_manual_signing_assets(
    input: ManualSigningAssetsInput,
) -> Result<(ValidatedManualSigningAssets, ManualSigningAssetsInput), ManualSigningAssetError> {
    let now_unix_seconds = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| ManualSigningAssetError::Clock)?
        .as_secs();
    validate_manual_signing_assets_with_policy(
        input,
        &SigningAssetPolicy {
            trust_anchors: &PRODUCTION_TRUST_ANCHORS,
            accepted_common_name_prefixes: &[APPLE_DEVELOPMENT_PREFIX, IPHONE_DEVELOPER_PREFIX],
            now_unix_seconds,
        },
    )
}

/// Validate one PKCS#12 identity without provisioning-profile bytes.
///
/// The exact input buffers are returned on success for one later upload.
///
/// # Errors
///
/// Returns a secret-free identity-validation error.
pub fn validate_manual_signing_identity(
    input: ManualSigningIdentityInput,
) -> Result<(SigningCertificate, ManualSigningIdentityInput), ManualSigningAssetError> {
    let now_unix_seconds = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| ManualSigningAssetError::Clock)?
        .as_secs();
    let certificate = validate_manual_signing_identity_with_policy(
        &input.certificate_pkcs12,
        &input.certificate_password,
        &SigningAssetPolicy {
            trust_anchors: &PRODUCTION_TRUST_ANCHORS,
            accepted_common_name_prefixes: &[APPLE_DEVELOPMENT_PREFIX, IPHONE_DEVELOPER_PREFIX],
            now_unix_seconds,
        },
    )?;
    Ok((certificate, input))
}

/// Validate one CMS provisioning profile against an already validated identity.
///
/// The exact profile buffer is returned on success for one later upload.
///
/// # Errors
///
/// Returns a secret-free CMS, metadata, team, or certificate-membership error.
pub fn validate_manual_signing_profile(
    profile: SecretBytes,
    certificate: &SigningCertificate,
) -> Result<(ProvisioningProfile, SecretBytes), ManualSigningAssetError> {
    validate_nonempty_size(
        &profile,
        MAX_MANUAL_SIGNING_PROFILE_BYTES,
        ManualSigningAssetField::ProvisioningProfile,
    )?;
    let now_unix_seconds = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| ManualSigningAssetError::Clock)?
        .as_secs();
    let parsed = validate_manual_signing_profile_with_policy(
        &profile,
        certificate,
        &SigningAssetPolicy {
            trust_anchors: &PRODUCTION_TRUST_ANCHORS,
            accepted_common_name_prefixes: &[APPLE_DEVELOPMENT_PREFIX, IPHONE_DEVELOPER_PREFIX],
            now_unix_seconds,
        },
    )?;
    Ok((parsed, profile))
}

#[derive(Clone, Copy)]
struct TrustAnchor<'a> {
    pem: &'a [u8],
    sha256: &'a str,
}

struct SigningAssetPolicy<'a> {
    trust_anchors: &'a [TrustAnchor<'a>],
    accepted_common_name_prefixes: &'a [&'a str],
    now_unix_seconds: u64,
}

fn validate_manual_signing_assets_with_policy(
    input: ManualSigningAssetsInput,
    policy: &SigningAssetPolicy<'_>,
) -> Result<(ValidatedManualSigningAssets, ManualSigningAssetsInput), ManualSigningAssetError> {
    let certificate_metadata = validate_manual_signing_identity_with_policy(
        &input.certificate_pkcs12,
        &input.certificate_password,
        policy,
    )?;
    let profile = validate_manual_signing_profile_with_policy(
        &input.provisioning_profile,
        &certificate_metadata,
        policy,
    )?;
    Ok((
        ValidatedManualSigningAssets {
            certificate: certificate_metadata,
            profile,
        },
        input,
    ))
}

fn validate_manual_signing_identity_with_policy(
    certificate_pkcs12: &SecretBytes,
    certificate_password: &SecretBytes,
    policy: &SigningAssetPolicy<'_>,
) -> Result<SigningCertificate, ManualSigningAssetError> {
    if !is_exact_der_sequence(certificate_pkcs12.expose_secret_bytes()) {
        return Err(ManualSigningAssetError::Pkcs12Malformed);
    }
    let pkcs12 = Pkcs12::from_der(certificate_pkcs12.expose_secret_bytes())
        .map_err(|_| ManualSigningAssetError::Pkcs12Malformed)?;

    // Legacy algorithms are available only for the bounded import operation.
    // `retain_fallbacks` preserves the default provider for modern archives.
    let legacy_provider = Provider::try_load(None, "legacy", true)
        .map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    let parse_result = {
        let password = str::from_utf8(certificate_password.expose_secret_bytes())
            .map_err(|_| ManualSigningAssetError::Pkcs12Decrypt)?;
        pkcs12.parse2(password)
    };
    drop(legacy_provider);
    let parsed = parse_result.map_err(|_| ManualSigningAssetError::Pkcs12Decrypt)?;
    let private_key = parsed
        .pkey
        .ok_or(ManualSigningAssetError::MissingPrivateKey)?;
    let certificate = parsed
        .cert
        .ok_or(ManualSigningAssetError::MissingCertificate)?;
    validate_private_key_match(&certificate, &private_key)?;

    validate_certificate(&certificate, parsed.ca.as_ref(), policy)
}

fn validate_manual_signing_profile_with_policy(
    provisioning_profile: &SecretBytes,
    certificate: &SigningCertificate,
    policy: &SigningAssetPolicy<'_>,
) -> Result<ProvisioningProfile, ManualSigningAssetError> {
    if !is_exact_der_sequence(provisioning_profile.expose_secret_bytes()) {
        return Err(ManualSigningAssetError::ProvisioningProfileCmsMalformed);
    }
    let mut cms = CmsContentInfo::from_der(provisioning_profile.expose_secret_bytes())
        .map_err(|_| ManualSigningAssetError::ProvisioningProfileCmsMalformed)?;
    let cms_store = build_trust_store(policy, None)?;
    let mut decoded_profile = Vec::new();
    let verification = cms.verify(
        None,
        Some(&cms_store),
        None,
        Some(&mut decoded_profile),
        CMSOptions::BINARY,
    );
    if verification.is_err() {
        decoded_profile.fill(0);
        return Err(ManualSigningAssetError::ProvisioningProfileSignature);
    }

    let profile_result = parse_decoded_provisioning_profile(&decoded_profile);
    decoded_profile.fill(0);
    let profile = profile_result.map_err(ManualSigningAssetError::ProvisioningProfileParse)?;
    if profile.created_at_unix_seconds > policy.now_unix_seconds {
        return Err(ManualSigningAssetError::ProvisioningProfileNotYetValid);
    }
    if profile.expires_at_unix_seconds <= policy.now_unix_seconds {
        return Err(ManualSigningAssetError::ProvisioningProfileExpired);
    }
    if profile.team.id() != certificate.team.id() {
        return Err(ManualSigningAssetError::ProvisioningProfileTeamMismatch);
    }
    if !profile
        .certificate_fingerprints
        .iter()
        .any(|fingerprint| fingerprint == &certificate.sha256_fingerprint)
    {
        return Err(ManualSigningAssetError::ProvisioningProfileCertificateMismatch);
    }
    Ok(profile)
}

fn validate_private_key_match(
    certificate: &X509,
    private_key: &PKeyRef<Private>,
) -> Result<(), ManualSigningAssetError> {
    let public_key = certificate
        .public_key()
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?;
    if !public_key.public_eq(private_key) {
        return Err(ManualSigningAssetError::PrivateKeyMismatch);
    }
    Ok(())
}

fn validate_certificate(
    certificate: &X509,
    supplied_chain: Option<&Stack<X509>>,
    policy: &SigningAssetPolicy<'_>,
) -> Result<SigningCertificate, ManualSigningAssetError> {
    let now = Asn1Time::from_unix(
        policy
            .now_unix_seconds
            .try_into()
            .map_err(|_| ManualSigningAssetError::Clock)?,
    )
    .map_err(|_| ManualSigningAssetError::Clock)?;
    if certificate
        .not_before()
        .compare(&now)
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?
        == Ordering::Greater
    {
        return Err(ManualSigningAssetError::CertificateNotYetValid);
    }
    if certificate
        .not_after()
        .compare(&now)
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?
        != Ordering::Greater
    {
        return Err(ManualSigningAssetError::CertificateExpired);
    }

    let common_name = unique_subject_value(certificate, Nid::COMMONNAME)?;
    let accepted_name = policy.accepted_common_name_prefixes.iter().any(|prefix| {
        common_name
            .strip_prefix(prefix)
            .is_some_and(|remainder| !remainder.is_empty())
    });
    if !accepted_name {
        return Err(ManualSigningAssetError::CertificateIdentity);
    }
    let team_id = unique_subject_value(certificate, Nid::ORGANIZATIONALUNITNAME)?;
    let team = DevelopmentTeam::new(team_id, None)
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?;

    let empty_chain = Stack::new().map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    let chain: &StackRef<X509> = match supplied_chain {
        Some(chain) => chain.as_ref(),
        None => empty_chain.as_ref(),
    };
    let store = build_trust_store(policy, Some(X509PurposeId::CODE_SIGN))?;
    let mut context =
        X509StoreContext::new().map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    let verified = context
        .init(
            &store,
            certificate,
            chain,
            openssl::x509::X509StoreContextRef::verify_cert,
        )
        .map_err(|_| ManualSigningAssetError::CertificateUntrusted)?;
    if !verified {
        return Err(ManualSigningAssetError::CertificateUntrusted);
    }

    let fingerprint = certificate
        .digest(MessageDigest::sha256())
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?;
    let metadata = SigningCertificate {
        common_name,
        sha256_fingerprint: uppercase_hex(fingerprint.as_ref()),
        team,
        expires_at_unix_seconds: asn1_time_to_unix(certificate.not_after())?,
    };
    metadata
        .validate()
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?;
    Ok(metadata)
}

fn unique_subject_value(certificate: &X509, nid: Nid) -> Result<String, ManualSigningAssetError> {
    let mut entries = certificate.subject_name().entries_by_nid(nid);
    let entry = entries
        .next()
        .ok_or(ManualSigningAssetError::CertificateIdentity)?;
    if entries.next().is_some() {
        return Err(ManualSigningAssetError::CertificateIdentity);
    }
    let value = entry
        .data()
        .to_string()
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?;
    if value.contains('\u{fffd}') {
        return Err(ManualSigningAssetError::CertificateIdentity);
    }
    Ok(value)
}

fn build_trust_store(
    policy: &SigningAssetPolicy<'_>,
    purpose: Option<X509PurposeId>,
) -> Result<X509Store, ManualSigningAssetError> {
    if policy.trust_anchors.is_empty() {
        return Err(ManualSigningAssetError::CryptoUnavailable);
    }
    let mut builder =
        X509StoreBuilder::new().map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    for anchor in policy.trust_anchors {
        builder
            .add_cert(load_trust_anchor(*anchor)?)
            .map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    }
    let mut parameters =
        X509VerifyParam::new().map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    parameters.set_time(
        policy
            .now_unix_seconds
            .try_into()
            .map_err(|_| ManualSigningAssetError::Clock)?,
    );
    parameters.set_depth(MAX_CERTIFICATE_CHAIN_DEPTH);
    builder
        .set_param(&parameters)
        .map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    if let Some(purpose) = purpose {
        builder
            .set_purpose(purpose)
            .map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    }
    Ok(builder.build())
}

fn load_trust_anchor(anchor: TrustAnchor<'_>) -> Result<X509, ManualSigningAssetError> {
    let certificate =
        X509::from_pem(anchor.pem).map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    let fingerprint = certificate
        .digest(MessageDigest::sha256())
        .map_err(|_| ManualSigningAssetError::CryptoUnavailable)?;
    if uppercase_hex(fingerprint.as_ref()) != anchor.sha256 {
        return Err(ManualSigningAssetError::CryptoUnavailable);
    }
    Ok(certificate)
}

fn asn1_time_to_unix(time: &Asn1TimeRef) -> Result<u64, ManualSigningAssetError> {
    let epoch = Asn1Time::from_unix(0).map_err(|_| ManualSigningAssetError::CertificateIdentity)?;
    let difference = epoch
        .diff(time)
        .map_err(|_| ManualSigningAssetError::CertificateIdentity)?;
    let seconds = i64::from(difference.days)
        .checked_mul(86_400)
        .and_then(|days| days.checked_add(i64::from(difference.secs)))
        .ok_or(ManualSigningAssetError::CertificateIdentity)?;
    u64::try_from(seconds).map_err(|_| ManualSigningAssetError::CertificateIdentity)
}

fn validate_nonempty_size(
    bytes: &SecretBytes,
    maximum: usize,
    field: ManualSigningAssetField,
) -> Result<(), ManualSigningAssetError> {
    if bytes.is_empty() {
        return Err(ManualSigningAssetError::InvalidInput {
            field,
            reason: ManualSigningAssetInputError::Empty,
        });
    }
    if bytes.len() > maximum {
        return Err(ManualSigningAssetError::InvalidInput {
            field,
            reason: ManualSigningAssetInputError::TooLarge,
        });
    }
    Ok(())
}

fn is_exact_der_sequence(bytes: &[u8]) -> bool {
    // OpenSSL's DER constructors accept one valid object prefix and ignore any
    // trailing bytes, so validate the complete top-level encoding separately.
    let Some((&0x30, remainder)) = bytes.split_first() else {
        return false;
    };
    let Some((&length_octet, remainder)) = remainder.split_first() else {
        return false;
    };
    let (header_length, content_length) = if length_octet & 0x80 == 0 {
        (2_usize, usize::from(length_octet))
    } else {
        let length_bytes = usize::from(length_octet & 0x7f);
        if length_bytes == 0
            || length_bytes > std::mem::size_of::<usize>()
            || remainder.len() < length_bytes
        {
            return false;
        }
        let encoded_length = &remainder[..length_bytes];
        if encoded_length[0] == 0 {
            return false;
        }
        let Some(content_length) = encoded_length.iter().try_fold(0_usize, |length, byte| {
            length
                .checked_mul(256)
                .and_then(|length| length.checked_add(usize::from(*byte)))
        }) else {
            return false;
        };
        if content_length < 128 {
            return false;
        }
        (2 + length_bytes, content_length)
    };
    header_length
        .checked_add(content_length)
        .is_some_and(|encoded_length| encoded_length == bytes.len())
}

fn uppercase_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let mut output = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        output.push(char::from(HEX[usize::from(byte >> 4)]));
        output.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    output
}

#[cfg(test)]
mod tests {
    use std::time::{Duration, UNIX_EPOCH};

    use openssl::{
        asn1::{Asn1Integer, Asn1Time},
        bn::BigNum,
        ec::{EcGroup, EcKey},
        pkey::{PKey, Private},
        x509::{
            X509Builder, X509NameBuilder,
            extension::{BasicConstraints, ExtendedKeyUsage, KeyUsage},
        },
    };
    use plist::{Dictionary, Value as PlistValue};

    use super::*;

    const TEAM_ID: &str = "TESTTEAM01";
    const TEST_NOW_UNIX_SECONDS: u64 = 1_900_000_000;
    const PASSWORD: &str = "fixture-password";
    const DEVICE_UDID: &str = "00008110-001234567890801E";

    struct Fixture {
        root_pem: Vec<u8>,
        root_fingerprint: String,
        pkcs12: Vec<u8>,
        profile_cms: Vec<u8>,
        certificate_fingerprint: String,
        signing_certificate: X509,
    }

    #[test]
    fn validates_synthetic_assets_and_returns_the_exact_owned_inputs() {
        let fixture = fixture(false, LeafUsage::CodeSigning);
        let result = validate_fixture(
            &fixture,
            fixture.pkcs12.clone(),
            PASSWORD,
            fixture.profile_cms.clone(),
        );
        let (validated, input) = result.expect("synthetic signing assets should validate");

        assert_eq!(validated.certificate.team.id(), TEAM_ID);
        assert_eq!(
            validated.certificate.sha256_fingerprint,
            fixture.certificate_fingerprint
        );
        assert_eq!(validated.profile.team.id(), TEAM_ID);
        assert_eq!(
            validated.profile.uuid,
            "12345678-1234-1234-1234-123456789ABC"
        );

        let (pkcs12, password, profile) = input.into_parts();
        assert_eq!(pkcs12.expose_secret_bytes(), fixture.pkcs12);
        assert_eq!(password.expose_secret_bytes(), PASSWORD.as_bytes());
        assert_eq!(profile.expose_secret_bytes(), fixture.profile_cms);
    }

    #[test]
    fn split_identity_and_multiple_profile_validation_retains_each_secret_once() {
        let fixture = fixture(false, LeafUsage::CodeSigning);
        let anchors = [TrustAnchor {
            pem: &fixture.root_pem,
            sha256: &fixture.root_fingerprint,
        }];
        let policy = SigningAssetPolicy {
            trust_anchors: &anchors,
            accepted_common_name_prefixes: &[APPLE_DEVELOPMENT_PREFIX, IPHONE_DEVELOPER_PREFIX],
            now_unix_seconds: TEST_NOW_UNIX_SECONDS,
        };
        let identity = ManualSigningIdentityInput::new(
            SecretBytes::new(fixture.pkcs12.clone()),
            SecretBytes::new(PASSWORD.as_bytes().to_vec()),
        )
        .expect("bounded identity");
        let certificate = validate_manual_signing_identity_with_policy(
            &identity.certificate_pkcs12,
            &identity.certificate_password,
            &policy,
        )
        .expect("identity validates once");

        let first = SecretBytes::new(fixture.profile_cms.clone());
        let second = SecretBytes::new(fixture.profile_cms.clone());
        let first_metadata =
            validate_manual_signing_profile_with_policy(&first, &certificate, &policy)
                .expect("first profile");
        let second_metadata =
            validate_manual_signing_profile_with_policy(&second, &certificate, &policy)
                .expect("second profile");
        assert_eq!(first_metadata, second_metadata);
        assert_eq!(first.expose_secret_bytes(), fixture.profile_cms);
        assert_eq!(second.expose_secret_bytes(), fixture.profile_cms);

        let (pkcs12, password) = identity.into_parts();
        assert_eq!(pkcs12.expose_secret_bytes(), fixture.pkcs12);
        assert_eq!(password.expose_secret_bytes(), PASSWORD.as_bytes());

        let mut wrong_team = certificate.clone();
        wrong_team.team = DevelopmentTeam::new("OTHERTEAM1", None).expect("other team");
        assert_eq!(
            validate_manual_signing_profile_with_policy(&first, &wrong_team, &policy)
                .expect_err("wrong team"),
            ManualSigningAssetError::ProvisioningProfileTeamMismatch
        );
        let mut wrong_certificate = certificate.clone();
        wrong_certificate.sha256_fingerprint = "F".repeat(64);
        assert_eq!(
            validate_manual_signing_profile_with_policy(&first, &wrong_certificate, &policy)
                .expect_err("wrong certificate"),
            ManualSigningAssetError::ProvisioningProfileCertificateMismatch
        );

        let expired = fixture_with_profile_window(
            false,
            LeafUsage::CodeSigning,
            TEST_NOW_UNIX_SECONDS - 3_600,
            TEST_NOW_UNIX_SECONDS,
        );
        let expired_anchors = [TrustAnchor {
            pem: &expired.root_pem,
            sha256: &expired.root_fingerprint,
        }];
        let expired_policy = SigningAssetPolicy {
            trust_anchors: &expired_anchors,
            accepted_common_name_prefixes: &[APPLE_DEVELOPMENT_PREFIX, IPHONE_DEVELOPER_PREFIX],
            now_unix_seconds: TEST_NOW_UNIX_SECONDS,
        };
        let expired_certificate = validate_manual_signing_identity_with_policy(
            &SecretBytes::new(expired.pkcs12.clone()),
            &SecretBytes::new(PASSWORD.as_bytes().to_vec()),
            &expired_policy,
        )
        .expect("expired fixture identity remains valid");
        let expired_error = validate_manual_signing_profile_with_policy(
            &SecretBytes::new(expired.profile_cms),
            &expired_certificate,
            &expired_policy,
        )
        .expect_err("expired profile");
        assert_eq!(
            expired_error,
            ManualSigningAssetError::ProvisioningProfileExpired
        );
        let malformed = validate_manual_signing_profile_with_policy(
            &SecretBytes::new(b"canary-profile".to_vec()),
            &certificate,
            &policy,
        )
        .expect_err("malformed profile");
        assert_eq!(
            malformed,
            ManualSigningAssetError::ProvisioningProfileCmsMalformed
        );
        assert!(!malformed.to_string().contains("canary"));
    }

    #[test]
    fn rejects_wrong_pkcs12_password_without_secret_diagnostics() {
        let fixture = fixture(false, LeafUsage::CodeSigning);
        let error = validation_error(validate_fixture(
            &fixture,
            fixture.pkcs12.clone(),
            "wrong-password",
            fixture.profile_cms.clone(),
        ));

        assert_eq!(error, ManualSigningAssetError::Pkcs12Decrypt);
        assert!(!error.to_string().contains("wrong-password"));
    }

    #[test]
    fn rejects_certificate_and_private_key_mismatch() {
        let fixture = fixture(false, LeafUsage::CodeSigning);
        let error = validate_private_key_match(&fixture.signing_certificate, &generate_key())
            .expect_err("unrelated private key should be rejected");

        assert_eq!(error, ManualSigningAssetError::PrivateKeyMismatch);
    }

    #[test]
    fn rejects_expired_certificate_before_profile_use() {
        let fixture = fixture(true, LeafUsage::CodeSigning);
        let error = validation_error(validate_fixture(
            &fixture,
            fixture.pkcs12.clone(),
            PASSWORD,
            fixture.profile_cms.clone(),
        ));

        assert_eq!(error, ManualSigningAssetError::CertificateExpired);
    }

    #[test]
    fn profile_validity_boundaries_are_enforced_after_cms_verification() {
        let future = fixture_with_profile_window(
            false,
            LeafUsage::CodeSigning,
            TEST_NOW_UNIX_SECONDS + 1,
            TEST_NOW_UNIX_SECONDS + 3_600,
        );
        assert_eq!(
            validation_error(validate_fixture(
                &future,
                future.pkcs12.clone(),
                PASSWORD,
                future.profile_cms.clone(),
            )),
            ManualSigningAssetError::ProvisioningProfileNotYetValid
        );

        let expired = fixture_with_profile_window(
            false,
            LeafUsage::CodeSigning,
            TEST_NOW_UNIX_SECONDS - 3_600,
            TEST_NOW_UNIX_SECONDS,
        );
        assert_eq!(
            validation_error(validate_fixture(
                &expired,
                expired.pkcs12.clone(),
                PASSWORD,
                expired.profile_cms.clone(),
            )),
            ManualSigningAssetError::ProvisioningProfileExpired
        );

        let boundary = fixture_with_profile_window(
            false,
            LeafUsage::CodeSigning,
            TEST_NOW_UNIX_SECONDS,
            TEST_NOW_UNIX_SECONDS + 3_600,
        );
        validate_fixture(
            &boundary,
            boundary.pkcs12.clone(),
            PASSWORD,
            boundary.profile_cms.clone(),
        )
        .expect("profile created at validation time should be valid");
    }

    #[test]
    fn rejects_certificate_without_code_signing_usage() {
        let fixture = fixture(false, LeafUsage::EmailProtection);
        let error = validation_error(validate_fixture(
            &fixture,
            fixture.pkcs12.clone(),
            PASSWORD,
            fixture.profile_cms.clone(),
        ));

        assert_eq!(error, ManualSigningAssetError::CertificateUntrusted);
    }

    #[test]
    fn rejects_tampered_cms_signed_content() {
        let fixture = fixture(false, LeafUsage::CodeSigning);
        let mut tampered = fixture.profile_cms.clone();
        let marker = b"RustFerry Development";
        let marker_offset = tampered
            .windows(marker.len())
            .position(|window| window == marker)
            .expect("CMS fixture should contain its attached plist content");
        tampered[marker_offset] ^= 1;

        let error = validation_error(validate_fixture(
            &fixture,
            fixture.pkcs12.clone(),
            PASSWORD,
            tampered,
        ));
        assert_eq!(error, ManualSigningAssetError::ProvisioningProfileSignature);
    }

    #[test]
    fn rejects_unvalidated_bytes_appended_to_der_inputs() {
        let fixture = fixture(false, LeafUsage::CodeSigning);
        let mut pkcs12 = fixture.pkcs12.clone();
        pkcs12.push(0);
        let error = validation_error(validate_fixture(
            &fixture,
            pkcs12,
            PASSWORD,
            fixture.profile_cms.clone(),
        ));
        assert_eq!(error, ManualSigningAssetError::Pkcs12Malformed);

        let mut profile_cms = fixture.profile_cms.clone();
        profile_cms.push(0);
        let error = validation_error(validate_fixture(
            &fixture,
            fixture.pkcs12.clone(),
            PASSWORD,
            profile_cms,
        ));
        assert_eq!(
            error,
            ManualSigningAssetError::ProvisioningProfileCmsMalformed
        );
    }

    #[test]
    fn embedded_apple_roots_match_all_runtime_fingerprint_constants() {
        assert_eq!(
            PRODUCTION_TRUST_ANCHORS.map(|anchor| anchor.sha256),
            [
                APPLE_ROOT_CA_SHA256,
                APPLE_ROOT_CA_G2_SHA256,
                APPLE_ROOT_CA_G3_SHA256,
            ]
        );
        for anchor in PRODUCTION_TRUST_ANCHORS {
            let certificate = load_trust_anchor(anchor)
                .expect("embedded Apple root should match its pinned fingerprint");
            let fingerprint = certificate
                .digest(MessageDigest::sha256())
                .expect("embedded Apple root should be hashable");
            assert_eq!(uppercase_hex(fingerprint.as_ref()), anchor.sha256);
        }

        assert!(matches!(
            load_trust_anchor(TrustAnchor {
                pem: APPLE_ROOT_CA_PEM,
                sha256: APPLE_ROOT_CA_G2_SHA256,
            }),
            Err(ManualSigningAssetError::CryptoUnavailable)
        ));
    }

    fn validation_error(
        result: Result<
            (ValidatedManualSigningAssets, ManualSigningAssetsInput),
            ManualSigningAssetError,
        >,
    ) -> ManualSigningAssetError {
        match result {
            Ok(_) => panic!("invalid synthetic assets unexpectedly validated"),
            Err(error) => error,
        }
    }

    fn validate_fixture(
        fixture: &Fixture,
        pkcs12: Vec<u8>,
        password: &str,
        profile_cms: Vec<u8>,
    ) -> Result<(ValidatedManualSigningAssets, ManualSigningAssetsInput), ManualSigningAssetError>
    {
        let anchors = [TrustAnchor {
            pem: &fixture.root_pem,
            sha256: &fixture.root_fingerprint,
        }];
        let prefixes = [APPLE_DEVELOPMENT_PREFIX, IPHONE_DEVELOPER_PREFIX];
        let input = ManualSigningAssetsInput::new(
            SecretBytes::new(pkcs12),
            SecretBytes::new(password.as_bytes().to_vec()),
            SecretBytes::new(profile_cms),
        )?;
        validate_manual_signing_assets_with_policy(
            input,
            &SigningAssetPolicy {
                trust_anchors: &anchors,
                accepted_common_name_prefixes: &prefixes,
                now_unix_seconds: TEST_NOW_UNIX_SECONDS,
            },
        )
    }

    #[derive(Clone, Copy)]
    enum LeafUsage {
        CodeSigning,
        EmailProtection,
    }

    fn fixture(expired: bool, leaf_usage: LeafUsage) -> Fixture {
        fixture_with_profile_window(
            expired,
            leaf_usage,
            TEST_NOW_UNIX_SECONDS - 3_600,
            TEST_NOW_UNIX_SECONDS + 3_600,
        )
    }

    fn fixture_with_profile_window(
        expired: bool,
        leaf_usage: LeafUsage,
        profile_created_at: u64,
        profile_expires_at: u64,
    ) -> Fixture {
        let root_key = generate_key();
        let root = build_root(&root_key);
        let signing_key = generate_key();
        let signing_certificate = build_leaf(
            &signing_key,
            &root,
            &root_key,
            "Apple Development: RustFerry Fixture",
            leaf_usage,
            expired,
            2,
        );
        let profile_signer_key = generate_key();
        let profile_signer = build_leaf(
            &profile_signer_key,
            &root,
            &root_key,
            "RustFerry Profile Signer",
            LeafUsage::EmailProtection,
            false,
            3,
        );

        let certificate_der = signing_certificate
            .to_der()
            .expect("fixture certificate should serialize");
        let certificate_fingerprint = uppercase_hex(
            signing_certificate
                .digest(MessageDigest::sha256())
                .expect("fixture certificate should be hashable")
                .as_ref(),
        );
        let profile_plist = profile_plist(&certificate_der, profile_created_at, profile_expires_at);
        let profile_cms = CmsContentInfo::sign(
            Some(&profile_signer),
            Some(&profile_signer_key),
            None,
            Some(&profile_plist),
            CMSOptions::BINARY,
        )
        .expect("fixture profile should sign")
        .to_der()
        .expect("fixture CMS should serialize");
        let pkcs12_bytes = pkcs12(&signing_key, &signing_certificate);
        let root_fingerprint = uppercase_hex(
            root.digest(MessageDigest::sha256())
                .expect("fixture root should be hashable")
                .as_ref(),
        );

        Fixture {
            root_pem: root.to_pem().expect("fixture root should serialize"),
            root_fingerprint,
            pkcs12: pkcs12_bytes,
            profile_cms,
            certificate_fingerprint,
            signing_certificate,
        }
    }

    fn generate_key() -> PKey<Private> {
        let group =
            EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).expect("fixture curve should exist");
        let key = EcKey::generate(&group).expect("fixture key should generate");
        PKey::from_ec_key(key).expect("fixture key should convert")
    }

    fn build_root(key: &PKey<Private>) -> X509 {
        let mut name = X509NameBuilder::new().expect("fixture name builder should initialize");
        name.append_entry_by_nid(Nid::COMMONNAME, "RustFerry Test Root")
            .expect("fixture root name should be valid");
        let name = name.build();

        let mut builder = certificate_builder(1, key, &name, &name, false);
        builder
            .append_extension(
                BasicConstraints::new()
                    .critical()
                    .ca()
                    .build()
                    .expect("root constraints should build"),
            )
            .expect("root constraints should append");
        builder
            .append_extension(
                KeyUsage::new()
                    .critical()
                    .key_cert_sign()
                    .crl_sign()
                    .build()
                    .expect("root key usage should build"),
            )
            .expect("root key usage should append");
        builder
            .sign(key, MessageDigest::sha256())
            .expect("fixture root should sign");
        builder.build()
    }

    #[allow(clippy::too_many_arguments)]
    fn build_leaf(
        key: &PKey<Private>,
        issuer: &X509,
        issuer_key: &PKey<Private>,
        common_name: &str,
        usage: LeafUsage,
        expired: bool,
        serial: u32,
    ) -> X509 {
        let mut name = X509NameBuilder::new().expect("fixture name builder should initialize");
        name.append_entry_by_nid(Nid::COMMONNAME, common_name)
            .expect("fixture common name should be valid");
        name.append_entry_by_nid(Nid::ORGANIZATIONALUNITNAME, TEAM_ID)
            .expect("fixture team should be valid");
        let name = name.build();

        let mut builder = certificate_builder(serial, key, &name, issuer.subject_name(), expired);
        builder
            .append_extension(
                BasicConstraints::new()
                    .critical()
                    .build()
                    .expect("leaf constraints should build"),
            )
            .expect("leaf constraints should append");
        builder
            .append_extension(
                KeyUsage::new()
                    .critical()
                    .digital_signature()
                    .build()
                    .expect("leaf key usage should build"),
            )
            .expect("leaf key usage should append");
        let mut extended_usage = ExtendedKeyUsage::new();
        match usage {
            LeafUsage::CodeSigning => {
                extended_usage.code_signing();
            }
            LeafUsage::EmailProtection => {
                extended_usage.email_protection();
            }
        }
        builder
            .append_extension(
                extended_usage
                    .critical()
                    .build()
                    .expect("leaf extended key usage should build"),
            )
            .expect("leaf extended key usage should append");
        builder
            .sign(issuer_key, MessageDigest::sha256())
            .expect("fixture leaf should sign");
        builder.build()
    }

    fn certificate_builder(
        serial: u32,
        key: &PKey<Private>,
        subject: &openssl::x509::X509NameRef,
        issuer: &openssl::x509::X509NameRef,
        expired: bool,
    ) -> X509Builder {
        let mut builder = X509::builder().expect("fixture certificate builder should initialize");
        builder
            .set_version(2)
            .expect("fixture certificate version should set");
        let serial_number = BigNum::from_u32(serial).expect("fixture serial should build");
        let serial_number =
            Asn1Integer::from_bn(&serial_number).expect("fixture serial should convert");
        builder
            .set_serial_number(&serial_number)
            .expect("fixture serial should set");
        builder
            .set_subject_name(subject)
            .expect("fixture subject should set");
        builder
            .set_issuer_name(issuer)
            .expect("fixture issuer should set");
        builder
            .set_pubkey(key)
            .expect("fixture public key should set");
        let not_before = Asn1Time::from_unix(
            (TEST_NOW_UNIX_SECONDS - 86_400)
                .try_into()
                .expect("fixture time should fit"),
        )
        .expect("fixture not-before should build");
        let not_after_seconds = if expired {
            TEST_NOW_UNIX_SECONDS - 1
        } else {
            TEST_NOW_UNIX_SECONDS + 31_536_000
        };
        let not_after = Asn1Time::from_unix(
            not_after_seconds
                .try_into()
                .expect("fixture time should fit"),
        )
        .expect("fixture not-after should build");
        builder
            .set_not_before(&not_before)
            .expect("fixture not-before should set");
        builder
            .set_not_after(&not_after)
            .expect("fixture not-after should set");
        builder
    }

    fn pkcs12(key: &PKey<Private>, certificate: &X509) -> Vec<u8> {
        let mut builder = Pkcs12::builder();
        builder
            .name("RustFerry Fixture")
            .pkey(key)
            .cert(certificate);
        builder
            .build2(PASSWORD)
            .expect("fixture PKCS#12 should build")
            .to_der()
            .expect("fixture PKCS#12 should serialize")
    }

    fn profile_plist(
        certificate_der: &[u8],
        profile_created_at: u64,
        profile_expires_at: u64,
    ) -> Vec<u8> {
        let mut entitlements = Dictionary::new();
        entitlements.insert(
            "application-identifier".to_owned(),
            PlistValue::String(format!("{TEAM_ID}.com.example.rustferry")),
        );
        entitlements.insert(
            "com.apple.developer.team-identifier".to_owned(),
            PlistValue::String(TEAM_ID.to_owned()),
        );
        entitlements.insert("get-task-allow".to_owned(), PlistValue::Boolean(true));

        let mut profile = Dictionary::new();
        profile.insert(
            "UUID".to_owned(),
            PlistValue::String("12345678-1234-1234-1234-123456789ABC".to_owned()),
        );
        profile.insert(
            "Name".to_owned(),
            PlistValue::String("RustFerry Development".to_owned()),
        );
        profile.insert(
            "TeamIdentifier".to_owned(),
            PlistValue::Array(vec![PlistValue::String(TEAM_ID.to_owned())]),
        );
        profile.insert(
            "TeamName".to_owned(),
            PlistValue::String("RustFerry Fixture Team".to_owned()),
        );
        profile.insert(
            "CreationDate".to_owned(),
            PlistValue::Date((UNIX_EPOCH + Duration::from_secs(profile_created_at)).into()),
        );
        profile.insert(
            "ExpirationDate".to_owned(),
            PlistValue::Date((UNIX_EPOCH + Duration::from_secs(profile_expires_at)).into()),
        );
        profile.insert(
            "Platform".to_owned(),
            PlistValue::Array(vec![PlistValue::String("iOS".to_owned())]),
        );
        profile.insert(
            "ProvisionedDevices".to_owned(),
            PlistValue::Array(vec![PlistValue::String(DEVICE_UDID.to_owned())]),
        );
        profile.insert(
            "DeveloperCertificates".to_owned(),
            PlistValue::Array(vec![PlistValue::Data(certificate_der.to_vec())]),
        );
        profile.insert(
            "Entitlements".to_owned(),
            PlistValue::Dictionary(entitlements),
        );

        let mut plist = Vec::new();
        PlistValue::Dictionary(profile)
            .to_writer_xml(&mut plist)
            .expect("fixture profile should serialize");
        plist
    }
}