rustferry-remote 0.1.0

Versioned remote-build contracts and provider interfaces 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
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
use std::{
    collections::{BTreeMap, BTreeSet},
    error::Error,
    fmt,
};

use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::secret::SecretReference;

const MAX_LABEL_BYTES: usize = 128;
const MAX_ENTITLEMENT_KEY_BYTES: usize = 255;
const MAX_ENTITLEMENT_STRING_BYTES: usize = 16 * 1024;
const MAX_ENTITLEMENT_COLLECTION_ITEMS: usize = 1_024;
const MAX_ENTITLEMENT_DEPTH: usize = 16;
const SIGNING_TARGET_GRAPH_SHA256_DOMAIN: &[u8] = b"rustferry.signing-target-graph.sha256.v1\0";

/// Supported Apple signing mode.
#[derive(
    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum SigningMode {
    /// Compile and inspect an iPhoneOS artifact without making it installable.
    UnsignedCompileOnly,
    /// Normal Apple Development signing.
    Development,
    /// User-supplied development identity and profiles.
    ManualDevelopment,
    /// Persistent-Mac Personal Team flow configured interactively in Xcode.
    PersonalTeam,
    /// Future registered-device ad-hoc distribution.
    AdHoc,
    /// Future App Store distribution.
    AppStore,
}

impl SigningMode {
    /// Return whether this mode produces a signed artifact.
    pub fn is_signed(self) -> bool {
        self != Self::UnsignedCompileOnly
    }

    /// Return whether this mode requires one registered device.
    pub fn requires_device(self) -> bool {
        matches!(
            self,
            Self::Development | Self::ManualDevelopment | Self::PersonalTeam | Self::AdHoc
        )
    }

    fn requires_identity_reference(self) -> bool {
        matches!(
            self,
            Self::Development | Self::ManualDevelopment | Self::AdHoc | Self::AppStore
        )
    }
}

/// Fine-grained signing progress; never collapse this into one success boolean.
#[derive(
    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(rename_all = "snake_case")]
pub enum SigningStatus {
    /// No certificate or provisioning validation has completed.
    Unsigned,
    /// Certificate type, expiry, team, and private-key match validated.
    CertificateValidated,
    /// All required provisioning profiles validated.
    ProfileValidated,
    /// Frameworks, libraries, and extensions signed inside-out.
    NestedCodeSigned,
    /// Main application signed after nested code.
    ApplicationSigned,
    /// Development IPA exported.
    IpaExported,
    /// Independent artifact validation completed.
    ArtifactValidated,
    /// A validation or signing stage failed.
    Invalid,
}

impl SigningStatus {
    /// Advance one exact lifecycle step.
    ///
    /// # Errors
    ///
    /// Returns [`SigningValidationError::InvalidStatusTransition`] when a stage
    /// is skipped, repeated, or resumed after invalidation.
    pub fn advance(self, next: Self) -> Result<Self, SigningValidationError> {
        let valid = matches!(
            (self, next),
            (Self::Unsigned, Self::CertificateValidated)
                | (Self::CertificateValidated, Self::ProfileValidated)
                | (Self::ProfileValidated, Self::NestedCodeSigned)
                | (Self::NestedCodeSigned, Self::ApplicationSigned)
                | (Self::ApplicationSigned, Self::IpaExported)
                | (Self::IpaExported, Self::ArtifactValidated)
        );
        if valid || next == Self::Invalid {
            Ok(next)
        } else {
            Err(SigningValidationError::InvalidStatusTransition {
                from: self,
                to: next,
            })
        }
    }
}

/// Serializable signing inputs containing public identity metadata and opaque
/// references only, never secret bytes.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SigningReference {
    /// Expected public certificate paired with the opaque private-key reference.
    pub identity: SigningIdentity,
    /// Opaque reference to its password or passphrase, when required.
    pub password: Option<SecretReference>,
}

/// Validated Apple application bundle identifier.
#[derive(Clone, Debug, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize)]
#[schemars(transparent)]
pub struct BundleIdentifier(String);

impl BundleIdentifier {
    /// Validate and construct an explicit bundle identifier.
    ///
    /// # Errors
    ///
    /// Returns [`SigningValidationError::InvalidBundleIdentifier`] for a
    /// wildcard, malformed, or oversized value.
    pub fn new(value: impl Into<String>) -> Result<Self, SigningValidationError> {
        let value = value.into();
        if value.len() > 255
            || value.split('.').count() < 2
            || value.split('.').any(|segment| {
                segment.is_empty()
                    || !segment
                        .bytes()
                        .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
                    || !segment.as_bytes()[0].is_ascii_alphanumeric()
                    || !segment.as_bytes()[segment.len() - 1].is_ascii_alphanumeric()
            })
        {
            return Err(SigningValidationError::InvalidBundleIdentifier);
        }
        Ok(Self(value))
    }

    /// Return the validated identifier.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl<'de> Deserialize<'de> for BundleIdentifier {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

/// Apple development team selected for signing.
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
pub struct DevelopmentTeam {
    id: String,
    display_name: Option<String>,
}

impl DevelopmentTeam {
    /// Construct a validated ten-character Apple Team ID.
    ///
    /// # Errors
    ///
    /// Returns [`SigningValidationError::InvalidTeamIdentifier`] for malformed
    /// IDs or unsafe display names.
    pub fn new(
        id: impl Into<String>,
        display_name: Option<String>,
    ) -> Result<Self, SigningValidationError> {
        let id = id.into();
        if id.len() != 10
            || !id
                .bytes()
                .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit())
        {
            return Err(SigningValidationError::InvalidTeamIdentifier);
        }
        if display_name
            .as_deref()
            .is_some_and(|name| !is_safe_label(name))
        {
            return Err(SigningValidationError::InvalidTeamIdentifier);
        }
        Ok(Self { id, display_name })
    }

    /// Return the Apple Team ID.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Return the optional public display name.
    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct UncheckedDevelopmentTeam {
    id: String,
    display_name: Option<String>,
}

impl<'de> Deserialize<'de> for DevelopmentTeam {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let unchecked = UncheckedDevelopmentTeam::deserialize(deserializer)?;
        Self::new(unchecked.id, unchecked.display_name).map_err(serde::de::Error::custom)
    }
}

/// Registered physical iPhone selected for a development artifact.
#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
pub struct DevicePlan {
    udid_sha256: String,
    display_name: Option<String>,
}

impl DevicePlan {
    /// Validate and hash an Apple device identifier without retaining it.
    ///
    /// # Errors
    ///
    /// Returns [`SigningValidationError::InvalidDeviceIdentifier`] for unsafe
    /// identifiers or display names.
    pub fn new(
        udid: impl Into<String>,
        display_name: Option<String>,
    ) -> Result<Self, SigningValidationError> {
        let udid = udid.into();
        validate_raw_udid(&udid)?;
        Self::from_sha256(sha256_lowercase(udid.as_bytes()), display_name)
    }

    /// Construct a device plan from an existing lowercase SHA-256 digest.
    ///
    /// # Errors
    ///
    /// Returns [`SigningValidationError::InvalidDeviceIdentifier`] for a
    /// malformed digest or unsafe display name.
    pub fn from_sha256(
        udid_sha256: impl Into<String>,
        display_name: Option<String>,
    ) -> Result<Self, SigningValidationError> {
        let udid_sha256 = udid_sha256.into();
        if !is_lowercase_sha256(&udid_sha256)
            || display_name
                .as_deref()
                .is_some_and(|name| !is_safe_label(name))
        {
            return Err(SigningValidationError::InvalidDeviceIdentifier);
        }
        Ok(Self {
            udid_sha256,
            display_name,
        })
    }

    /// Return the lowercase SHA-256 of the selected device identifier.
    pub fn udid_sha256(&self) -> &str {
        &self.udid_sha256
    }

    /// Validate and compare a raw device identifier without retaining it.
    ///
    /// # Errors
    ///
    /// Returns [`SigningValidationError::InvalidDeviceIdentifier`] when the
    /// candidate is malformed.
    pub fn matches_udid(&self, udid: &str) -> Result<bool, SigningValidationError> {
        validate_raw_udid(udid)?;
        Ok(self.udid_sha256 == sha256_lowercase(udid.as_bytes()))
    }

    /// Return the optional public device name.
    pub fn display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct UncheckedDevicePlan {
    udid_sha256: String,
    display_name: Option<String>,
}

impl<'de> Deserialize<'de> for DevicePlan {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let unchecked = UncheckedDevicePlan::deserialize(deserializer)?;
        Self::from_sha256(unchecked.udid_sha256, unchecked.display_name)
            .map_err(serde::de::Error::custom)
    }
}

/// Development team expectation carried by a signing plan.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DevelopmentTeamPlan {
    /// Team that certificate, profile, application, and extensions must share.
    pub expected: DevelopmentTeam,
}

/// Short protocol name for a development-team expectation.
pub type TeamPlan = DevelopmentTeamPlan;

/// Opaque reference to private-key material held outside project configuration.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SigningPrivateKeyReference {
    /// Validated credential-store, workflow-secret, environment, or worker handle.
    pub reference: SecretReference,
}

/// Public certificate metadata used for validation and reporting.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SigningCertificate {
    /// Public certificate subject name.
    pub common_name: String,
    /// Uppercase SHA-256 fingerprint without separators.
    pub sha256_fingerprint: String,
    /// Team encoded by the signing certificate.
    pub team: DevelopmentTeam,
    /// Certificate expiration as a Unix timestamp.
    pub expires_at_unix_seconds: u64,
}

impl SigningCertificate {
    /// Validate public certificate metadata.
    ///
    /// # Errors
    ///
    /// Returns a typed validation error for an unsafe name or malformed
    /// fingerprint.
    pub fn validate(&self) -> Result<(), SigningValidationError> {
        if !is_safe_label(&self.common_name) {
            return Err(SigningValidationError::InvalidCertificateName);
        }
        validate_fingerprint(&self.sha256_fingerprint)
    }
}

/// Certificate metadata paired with an opaque private-key reference.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SigningIdentity {
    /// Public certificate metadata.
    pub certificate: SigningCertificate,
    /// Reference only; private-key bytes are never serializable.
    pub private_key: SigningPrivateKeyReference,
}

/// Provisioning profile category.
#[derive(
    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(rename_all = "kebab-case")]
pub enum ProvisioningProfileType {
    /// Registered-device development profile.
    Development,
    /// Registered-device ad-hoc distribution profile.
    AdHoc,
    /// App Store distribution profile.
    AppStore,
}

/// Supported profile platform.
#[derive(
    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(rename_all = "snake_case")]
pub enum ProvisioningPlatform {
    /// Physical iPhone/iPad platform.
    Ios,
}

/// Validated entitlement dictionary for one signing target.
#[derive(Clone, Debug, Default, Eq, JsonSchema, PartialEq, Serialize)]
#[schemars(transparent)]
pub struct EntitlementSet(BTreeMap<String, Value>);

impl EntitlementSet {
    /// Validate entitlement keys, collection bounds, depth, and plist-compatible values.
    ///
    /// # Errors
    ///
    /// Returns a typed entitlement validation error without echoing its value.
    pub fn new(values: BTreeMap<String, Value>) -> Result<Self, SigningValidationError> {
        if values.len() > MAX_ENTITLEMENT_COLLECTION_ITEMS {
            return Err(SigningValidationError::InvalidEntitlementValue {
                key: None,
                reason: EntitlementValueError::CollectionTooLarge,
            });
        }
        for (key, value) in &values {
            validate_entitlement_key(key)?;
            validate_entitlement_value(Some(key), value, 0)?;
        }
        Ok(Self(values))
    }

    /// Return the validated entitlement mapping.
    pub fn values(&self) -> &BTreeMap<String, Value> {
        &self.0
    }

    /// Return one entitlement value.
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.0.get(key)
    }

    /// Return whether no entitlements are requested.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl<'de> Deserialize<'de> for EntitlementSet {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let values = BTreeMap::<String, Value>::deserialize(deserializer)?;
        Self::new(values).map_err(serde::de::Error::custom)
    }
}

/// Public decoded provisioning-profile metadata; raw profile bytes are excluded.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProvisioningProfile {
    /// Profile UUID.
    pub uuid: String,
    /// Public profile name.
    pub name: String,
    /// Development team embedded in the profile.
    pub team: DevelopmentTeam,
    /// Full `application-identifier` entitlement.
    pub application_identifier: String,
    /// Explicit or wildcard bundle pattern.
    pub bundle_identifier_pattern: String,
    /// Whether the profile uses a wildcard App ID.
    pub wildcard: bool,
    /// Creation time as a Unix timestamp.
    pub created_at_unix_seconds: u64,
    /// Expiration time as a Unix timestamp.
    pub expires_at_unix_seconds: u64,
    /// Lowercase SHA-256 digests of registered device identifiers, empty for
    /// App Store profiles.
    pub device_udid_sha256s: Vec<String>,
    /// Profile entitlements.
    pub entitlements: EntitlementSet,
    /// Profile platform allowlist.
    pub platforms: BTreeSet<ProvisioningPlatform>,
    /// Profile category.
    pub profile_type: ProvisioningProfileType,
    /// Public certificate SHA-256 fingerprints.
    pub certificate_fingerprints: Vec<String>,
}

impl ProvisioningProfile {
    /// Validate public profile metadata without reading a profile or key.
    ///
    /// # Errors
    ///
    /// Returns the first typed metadata failure.
    pub fn validate_metadata(&self) -> Result<(), SigningValidationError> {
        if !is_profile_identifier(&self.uuid) {
            return Err(SigningValidationError::InvalidProvisioningProfileIdentifier);
        }
        if !is_safe_label(&self.name) {
            return Err(SigningValidationError::InvalidProvisioningProfileName);
        }
        if self.created_at_unix_seconds > self.expires_at_unix_seconds {
            return Err(SigningValidationError::InvalidProvisioningProfileDates);
        }
        let bundle_pattern_valid = if self.wildcard {
            self.bundle_identifier_pattern == "*"
                || self
                    .bundle_identifier_pattern
                    .strip_suffix(".*")
                    .is_some_and(|prefix| BundleIdentifier::new(prefix).is_ok())
        } else {
            BundleIdentifier::new(self.bundle_identifier_pattern.clone()).is_ok()
        };
        if !bundle_pattern_valid {
            return Err(SigningValidationError::ProfileBundleIdentifierMismatch);
        }
        let expected_application_identifier =
            format!("{}.{}", self.team.id(), self.bundle_identifier_pattern);
        if self.application_identifier != expected_application_identifier {
            return Err(SigningValidationError::ApplicationIdentifierMismatch);
        }
        if !self.platforms.contains(&ProvisioningPlatform::Ios) {
            return Err(SigningValidationError::ProfilePlatformMismatch);
        }
        if self.certificate_fingerprints.is_empty() {
            return Err(SigningValidationError::ProfileCertificateMismatch);
        }
        for fingerprint in &self.certificate_fingerprints {
            validate_fingerprint(fingerprint)?;
        }
        let mut devices = BTreeSet::new();
        for udid_sha256 in &self.device_udid_sha256s {
            DevicePlan::from_sha256(udid_sha256.clone(), None)?;
            if !devices.insert(udid_sha256) {
                return Err(SigningValidationError::InvalidDeviceIdentifier);
            }
        }
        match self.profile_type {
            ProvisioningProfileType::Development | ProvisioningProfileType::AdHoc
                if self.device_udid_sha256s.is_empty() =>
            {
                return Err(SigningValidationError::DeviceNotProvisioned);
            }
            ProvisioningProfileType::AppStore if !self.device_udid_sha256s.is_empty() => {
                return Err(SigningValidationError::ProfileTypeMismatch);
            }
            ProvisioningProfileType::Development
            | ProvisioningProfileType::AdHoc
            | ProvisioningProfileType::AppStore => {}
        }
        Ok(())
    }

    /// Validate metadata and reject an expired profile at a caller-supplied time.
    ///
    /// # Errors
    ///
    /// Returns a typed time-validity error when the profile is not yet valid
    /// or has expired, or another typed metadata error.
    pub fn validate_metadata_at(
        &self,
        now_unix_seconds: u64,
    ) -> Result<(), SigningValidationError> {
        self.validate_metadata()?;
        if self.created_at_unix_seconds > now_unix_seconds {
            Err(SigningValidationError::ProfileNotYetValid)
        } else if self.expires_at_unix_seconds <= now_unix_seconds {
            Err(SigningValidationError::ProfileExpired)
        } else {
            Ok(())
        }
    }
}

fn validate_raw_udid(udid: &str) -> Result<(), SigningValidationError> {
    let valid = (20..=64).contains(&udid.len())
        && udid
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
        && !udid.starts_with('-')
        && !udid.ends_with('-');
    if valid {
        Ok(())
    } else {
        Err(SigningValidationError::InvalidDeviceIdentifier)
    }
}

fn is_lowercase_sha256(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn sha256_lowercase(bytes: &[u8]) -> String {
    hex::encode(Sha256::digest(bytes))
}

/// Kind of code object in the required inside-out signing order.
#[derive(
    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(rename_all = "snake_case")]
pub enum SigningTargetKind {
    /// Embedded dynamic library.
    DynamicLibrary,
    /// Embedded framework.
    Framework,
    /// Widget, Live Activity, or other application extension.
    Extension,
    /// Main application; always signed last.
    Application,
}

/// One public signing target.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SigningTarget {
    /// Stable target name used by per-target plans.
    pub name: String,
    /// Bundle identifier encoded into its signature.
    pub bundle_identifier: BundleIdentifier,
    /// Code-object category determining inside-out order.
    pub kind: SigningTargetKind,
}

/// SHA-256 of a canonical, order-independent full signing-target graph.
///
/// The hash input starts with a versioned domain separator and record count.
/// Every target is sorted by UTF-8 target name, bundle identifier, then kind;
/// kind, name, and bundle identifier are encoded as ASCII-length-prefixed byte
/// fields. The resulting lowercase digest binds every target kind without
/// relying on serialization formats or enum discriminants.
pub fn canonical_signing_target_graph_sha256(targets: &[SigningTarget]) -> String {
    let mut targets = targets.iter().collect::<Vec<_>>();
    targets.sort_unstable_by(|left, right| {
        left.name
            .as_bytes()
            .cmp(right.name.as_bytes())
            .then_with(|| {
                left.bundle_identifier
                    .as_str()
                    .as_bytes()
                    .cmp(right.bundle_identifier.as_str().as_bytes())
            })
            .then_with(|| {
                signing_target_kind_name(left.kind).cmp(signing_target_kind_name(right.kind))
            })
    });

    let mut digest = Sha256::new();
    digest.update(SIGNING_TARGET_GRAPH_SHA256_DOMAIN);
    update_canonical_length(&mut digest, targets.len());
    for target in targets {
        update_canonical_field(
            &mut digest,
            signing_target_kind_name(target.kind).as_bytes(),
        );
        update_canonical_field(&mut digest, target.name.as_bytes());
        update_canonical_field(&mut digest, target.bundle_identifier.as_str().as_bytes());
    }
    hex::encode(digest.finalize())
}

fn update_canonical_field(digest: &mut Sha256, value: &[u8]) {
    update_canonical_length(digest, value.len());
    digest.update(value);
}

fn update_canonical_length(digest: &mut Sha256, length: usize) {
    digest.update(length.to_string().as_bytes());
    digest.update(b":");
}

const fn signing_target_kind_name(kind: SigningTargetKind) -> &'static str {
    match kind {
        SigningTargetKind::DynamicLibrary => "dynamic_library",
        SigningTargetKind::Framework => "framework",
        SigningTargetKind::Extension => "extension",
        SigningTargetKind::Application => "application",
    }
}

/// Per-target provisioning-profile selection.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProvisioningPlan {
    /// Target name from [`SigningPlan::targets`].
    pub target: String,
    /// Opaque profile reference; never raw `.mobileprovision` bytes.
    pub profile: SecretReference,
    /// Required profile category.
    pub profile_type: ProvisioningProfileType,
}

/// Per-target entitlement expectation.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct EntitlementPlan {
    /// Target name from [`SigningPlan::targets`].
    pub target: String,
    /// Entitlements that must remain enabled and match the profile.
    pub required: EntitlementSet,
}

/// Complete declarative physical-iPhone signing plan.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SigningPlan {
    /// Requested signing mode.
    pub mode: SigningMode,
    /// Public identity metadata plus opaque key/password references.
    pub signing: Option<SigningReference>,
    /// Expected team for all code and profiles.
    pub team: Option<DevelopmentTeamPlan>,
    /// Required registered device for development and ad-hoc artifacts.
    pub device: Option<DevicePlan>,
    /// All signable code objects.
    pub targets: Vec<SigningTarget>,
    /// Separate profile for each application and extension target.
    pub provisioning: Vec<ProvisioningPlan>,
    /// Per-target entitlement requirements.
    pub entitlements: Vec<EntitlementPlan>,
    /// Explicit opt-in to official Xcode profile updates.
    pub allow_provisioning_updates: bool,
}

impl SigningPlan {
    /// Validate plan structure without accessing any secret or external service.
    ///
    /// # Errors
    ///
    /// Returns all independent typed structural failures.
    pub fn validate(&self) -> Result<(), SigningValidationErrors> {
        let mut errors = Vec::new();

        if self.mode == SigningMode::UnsignedCompileOnly {
            if self.signing.is_some() || !self.provisioning.is_empty() {
                errors.push(SigningValidationError::SigningReferencesForbiddenForUnsigned);
            }
            if self.allow_provisioning_updates {
                errors.push(SigningValidationError::ProvisioningUpdatesForbiddenForUnsigned);
            }
        } else {
            if self.mode.requires_identity_reference() && self.signing.is_none() {
                errors.push(SigningValidationError::MissingSigningReference);
            }
            if let Some(signing) = &self.signing {
                if let Err(error) = signing.identity.certificate.validate() {
                    errors.push(error);
                }
                if self.team.as_ref().is_some_and(|team| {
                    team.expected.id() != signing.identity.certificate.team.id()
                }) {
                    errors.push(SigningValidationError::CertificateTeamMismatch);
                }
            }
            if self.mode == SigningMode::ManualDevelopment
                && self
                    .signing
                    .as_ref()
                    .is_some_and(|signing| signing.password.is_none())
            {
                errors.push(SigningValidationError::MissingSigningPasswordReference);
            }
            if self.team.is_none() {
                errors.push(SigningValidationError::MissingDevelopmentTeam);
            }
            if self.mode.requires_device() && self.device.is_none() {
                errors.push(SigningValidationError::MissingDevice);
            }
        }

        let mut target_names = BTreeSet::new();
        let mut bundle_identifiers = BTreeSet::new();
        let mut application_targets = 0;
        for target in &self.targets {
            if !is_safe_identifier(&target.name) {
                errors.push(SigningValidationError::InvalidTargetName);
            }
            if !target_names.insert(target.name.as_str()) {
                errors.push(SigningValidationError::DuplicateTarget {
                    target: target.name.clone(),
                });
            }
            if !bundle_identifiers.insert(target.bundle_identifier.as_str()) {
                errors.push(SigningValidationError::DuplicateBundleIdentifier {
                    bundle_identifier: target.bundle_identifier.as_str().to_owned(),
                });
            }
            if target.kind == SigningTargetKind::Application {
                application_targets += 1;
            }
        }
        if application_targets == 0 {
            errors.push(SigningValidationError::MissingApplicationTarget);
        } else if application_targets > 1 {
            errors.push(SigningValidationError::MultipleApplicationTargets);
        }

        validate_per_target_plans(self, &target_names, &mut errors);

        if errors.is_empty() {
            Ok(())
        } else {
            Err(SigningValidationErrors { errors })
        }
    }

    /// Return targets in the required inside-out signing order.
    pub fn targets_in_signing_order(&self) -> Vec<&SigningTarget> {
        let mut targets: Vec<_> = self.targets.iter().collect();
        targets.sort_by_key(|target| target.kind);
        targets
    }
}

fn validate_per_target_plans(
    plan: &SigningPlan,
    target_names: &BTreeSet<&str>,
    errors: &mut Vec<SigningValidationError>,
) {
    let mut profile_targets = BTreeSet::new();
    for provisioning in &plan.provisioning {
        if !target_names.contains(provisioning.target.as_str()) {
            errors.push(SigningValidationError::UnknownProvisioningTarget {
                target: provisioning.target.clone(),
            });
        }
        if !profile_targets.insert(provisioning.target.as_str()) {
            errors.push(SigningValidationError::AmbiguousProvisioningProfile {
                target: provisioning.target.clone(),
            });
        }
        if expected_profile_type(plan.mode)
            .is_some_and(|expected| provisioning.profile_type != expected)
        {
            errors.push(SigningValidationError::ProfileTypeMismatch);
        }
    }

    let mut entitlement_targets = BTreeSet::new();
    for entitlements in &plan.entitlements {
        if !target_names.contains(entitlements.target.as_str()) {
            errors.push(SigningValidationError::UnknownEntitlementTarget {
                target: entitlements.target.clone(),
            });
        }
        if !entitlement_targets.insert(entitlements.target.as_str()) {
            errors.push(SigningValidationError::DuplicateEntitlementPlan {
                target: entitlements.target.clone(),
            });
        }
    }

    for target in &plan.targets {
        if !plan.mode.is_signed()
            || !matches!(
                target.kind,
                SigningTargetKind::Application | SigningTargetKind::Extension
            )
        {
            continue;
        }
        if !profile_targets.contains(target.name.as_str()) {
            errors.push(SigningValidationError::MissingProvisioningProfile {
                target: target.name.clone(),
            });
        }
        if !entitlement_targets.contains(target.name.as_str()) {
            errors.push(SigningValidationError::MissingEntitlementPlan {
                target: target.name.clone(),
            });
        }
    }
}

fn expected_profile_type(mode: SigningMode) -> Option<ProvisioningProfileType> {
    match mode {
        SigningMode::UnsignedCompileOnly => None,
        SigningMode::Development | SigningMode::ManualDevelopment | SigningMode::PersonalTeam => {
            Some(ProvisioningProfileType::Development)
        }
        SigningMode::AdHoc => Some(ProvisioningProfileType::AdHoc),
        SigningMode::AppStore => Some(ProvisioningProfileType::AppStore),
    }
}

/// Validation state for one independent signing concern.
#[derive(
    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(rename_all = "snake_case")]
pub enum ValidationStatus {
    /// Check has not run.
    NotChecked,
    /// Check completed and all invariants passed.
    Validated,
    /// Check completed and at least one invariant failed.
    Invalid,
    /// Check does not apply to this signing mode.
    NotApplicable,
}

/// Component tracked independently in a validation report.
#[derive(
    Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
)]
#[serde(rename_all = "snake_case")]
pub enum ValidationComponent {
    /// Public certificate metadata and private-key match.
    Certificate,
    /// Provisioning-profile selection and contents.
    Provisioning,
    /// Team compatibility across certificate, profile, and targets.
    Team,
    /// Registered-device compatibility.
    Device,
    /// Signed/profile/requested entitlement compatibility.
    Entitlements,
}

/// Detailed validation state and typed failures for one signing operation.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SigningValidationReport {
    /// Signing mode whose evidence this report validates.
    pub mode: SigningMode,
    /// Overall signing lifecycle stage.
    pub signing_status: SigningStatus,
    /// Certificate validation state.
    pub certificate: ValidationStatus,
    /// Provisioning validation state.
    pub provisioning: ValidationStatus,
    /// Team validation state.
    pub team: ValidationStatus,
    /// Device validation state.
    pub device: ValidationStatus,
    /// Entitlement validation state.
    pub entitlements: ValidationStatus,
    /// Typed secret-free failures.
    pub errors: Vec<SigningValidationError>,
}

impl SigningValidationReport {
    /// Create an empty report with mode-appropriate component states.
    pub fn new(mode: SigningMode) -> Self {
        let initial = if mode.is_signed() {
            ValidationStatus::NotChecked
        } else {
            ValidationStatus::NotApplicable
        };
        Self {
            mode,
            signing_status: SigningStatus::Unsigned,
            certificate: initial,
            provisioning: initial,
            team: initial,
            device: if mode.requires_device() {
                initial
            } else {
                ValidationStatus::NotApplicable
            },
            entitlements: initial,
            errors: Vec::new(),
        }
    }

    /// Mark one component validated.
    pub fn mark_validated(&mut self, component: ValidationComponent) {
        *self.component_mut(component) = ValidationStatus::Validated;
    }

    /// Record a typed failure and invalidate the overall signing status.
    pub fn record_error(&mut self, component: ValidationComponent, error: SigningValidationError) {
        *self.component_mut(component) = ValidationStatus::Invalid;
        self.signing_status = SigningStatus::Invalid;
        self.errors.push(error);
    }

    /// Advance the overall lifecycle by one stage.
    ///
    /// # Errors
    ///
    /// Returns a typed transition error when a stage is skipped.
    pub fn advance(&mut self, next: SigningStatus) -> Result<(), SigningValidationError> {
        self.signing_status = self.signing_status.advance(next)?;
        Ok(())
    }

    /// Return whether the report proves an independently validated artifact.
    pub fn artifact_is_validated(&self) -> bool {
        self.signing_status == SigningStatus::ArtifactValidated
            && self.errors.is_empty()
            && [
                self.certificate,
                self.provisioning,
                self.team,
                self.entitlements,
            ]
            .iter()
            .all(|status| *status == ValidationStatus::Validated)
            && if self.mode.requires_device() {
                self.device == ValidationStatus::Validated
            } else {
                self.device == ValidationStatus::NotApplicable
            }
    }

    fn component_mut(&mut self, component: ValidationComponent) -> &mut ValidationStatus {
        match component {
            ValidationComponent::Certificate => &mut self.certificate,
            ValidationComponent::Provisioning => &mut self.provisioning,
            ValidationComponent::Team => &mut self.team,
            ValidationComponent::Device => &mut self.device,
            ValidationComponent::Entitlements => &mut self.entitlements,
        }
    }
}

/// Collection of independent signing-plan validation failures.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
pub struct SigningValidationErrors {
    errors: Vec<SigningValidationError>,
}

impl SigningValidationErrors {
    /// Return all typed failures.
    pub fn errors(&self) -> &[SigningValidationError] {
        &self.errors
    }

    /// Consume the collection.
    pub fn into_errors(self) -> Vec<SigningValidationError> {
        self.errors
    }
}

impl fmt::Display for SigningValidationErrors {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "signing plan has {} validation error(s)",
            self.errors.len()
        )
    }
}

impl Error for SigningValidationErrors {}

/// Reason a signing plan, profile, entitlement, or validation stage failed.
#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case", tag = "code")]
pub enum SigningValidationError {
    /// Signed mode omitted the opaque identity reference.
    MissingSigningReference,
    /// Manual development mode omitted the encrypted identity password reference.
    MissingSigningPasswordReference,
    /// Signed mode omitted a development team.
    MissingDevelopmentTeam,
    /// Device-bound mode omitted a registered device.
    MissingDevice,
    /// Unsigned mode attempted to carry signing/profile references.
    SigningReferencesForbiddenForUnsigned,
    /// Unsigned mode enabled Xcode provisioning updates.
    ProvisioningUpdatesForbiddenForUnsigned,
    /// Apple Team ID or its public label was malformed.
    InvalidTeamIdentifier,
    /// Device identifier or its public label was malformed.
    InvalidDeviceIdentifier,
    /// Bundle identifier was malformed or contained a wildcard.
    InvalidBundleIdentifier,
    /// Target name was unsafe for protocol use.
    InvalidTargetName,
    /// Certificate public name was malformed.
    InvalidCertificateName,
    /// Certificate fingerprint was not a SHA-256 hex digest.
    InvalidCertificateFingerprint,
    /// Provisioning profile UUID was malformed.
    InvalidProvisioningProfileIdentifier,
    /// Provisioning profile public name was malformed.
    InvalidProvisioningProfileName,
    /// Provisioning profile creation/expiration ordering was invalid.
    InvalidProvisioningProfileDates,
    /// Entitlement key was empty, oversized, or malformed.
    InvalidEntitlementKey {
        /// Byte offset when available; rejected content is never echoed.
        index: Option<usize>,
    },
    /// Entitlement value cannot be represented safely as a bounded plist value.
    InvalidEntitlementValue {
        /// Public entitlement key, or none for the root collection.
        key: Option<String>,
        /// Structural reason; value content is never included.
        reason: EntitlementValueError,
    },
    /// No main application target was supplied.
    MissingApplicationTarget,
    /// More than one main application target was supplied.
    MultipleApplicationTargets,
    /// Target name appeared more than once.
    DuplicateTarget {
        /// Public target name.
        target: String,
    },
    /// Bundle identifier appeared on more than one target.
    DuplicateBundleIdentifier {
        /// Public bundle identifier.
        bundle_identifier: String,
    },
    /// Provisioning plan referred to an unknown target.
    UnknownProvisioningTarget {
        /// Public target name.
        target: String,
    },
    /// More than one profile matched or was assigned to a target.
    AmbiguousProvisioningProfile {
        /// Public target name.
        target: String,
    },
    /// Signed application or extension omitted a profile.
    MissingProvisioningProfile {
        /// Public target name.
        target: String,
    },
    /// Entitlement plan referred to an unknown target.
    UnknownEntitlementTarget {
        /// Public target name.
        target: String,
    },
    /// Target had multiple entitlement plans.
    DuplicateEntitlementPlan {
        /// Public target name.
        target: String,
    },
    /// Signed application or extension omitted entitlement expectations.
    MissingEntitlementPlan {
        /// Public target name.
        target: String,
    },
    /// Certificate has expired.
    CertificateExpired,
    /// Certificate type is not valid for the selected mode.
    CertificateTypeMismatch,
    /// Certificate does not match the referenced private key.
    CertificatePrivateKeyMismatch,
    /// Certificate and expected development team differ.
    CertificateTeamMismatch,
    /// Provisioning profile has expired.
    ProfileExpired,
    /// Provisioning profile creation time is in the future.
    ProfileNotYetValid,
    /// Provisioning profile is not an iOS-device profile.
    ProfilePlatformMismatch,
    /// Provisioning profile type does not match the mode.
    ProfileTypeMismatch,
    /// Provisioning profile and expected team differ.
    ProfileTeamMismatch,
    /// Provisioning profile and certificate are incompatible.
    ProfileCertificateMismatch,
    /// Provisioning profile and target bundle identifier differ.
    ProfileBundleIdentifierMismatch,
    /// Profile `application-identifier` does not match team and bundle.
    ApplicationIdentifierMismatch,
    /// Requested registered device is absent from the profile.
    DeviceNotProvisioned,
    /// Required extension has no separate compatible profile.
    ExtensionProfileRequired {
        /// Public target name.
        target: String,
    },
    /// Signed entitlements omitted one required key.
    MissingEntitlement {
        /// Public target name.
        target: String,
        /// Public entitlement key.
        key: String,
    },
    /// Signed/profile/requested values disagree for one entitlement.
    EntitlementMismatch {
        /// Public target name.
        target: String,
        /// Public entitlement key; values are never included.
        key: String,
    },
    /// Main application and extension application groups differ.
    AppGroupMismatch,
    /// `get-task-allow` does not match the signing mode.
    GetTaskAllowMismatch,
    /// Signing lifecycle attempted to skip, repeat, or resume a stage.
    InvalidStatusTransition {
        /// Current stage.
        from: SigningStatus,
        /// Requested next stage.
        to: SigningStatus,
    },
}

impl fmt::Display for SigningValidationError {
    #[allow(clippy::too_many_lines)]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingSigningReference => formatter.write_str("signing reference is required"),
            Self::MissingSigningPasswordReference => {
                formatter.write_str("signing password reference is required")
            }
            Self::MissingDevelopmentTeam => formatter.write_str("development team is required"),
            Self::MissingDevice => formatter.write_str("registered device is required"),
            Self::SigningReferencesForbiddenForUnsigned => {
                formatter.write_str("unsigned mode cannot carry signing references")
            }
            Self::ProvisioningUpdatesForbiddenForUnsigned => {
                formatter.write_str("unsigned mode cannot update provisioning")
            }
            Self::InvalidTeamIdentifier => formatter.write_str("development team is malformed"),
            Self::InvalidDeviceIdentifier => formatter.write_str("device identifier is malformed"),
            Self::InvalidBundleIdentifier => formatter.write_str("bundle identifier is malformed"),
            Self::InvalidTargetName => formatter.write_str("target name is malformed"),
            Self::InvalidCertificateName => formatter.write_str("certificate name is malformed"),
            Self::InvalidCertificateFingerprint => {
                formatter.write_str("certificate fingerprint is malformed")
            }
            Self::InvalidProvisioningProfileIdentifier => {
                formatter.write_str("provisioning profile identifier is malformed")
            }
            Self::InvalidProvisioningProfileName => {
                formatter.write_str("provisioning profile name is malformed")
            }
            Self::InvalidProvisioningProfileDates => {
                formatter.write_str("provisioning profile dates are inconsistent")
            }
            Self::InvalidEntitlementKey { .. } => {
                formatter.write_str("entitlement key is malformed")
            }
            Self::InvalidEntitlementValue { reason, .. } => {
                write!(formatter, "entitlement value is invalid: {reason}")
            }
            Self::MissingApplicationTarget => formatter.write_str("application target is missing"),
            Self::MultipleApplicationTargets => {
                formatter.write_str("multiple application targets were supplied")
            }
            Self::DuplicateTarget { target } => write!(formatter, "duplicate target `{target}`"),
            Self::DuplicateBundleIdentifier { bundle_identifier } => {
                write!(
                    formatter,
                    "duplicate bundle identifier `{bundle_identifier}`"
                )
            }
            Self::UnknownProvisioningTarget { target } => {
                write!(formatter, "unknown provisioning target `{target}`")
            }
            Self::AmbiguousProvisioningProfile { target } => {
                write!(formatter, "ambiguous provisioning profile for `{target}`")
            }
            Self::MissingProvisioningProfile { target } => {
                write!(formatter, "provisioning profile is missing for `{target}`")
            }
            Self::UnknownEntitlementTarget { target } => {
                write!(formatter, "unknown entitlement target `{target}`")
            }
            Self::DuplicateEntitlementPlan { target } => {
                write!(formatter, "duplicate entitlement plan for `{target}`")
            }
            Self::MissingEntitlementPlan { target } => {
                write!(formatter, "entitlement plan is missing for `{target}`")
            }
            Self::CertificateExpired => formatter.write_str("certificate has expired"),
            Self::CertificateTypeMismatch => {
                formatter.write_str("certificate type does not match signing mode")
            }
            Self::CertificatePrivateKeyMismatch => {
                formatter.write_str("certificate does not match private key")
            }
            Self::CertificateTeamMismatch => formatter.write_str("certificate team does not match"),
            Self::ProfileExpired => formatter.write_str("provisioning profile has expired"),
            Self::ProfileNotYetValid => {
                formatter.write_str("provisioning profile is not yet valid")
            }
            Self::ProfilePlatformMismatch => {
                formatter.write_str("provisioning profile is not for iOS devices")
            }
            Self::ProfileTypeMismatch => {
                formatter.write_str("provisioning profile type does not match")
            }
            Self::ProfileTeamMismatch => formatter.write_str("profile team does not match"),
            Self::ProfileCertificateMismatch => {
                formatter.write_str("profile certificate does not match")
            }
            Self::ProfileBundleIdentifierMismatch => {
                formatter.write_str("profile bundle identifier does not match")
            }
            Self::ApplicationIdentifierMismatch => {
                formatter.write_str("profile application identifier does not match")
            }
            Self::DeviceNotProvisioned => {
                formatter.write_str("device is absent from provisioning profile")
            }
            Self::ExtensionProfileRequired { target } => {
                write!(
                    formatter,
                    "extension `{target}` requires a separate profile"
                )
            }
            Self::MissingEntitlement { target, key } => {
                write!(
                    formatter,
                    "target `{target}` is missing entitlement `{key}`"
                )
            }
            Self::EntitlementMismatch { target, key } => {
                write!(
                    formatter,
                    "target `{target}` has incompatible entitlement `{key}`"
                )
            }
            Self::AppGroupMismatch => formatter.write_str("application groups do not match"),
            Self::GetTaskAllowMismatch => {
                formatter.write_str("get-task-allow does not match signing mode")
            }
            Self::InvalidStatusTransition { from, to } => {
                write!(
                    formatter,
                    "invalid signing transition from {from:?} to {to:?}"
                )
            }
        }
    }
}

impl Error for SigningValidationError {}

/// Structural reason an entitlement value was rejected.
#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EntitlementValueError {
    /// JSON null has no entitlement-plist representation.
    Null,
    /// Floating-point values are not accepted in entitlements.
    FloatingPoint,
    /// String exceeded the protocol limit.
    StringTooLong,
    /// Array or dictionary exceeded the item limit.
    CollectionTooLarge,
    /// Nested value exceeded the depth limit.
    TooDeep,
}

impl fmt::Display for EntitlementValueError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Null => formatter.write_str("null is unsupported"),
            Self::FloatingPoint => formatter.write_str("floating point is unsupported"),
            Self::StringTooLong => formatter.write_str("string is too long"),
            Self::CollectionTooLarge => formatter.write_str("collection is too large"),
            Self::TooDeep => formatter.write_str("nesting is too deep"),
        }
    }
}

fn validate_entitlement_key(key: &str) -> Result<(), SigningValidationError> {
    if key.is_empty() || key.len() > MAX_ENTITLEMENT_KEY_BYTES {
        return Err(SigningValidationError::InvalidEntitlementKey { index: None });
    }
    for (index, byte) in key.bytes().enumerate() {
        if !(byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')) {
            return Err(SigningValidationError::InvalidEntitlementKey { index: Some(index) });
        }
    }
    Ok(())
}

fn validate_entitlement_value(
    key: Option<&str>,
    value: &Value,
    depth: usize,
) -> Result<(), SigningValidationError> {
    if depth > MAX_ENTITLEMENT_DEPTH {
        return invalid_entitlement_value(key, EntitlementValueError::TooDeep);
    }
    match value {
        Value::Null => invalid_entitlement_value(key, EntitlementValueError::Null),
        Value::Number(number) if number.is_i64() || number.is_u64() => Ok(()),
        Value::Number(_) => invalid_entitlement_value(key, EntitlementValueError::FloatingPoint),
        Value::String(text) if text.len() > MAX_ENTITLEMENT_STRING_BYTES => {
            invalid_entitlement_value(key, EntitlementValueError::StringTooLong)
        }
        Value::Bool(_) | Value::String(_) => Ok(()),
        Value::Array(items) => {
            if items.len() > MAX_ENTITLEMENT_COLLECTION_ITEMS {
                return invalid_entitlement_value(key, EntitlementValueError::CollectionTooLarge);
            }
            for item in items {
                validate_entitlement_value(key, item, depth + 1)?;
            }
            Ok(())
        }
        Value::Object(object) => {
            if object.len() > MAX_ENTITLEMENT_COLLECTION_ITEMS {
                return invalid_entitlement_value(key, EntitlementValueError::CollectionTooLarge);
            }
            for (nested_key, nested_value) in object {
                validate_entitlement_key(nested_key)?;
                validate_entitlement_value(Some(nested_key), nested_value, depth + 1)?;
            }
            Ok(())
        }
    }
}

fn invalid_entitlement_value(
    key: Option<&str>,
    reason: EntitlementValueError,
) -> Result<(), SigningValidationError> {
    Err(SigningValidationError::InvalidEntitlementValue {
        key: key.map(str::to_owned),
        reason,
    })
}

fn validate_fingerprint(fingerprint: &str) -> Result<(), SigningValidationError> {
    if fingerprint.len() == 64 && fingerprint.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        Ok(())
    } else {
        Err(SigningValidationError::InvalidCertificateFingerprint)
    }
}

fn is_safe_label(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= MAX_LABEL_BYTES
        && !value.chars().any(char::is_control)
        && value.trim() == value
}

fn is_safe_identifier(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= MAX_LABEL_BYTES
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.'))
        && !value.contains("..")
}

fn is_profile_identifier(value: &str) -> bool {
    (8..=64).contains(&value.len())
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
        && !value.starts_with('-')
        && !value.ends_with('-')
}

#[cfg(test)]
mod target_graph_digest_tests {
    use super::*;

    fn target(name: &str, bundle_identifier: &str, kind: SigningTargetKind) -> SigningTarget {
        SigningTarget {
            name: name.to_owned(),
            bundle_identifier: BundleIdentifier::new(bundle_identifier).expect("bundle identifier"),
            kind,
        }
    }

    #[test]
    fn app_only_target_graph_digest_matches_golden() {
        let targets = [target(
            "App",
            "com.example.app",
            SigningTargetKind::Application,
        )];

        assert_eq!(
            canonical_signing_target_graph_sha256(&targets),
            "144f18f553557a96d6a39105b3aa0928c54bf075a5e32fef077a2eef59b37aff"
        );
    }

    #[test]
    fn full_target_graph_digest_is_deterministic_and_binds_every_identity() {
        let targets = vec![
            target(
                "RuntimeBridge",
                "com.example.weather.runtime-bridge",
                SigningTargetKind::Framework,
            ),
            target(
                "WeatherWidget",
                "com.example.weather.widget",
                SigningTargetKind::Extension,
            ),
            target(
                "Weather",
                "com.example.weather",
                SigningTargetKind::Application,
            ),
        ];
        let digest = canonical_signing_target_graph_sha256(&targets);
        let reordered = targets.iter().rev().cloned().collect::<Vec<_>>();

        assert_eq!(
            digest,
            "112e2935c240c978a4e356b5a0e7b3ffc0068ba249807666e8d1662bd366a691"
        );
        assert_eq!(canonical_signing_target_graph_sha256(&reordered), digest);

        let mut app_drift = targets.clone();
        app_drift
            .iter_mut()
            .find(|target| target.kind == SigningTargetKind::Application)
            .expect("application target")
            .bundle_identifier =
            BundleIdentifier::new("com.example.weather.renamed").expect("app bundle drift");
        assert_ne!(canonical_signing_target_graph_sha256(&app_drift), digest);

        let mut framework_drift = targets;
        framework_drift
            .iter_mut()
            .find(|target| target.kind == SigningTargetKind::Framework)
            .expect("framework target")
            .bundle_identifier =
            BundleIdentifier::new("com.example.weather.changed").expect("framework bundle drift");
        assert_ne!(
            canonical_signing_target_graph_sha256(&framework_drift),
            digest
        );
    }
}