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
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
use std::fs;

use camino::{Utf8Path, Utf8PathBuf};
use rustferry_core::{ArtifactDigest, ArtifactDigestKind, ProjectAssets, digest_artifact};
use serde::{Deserialize, Serialize};

use crate::{
    AppleError, AppleToolchain, CommandSpec, ExtensionKind, IosAssetPackaging, error::io_error,
    run_command,
};

const ACTIVITY_MODEL_BUNDLE_IDENTIFIER: &str = "org.rustferry.activity-model";
const ACTIVITY_MODEL_INSTALL_NAME: &str = "@rpath/FerryActivityModel.framework/FerryActivityModel";
const RUNTIME_BRIDGE_INSTALL_NAME: &str = "@rpath/FerryRuntimeBridge.framework/FerryRuntimeBridge";

/// Expected embedded app extension.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IosExtensionExpectation {
    /// Extension family.
    pub kind: ExtensionKind,
    /// Bundle directory name without `.appex`.
    pub bundle_name: String,
    /// Exact extension bundle identifier.
    pub bundle_identifier: String,
    /// Exact extension executable name.
    pub executable_name: String,
    /// Application group that must be embedded in the code signature.
    pub app_group: Option<String>,
}

/// Independent validation inputs for a built iOS application.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IosArtifactExpectation {
    /// Built `.app` directory.
    pub app_path: Utf8PathBuf,
    /// Exact `CFBundleIdentifier`.
    pub bundle_identifier: String,
    /// Exact `CFBundleExecutable` and executable filename.
    pub executable_name: String,
    /// Cargo binary whose Mach-O identity must match the signed embedded executable.
    pub rust_binary: Option<Utf8PathBuf>,
    /// Exact Mach-O architectures expected from `lipo -archs`.
    pub expected_architectures: Vec<String>,
    /// Expected embedded extensions.
    pub extensions: Vec<IosExtensionExpectation>,
    /// Custom URL schemes expected to route through the generated application delegate.
    pub deep_link_schemes: Vec<String>,
    /// Application group that must be embedded in the application signature.
    pub app_group: Option<String>,
    /// Optional destination for redacted validation logs.
    pub log_dir: Option<Utf8PathBuf>,
    /// Validated source snapshot requiring a compiled app-icon and launch-image catalog.
    pub project_assets: Option<ProjectAssets>,
    /// Expected asset representation, absent only when no project assets are required.
    pub asset_packaging: Option<IosAssetPackaging>,
}

/// Evidence that the app consumes the generated asset catalog.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IosAssetCatalogValidation {
    /// Compiled catalog sealed into the application bundle.
    pub compiled_catalog: Utf8PathBuf,
    /// App-icon set selected by processed bundle metadata.
    pub app_icon_name: String,
    /// Launch-screen image set selected by processed bundle metadata.
    pub launch_image_name: String,
}

/// Evidence for the runtime-free, SDK-only image resource fallback.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IosSdkOnlyAssetValidation {
    /// Exact validated icon resource sealed into the application bundle.
    pub icon: Utf8PathBuf,
    /// Exact validated splash resource sealed into the application bundle.
    pub splash: Utf8PathBuf,
    /// Legacy plist icon resource selected by the SDK-only host.
    pub icon_file: String,
    /// Launch-screen image resource selected by the SDK-only host.
    pub launch_image_name: String,
}

/// Validated ad-hoc code-signature metadata.
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IosCodeSignatureValidation {
    /// Exact identifier sealed into the signature.
    pub identifier: String,
    /// Whether the signature uses the local ad-hoc identity.
    pub ad_hoc: bool,
    /// Whether strict signature verification passed.
    pub strict_verified: bool,
    /// Whether recursive strict verification passed for this bundle.
    pub deep_verified: bool,
    /// Whether the bundle's `Info.plist` is sealed.
    pub info_plist_sealed: bool,
    /// Whether the bundle resources are sealed.
    pub resources_sealed: bool,
    /// Application groups embedded in the signature entitlements.
    pub app_groups: Vec<String>,
}

/// Validated embedded extension metadata.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IosExtensionValidation {
    /// Extension family.
    pub kind: ExtensionKind,
    /// Validated `.appex` path.
    pub path: Utf8PathBuf,
    /// Validated bundle identifier.
    pub bundle_identifier: String,
    /// Validated executable path.
    pub executable: Utf8PathBuf,
    /// Validated Mach-O architectures.
    pub architectures: Vec<String>,
    /// Validated extension-point identifier.
    pub extension_point_identifier: String,
    /// Whether an `ActivityKit` extension links the extension-safe shared model framework.
    pub activity_model_linked: bool,
    /// Strictly verified extension code signature.
    pub code_signature: IosCodeSignatureValidation,
}

/// Validated generated native runtime framework metadata.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IosRuntimeBridgeValidation {
    /// Embedded framework bundle path.
    pub path: Utf8PathBuf,
    /// Framework executable path.
    pub executable: Utf8PathBuf,
    /// Exact framework bundle identifier.
    pub bundle_identifier: String,
    /// Validated Mach-O architectures.
    pub architectures: Vec<String>,
    /// Mach-O install name used by the app and extensions.
    pub install_name: String,
    /// Whether the compiled framework contains the pre-`UIApplicationMain` delegate hook.
    pub application_delegate_hook: bool,
    /// Required C ABI entrypoints exported for Rust's dynamic loader.
    pub exported_symbols: Vec<String>,
    /// Strictly verified framework code signature.
    pub code_signature: IosCodeSignatureValidation,
}

/// Evidence collected from a successfully validated `.app`.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct IosArtifactValidation {
    /// Stable validation schema version.
    pub schema_version: u32,
    /// SHA-256 identity of the exact application tree inspected by the platform validator.
    pub artifact_digest: ArtifactDigest,
    /// Validated application path.
    pub app_path: Utf8PathBuf,
    /// Validated bundle identifier.
    pub bundle_identifier: String,
    /// Validated executable path.
    pub executable: Utf8PathBuf,
    /// Validated Mach-O architectures.
    pub architectures: Vec<String>,
    /// Whether the signed executable retains Cargo's Mach-O build identity.
    pub rust_binary_embedded: bool,
    /// Required resources found in the app.
    pub resources: Vec<Utf8PathBuf>,
    /// Compiled asset-catalog and processed metadata evidence.
    pub asset_catalog: Option<IosAssetCatalogValidation>,
    /// Validated raw-resource fallback used when no Simulator runtime is installed.
    pub sdk_only_assets: Option<IosSdkOnlyAssetValidation>,
    /// Inspected embedded frameworks and dynamic libraries.
    pub embedded_frameworks: Vec<Utf8PathBuf>,
    /// Generated native runtime framework evidence.
    pub runtime_bridge: IosRuntimeBridgeValidation,
    /// Validated embedded extensions.
    pub extensions: Vec<IosExtensionValidation>,
    /// Validated custom URL schemes.
    pub deep_link_schemes: Vec<String>,
    /// Generated `UIApplication` delegate class when deep links are enabled.
    pub application_delegate: Option<String>,
    /// Strictly and recursively verified application code signature.
    pub code_signature: IosCodeSignatureValidation,
}

/// Validate plist metadata, executable identity/architecture, resources, libraries, and extensions.
///
/// # Errors
///
/// Returns [`AppleError`] when the bundle is missing, malformed, has unexpected
/// metadata, architecture, code signature, or Cargo build identity, or a validation
/// tool cannot run successfully.
#[allow(clippy::too_many_lines)]
pub fn validate_ios_app(
    expected: &IosArtifactExpectation,
    toolchain: &AppleToolchain,
) -> Result<IosArtifactValidation, AppleError> {
    validate_real_directory(&expected.app_path, "application bundle")?;
    let validated_digest = ios_artifact_digest(&expected.app_path)?;
    let info_plist = expected.app_path.join("Info.plist");
    validate_regular_file(&info_plist, "application Info.plist")?;
    lint_plist(&info_plist, toolchain, expected.log_dir.as_deref(), 1)?;

    let bundle_identifier = plist_value(
        &info_plist,
        "CFBundleIdentifier",
        toolchain,
        expected.log_dir.as_deref(),
        2,
    )?;
    if bundle_identifier != expected.bundle_identifier {
        return invalid(
            &expected.app_path,
            format!(
                "CFBundleIdentifier is `{bundle_identifier}`, expected `{}`",
                expected.bundle_identifier
            ),
        );
    }
    let executable_name = plist_value(
        &info_plist,
        "CFBundleExecutable",
        toolchain,
        expected.log_dir.as_deref(),
        3,
    )?;
    if executable_name != expected.executable_name {
        return invalid(
            &expected.app_path,
            format!(
                "CFBundleExecutable is `{executable_name}`, expected `{}`",
                expected.executable_name
            ),
        );
    }
    let package_type = plist_value(
        &info_plist,
        "CFBundlePackageType",
        toolchain,
        expected.log_dir.as_deref(),
        4,
    )?;
    if package_type != "APPL" {
        return invalid(
            &expected.app_path,
            format!("CFBundlePackageType is `{package_type}`, expected `APPL`"),
        );
    }

    if !expected.deep_link_schemes.is_empty() {
        for (index, scheme) in expected.deep_link_schemes.iter().enumerate() {
            let actual = plist_value(
                &info_plist,
                &format!("CFBundleURLTypes.0.CFBundleURLSchemes.{index}"),
                toolchain,
                expected.log_dir.as_deref(),
                6 + index,
            )?;
            if actual != *scheme {
                return invalid(
                    &info_plist,
                    format!("custom URL scheme {index} is `{actual}`, expected `{scheme}`"),
                );
            }
        }
    }

    let executable = expected.app_path.join(&expected.executable_name);
    validate_executable(&executable)?;
    let architectures =
        macho_architectures(&executable, toolchain, expected.log_dir.as_deref(), 5)?;
    let mut expected_architectures = expected.expected_architectures.clone();
    expected_architectures.sort();
    expected_architectures.dedup();
    if architectures != expected_architectures {
        return invalid(
            &executable,
            format!(
                "Mach-O architectures are {architectures:?}, expected {expected_architectures:?}"
            ),
        );
    }

    let rust_binary_embedded = if let Some(rust_binary) = &expected.rust_binary {
        validate_regular_file(rust_binary, "Cargo-produced Rust executable")?;
        let cargo_uuids = macho_uuids(rust_binary, toolchain, expected.log_dir.as_deref(), 100)?;
        let embedded_uuids = macho_uuids(&executable, toolchain, expected.log_dir.as_deref(), 101)?;
        if cargo_uuids != embedded_uuids {
            return invalid(
                &executable,
                format!(
                    "signed executable Mach-O UUIDs {embedded_uuids:?} differ from Cargo output `{rust_binary}` UUIDs {cargo_uuids:?}; Rust linkage cannot be proven"
                ),
            );
        }
        true
    } else {
        false
    };

    let resources = [
        "FerryResources.json",
        "Assets.car",
        "FerryIcon.png",
        "FerrySplash.png",
    ]
    .into_iter()
    .map(|name| expected.app_path.join(name))
    .filter(|path| path.is_file())
    .collect::<Vec<_>>();
    if !resources
        .iter()
        .any(|path| path.file_name() == Some("FerryResources.json"))
    {
        return invalid(
            &expected.app_path,
            "generated resource metadata `FerryResources.json` is absent from the application bundle"
                .to_owned(),
        );
    }
    let (asset_catalog, sdk_only_assets) = match (
        expected.project_assets.as_ref(),
        expected.asset_packaging,
    ) {
        (None, None) => (None, None),
        (Some(_), Some(IosAssetPackaging::CompiledCatalog)) => {
            for name in ["FerryIcon.png", "FerrySplash.png"] {
                let path = expected.app_path.join(name);
                if path.exists() {
                    return invalid(
                        &path,
                        "SDK-only image resource is present in a compiled-catalog bundle"
                            .to_owned(),
                    );
                }
            }
            let compiled_catalog = expected.app_path.join("Assets.car");
            validate_regular_file(&compiled_catalog, "compiled asset catalog")?;
            let app_icon_name = plist_value(
                &info_plist,
                "CFBundleIconName",
                toolchain,
                expected.log_dir.as_deref(),
                102,
            )?;
            if app_icon_name != "AppIcon" {
                return invalid(
                    &info_plist,
                    format!("CFBundleIconName is `{app_icon_name}`, expected `AppIcon`"),
                );
            }
            let launch_image_name = plist_value(
                &info_plist,
                "UILaunchScreen.UIImageName",
                toolchain,
                expected.log_dir.as_deref(),
                103,
            )?;
            if launch_image_name != "FerryLaunch" {
                return invalid(
                    &info_plist,
                    format!(
                        "UILaunchScreen UIImageName is `{launch_image_name}`, expected `FerryLaunch`"
                    ),
                );
            }
            (
                Some(IosAssetCatalogValidation {
                    compiled_catalog,
                    app_icon_name,
                    launch_image_name,
                }),
                None,
            )
        }
        (Some(assets), Some(IosAssetPackaging::SdkOnlyResources)) => {
            let compiled_catalog = expected.app_path.join("Assets.car");
            if compiled_catalog.exists() {
                return invalid(
                    &compiled_catalog,
                    "compiled asset catalog is present in an SDK-only resource bundle".to_owned(),
                );
            }
            let icon = expected.app_path.join("FerryIcon.png");
            let splash = expected.app_path.join("FerrySplash.png");
            for (path, source_bytes) in [(&icon, assets.icon()), (&splash, assets.splash())] {
                validate_regular_file(path, "SDK-only project image resource")?;
                let actual = fs::read(path)
                    .map_err(|source| io_error("read SDK-only project image", path, source))?;
                if actual != source_bytes {
                    return invalid(
                        path,
                        "embedded image bytes differ from the validated project asset".to_owned(),
                    );
                }
            }
            let icon_file = plist_value(
                &info_plist,
                "CFBundleIconFile",
                toolchain,
                expected.log_dir.as_deref(),
                104,
            )?;
            if icon_file != "FerryIcon" {
                return invalid(
                    &info_plist,
                    format!("CFBundleIconFile is `{icon_file}`, expected `FerryIcon`"),
                );
            }
            let legacy_launch_image = plist_value(
                &info_plist,
                "UILaunchImageFile",
                toolchain,
                expected.log_dir.as_deref(),
                105,
            )?;
            if legacy_launch_image != "FerrySplash" {
                return invalid(
                    &info_plist,
                    format!("UILaunchImageFile is `{legacy_launch_image}`, expected `FerrySplash`"),
                );
            }
            let launch_image_name = plist_value(
                &info_plist,
                "UILaunchScreen.UIImageName",
                toolchain,
                expected.log_dir.as_deref(),
                106,
            )?;
            if launch_image_name != "FerrySplash" {
                return invalid(
                    &info_plist,
                    format!(
                        "UILaunchScreen UIImageName is `{launch_image_name}`, expected `FerrySplash`"
                    ),
                );
            }
            (
                None,
                Some(IosSdkOnlyAssetValidation {
                    icon,
                    splash,
                    icon_file,
                    launch_image_name,
                }),
            )
        }
        _ => {
            return Err(AppleError::InvalidRequest(
                "iOS artifact assets and packaging expectation must either both be present or both be absent"
                    .to_owned(),
            ));
        }
    };

    let embedded_frameworks = inspect_frameworks(&expected.app_path)?;
    let runtime_bridge = validate_runtime_bridge(
        &expected.app_path,
        &expected_architectures,
        toolchain,
        expected.log_dir.as_deref(),
    )?;
    let live_activity_enabled = expected
        .extensions
        .iter()
        .any(|extension| extension.kind == ExtensionKind::ActivityKit);
    if live_activity_enabled {
        validate_activity_model(
            &expected.app_path,
            &expected_architectures,
            &runtime_bridge.executable,
            toolchain,
            expected.log_dir.as_deref(),
        )?;
    } else {
        reject_unexpected_activity_model(&expected.app_path)?;
    }
    let application_delegate = if expected.deep_link_schemes.is_empty() {
        None
    } else if runtime_bridge.application_delegate_hook {
        Some("FerryApplicationDelegate".to_owned())
    } else {
        return invalid(
            &runtime_bridge.executable,
            "runtime framework does not contain the UIApplication initialization delegate hook"
                .to_owned(),
        );
    };
    let extensions = validate_extensions(expected, toolchain)?;
    let plugins = expected.app_path.join("PlugIns");
    if plugins.is_dir() {
        let actual_count = fs::read_dir(&plugins)
            .map_err(|source| io_error("inspect embedded app extensions", &plugins, source))?
            .filter_map(Result::ok)
            .filter(|entry| {
                entry
                    .path()
                    .extension()
                    .is_some_and(|extension| extension == "appex")
            })
            .count();
        if actual_count != expected.extensions.len() {
            return invalid(
                &plugins,
                format!(
                    "found {actual_count} embedded `.appex` bundles, expected {}",
                    expected.extensions.len()
                ),
            );
        }
    } else if !expected.extensions.is_empty() {
        return invalid(
            &plugins,
            format!(
                "PlugIns directory is absent; expected {} app extension(s)",
                expected.extensions.len()
            ),
        );
    }
    let code_signature = validate_code_signature(
        &expected.app_path,
        &expected.bundle_identifier,
        expected.app_group.as_deref(),
        true,
        toolchain,
        expected.log_dir.as_deref(),
        110,
    )?;

    let current_digest = ios_artifact_digest(&expected.app_path)?;
    if current_digest != validated_digest {
        return invalid(
            &expected.app_path,
            "application bundle changed while platform validation was running".to_owned(),
        );
    }

    Ok(IosArtifactValidation {
        schema_version: 9,
        artifact_digest: validated_digest,
        app_path: expected.app_path.clone(),
        bundle_identifier,
        executable,
        architectures,
        rust_binary_embedded,
        resources,
        asset_catalog,
        sdk_only_assets,
        embedded_frameworks,
        runtime_bridge,
        extensions,
        deep_link_schemes: expected.deep_link_schemes.clone(),
        application_delegate,
        code_signature,
    })
}

fn ios_artifact_digest(path: &Utf8Path) -> Result<ArtifactDigest, AppleError> {
    digest_artifact(path, ArtifactDigestKind::IosSimulatorApp).map_err(|error| {
        AppleError::InvalidArtifact {
            path: path.to_owned(),
            reason: format!("could not bind validation to exact application contents: {error}"),
        }
    })
}

fn validate_extensions(
    expected: &IosArtifactExpectation,
    toolchain: &AppleToolchain,
) -> Result<Vec<IosExtensionValidation>, AppleError> {
    let mut validations = Vec::new();
    for (index, extension) in expected.extensions.iter().enumerate() {
        let path = expected
            .app_path
            .join("PlugIns")
            .join(format!("{}.appex", extension.bundle_name));
        validations.push(validate_extension_at(
            &path,
            extension,
            &expected.expected_architectures,
            toolchain,
            expected.log_dir.as_deref(),
            30 + index * 20,
        )?);
    }
    Ok(validations)
}

/// Validate one standalone generated `.appex` product.
///
/// # Errors
///
/// Returns [`AppleError`] when the extension bundle, plist metadata,
/// executable, extension point, or architecture does not match `expected`.
pub fn validate_ios_extension(
    path: &Utf8Path,
    expected: &IosExtensionExpectation,
    expected_architectures: &[String],
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
) -> Result<IosExtensionValidation, AppleError> {
    validate_extension_at(
        path,
        expected,
        expected_architectures,
        toolchain,
        log_dir,
        1,
    )
}

fn validate_extension_at(
    path: &Utf8Path,
    extension: &IosExtensionExpectation,
    expected_architectures: &[String],
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    log_index: usize,
) -> Result<IosExtensionValidation, AppleError> {
    validate_real_directory(path, "embedded app extension")?;
    let info_plist = path.join("Info.plist");
    validate_regular_file(&info_plist, "extension Info.plist")?;
    lint_plist(&info_plist, toolchain, log_dir, log_index)?;
    let bundle_identifier = plist_value(
        &info_plist,
        "CFBundleIdentifier",
        toolchain,
        log_dir,
        log_index + 1,
    )?;
    if bundle_identifier != extension.bundle_identifier {
        return invalid(
            path,
            format!(
                "extension CFBundleIdentifier is `{bundle_identifier}`, expected `{}`",
                extension.bundle_identifier
            ),
        );
    }
    let executable_name = plist_value(
        &info_plist,
        "CFBundleExecutable",
        toolchain,
        log_dir,
        log_index + 2,
    )?;
    if executable_name != extension.executable_name {
        return invalid(
            path,
            format!(
                "extension executable is `{executable_name}`, expected `{}`",
                extension.executable_name
            ),
        );
    }
    let extension_point_identifier = plist_value(
        &info_plist,
        "NSExtension.NSExtensionPointIdentifier",
        toolchain,
        log_dir,
        log_index + 3,
    )?;
    if extension_point_identifier != "com.apple.widgetkit-extension" {
        return invalid(
            path,
            format!(
                "NSExtensionPointIdentifier is `{extension_point_identifier}`, expected `com.apple.widgetkit-extension`"
            ),
        );
    }
    let executable = path.join(&extension.executable_name);
    validate_executable(&executable)?;
    let architectures = macho_architectures(&executable, toolchain, log_dir, log_index + 4)?;
    let mut required = expected_architectures.to_vec();
    required.sort();
    required.dedup();
    if architectures != required {
        return invalid(
            &executable,
            format!("extension architectures are {architectures:?}, expected {required:?}"),
        );
    }
    let activity_model_linked = if extension.kind == ExtensionKind::ActivityKit {
        let dependencies = macho_dependencies(&executable, toolchain, log_dir, log_index + 5)?;
        validate_activity_extension_dependencies(&executable, &dependencies)?
    } else {
        false
    };
    let code_signature = validate_code_signature(
        path,
        &extension.bundle_identifier,
        extension.app_group.as_deref(),
        false,
        toolchain,
        log_dir,
        log_index + 6,
    )?;
    Ok(IosExtensionValidation {
        kind: extension.kind,
        path: path.to_owned(),
        bundle_identifier,
        executable,
        architectures,
        extension_point_identifier,
        activity_model_linked,
        code_signature,
    })
}

fn validate_activity_extension_dependencies(
    executable: &Utf8Path,
    dependencies: &[String],
) -> Result<bool, AppleError> {
    if dependencies
        .iter()
        .any(|dependency| dependency == RUNTIME_BRIDGE_INSTALL_NAME)
    {
        return invalid(
            executable,
            "ActivityKit extension links the app-only FerryRuntimeBridge framework; extensions may only share FerryActivityModel"
                .to_owned(),
        );
    }
    if !dependencies
        .iter()
        .any(|dependency| dependency == ACTIVITY_MODEL_INSTALL_NAME)
    {
        return invalid(
            executable,
            "ActivityKit extension does not link the extension-safe FerryActivityModel framework"
                .to_owned(),
        );
    }
    Ok(true)
}

fn validate_activity_model(
    app_path: &Utf8Path,
    expected_architectures: &[String],
    runtime_bridge_executable: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
) -> Result<(), AppleError> {
    let path = app_path.join("Frameworks/FerryActivityModel.framework");
    validate_real_directory(&path, "embedded Live Activity model framework")?;
    let info_plist = path.join("Info.plist");
    validate_regular_file(&info_plist, "Live Activity model framework Info.plist")?;
    lint_plist(&info_plist, toolchain, log_dir, 170)?;

    let bundle_identifier =
        plist_value(&info_plist, "CFBundleIdentifier", toolchain, log_dir, 171)?;
    if bundle_identifier != ACTIVITY_MODEL_BUNDLE_IDENTIFIER {
        return invalid(
            &path,
            format!(
                "Live Activity model framework bundle identifier is `{bundle_identifier}`, expected `{ACTIVITY_MODEL_BUNDLE_IDENTIFIER}`"
            ),
        );
    }
    let executable_name = plist_value(&info_plist, "CFBundleExecutable", toolchain, log_dir, 172)?;
    if executable_name != "FerryActivityModel" {
        return invalid(
            &path,
            format!(
                "Live Activity model framework executable is `{executable_name}`, expected `FerryActivityModel`"
            ),
        );
    }
    let package_type = plist_value(&info_plist, "CFBundlePackageType", toolchain, log_dir, 173)?;
    if package_type != "FMWK" {
        return invalid(
            &path,
            format!(
                "Live Activity model framework package type is `{package_type}`, expected `FMWK`"
            ),
        );
    }

    let executable = path.join(executable_name);
    validate_executable(&executable)?;
    let architectures = macho_architectures(&executable, toolchain, log_dir, 174)?;
    if architectures != expected_architectures {
        return invalid(
            &executable,
            format!(
                "Live Activity model framework architectures are {architectures:?}, expected {expected_architectures:?}"
            ),
        );
    }
    let install_name = macho_install_name(&executable, toolchain, log_dir, 175)?;
    if install_name != ACTIVITY_MODEL_INSTALL_NAME {
        return invalid(
            &executable,
            format!(
                "Live Activity model framework install name is `{install_name}`, expected `{ACTIVITY_MODEL_INSTALL_NAME}`"
            ),
        );
    }

    let runtime_dependencies =
        macho_dependencies(runtime_bridge_executable, toolchain, log_dir, 176)?;
    if !runtime_dependencies
        .iter()
        .any(|dependency| dependency == ACTIVITY_MODEL_INSTALL_NAME)
    {
        return invalid(
            runtime_bridge_executable,
            "FerryRuntimeBridge does not link the shared FerryActivityModel framework".to_owned(),
        );
    }
    let _ = validate_code_signature(
        &path,
        ACTIVITY_MODEL_BUNDLE_IDENTIFIER,
        None,
        false,
        toolchain,
        log_dir,
        177,
    )?;
    Ok(())
}

fn reject_unexpected_activity_model(app_path: &Utf8Path) -> Result<(), AppleError> {
    let path = app_path.join("Frameworks/FerryActivityModel.framework");
    match fs::symlink_metadata(&path) {
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Ok(_) => invalid(
            &path,
            "Live Activity model framework is embedded but no ActivityKit extension was requested"
                .to_owned(),
        ),
        Err(source) => Err(io_error(
            "inspect unexpected Live Activity model framework",
            &path,
            source,
        )),
    }
}

fn validate_runtime_bridge(
    app_path: &Utf8Path,
    expected_architectures: &[String],
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
) -> Result<IosRuntimeBridgeValidation, AppleError> {
    let path = app_path.join("Frameworks/FerryRuntimeBridge.framework");
    validate_real_directory(&path, "embedded RustFerry runtime framework")?;
    let info_plist = path.join("Info.plist");
    validate_regular_file(&info_plist, "RustFerry runtime framework Info.plist")?;
    lint_plist(&info_plist, toolchain, log_dir, 10)?;
    let bundle_identifier = plist_value(&info_plist, "CFBundleIdentifier", toolchain, log_dir, 11)?;
    if bundle_identifier != "org.rustferry.runtime-bridge" {
        return invalid(
            &path,
            format!(
                "runtime framework bundle identifier is `{bundle_identifier}`, expected `org.rustferry.runtime-bridge`"
            ),
        );
    }
    let executable_name = plist_value(&info_plist, "CFBundleExecutable", toolchain, log_dir, 12)?;
    if executable_name != "FerryRuntimeBridge" {
        return invalid(
            &path,
            format!(
                "runtime framework executable is `{executable_name}`, expected `FerryRuntimeBridge`"
            ),
        );
    }
    let executable = path.join(executable_name);
    validate_executable(&executable)?;
    let architectures = macho_architectures(&executable, toolchain, log_dir, 13)?;
    if architectures != expected_architectures {
        return invalid(
            &executable,
            format!(
                "runtime framework architectures are {architectures:?}, expected {expected_architectures:?}"
            ),
        );
    }
    let install_name = macho_install_name(&executable, toolchain, log_dir, 14)?;
    if install_name != RUNTIME_BRIDGE_INSTALL_NAME {
        return invalid(
            &executable,
            format!(
                "runtime framework install name is `{install_name}`, expected an @rpath framework"
            ),
        );
    }
    let application_delegate_hook = binary_contains(&executable, b"FerryApplicationDelegate")?
        && binary_contains(&executable, b"ferry_bridge_init")?;
    if !application_delegate_hook {
        return invalid(
            &executable,
            "runtime framework is missing the compiled UIApplication delegate-hook markers"
                .to_owned(),
        );
    }
    let exported_symbols = macho_exported_symbols(&executable, toolchain, log_dir, 15)?;
    for required in [
        "_ferry_bridge_call",
        "_ferry_bridge_free",
        "_ferry_bridge_init",
        "_ferry_bridge_install",
        "_ferry_bridge_with_application",
    ] {
        if !exported_symbols.iter().any(|symbol| symbol == required) {
            return invalid(
                &executable,
                format!("runtime framework does not export required C symbol `{required}`"),
            );
        }
    }
    let code_signature = validate_code_signature(
        &path,
        "org.rustferry.runtime-bridge",
        None,
        false,
        toolchain,
        log_dir,
        16,
    )?;
    Ok(IosRuntimeBridgeValidation {
        path,
        executable,
        bundle_identifier,
        architectures,
        install_name,
        application_delegate_hook,
        exported_symbols,
        code_signature,
    })
}

fn binary_contains(path: &Utf8Path, needle: &[u8]) -> Result<bool, AppleError> {
    let bytes = fs::read(path).map_err(|source| io_error("inspect Mach-O bytes", path, source))?;
    Ok(bytes.windows(needle.len()).any(|window| window == needle))
}

fn lint_plist(
    path: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    index: usize,
) -> Result<(), AppleError> {
    let mut command = CommandSpec::new(
        "validate Apple property list",
        &toolchain.plutil,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.args = vec!["-lint".to_owned(), path.to_string()];
    run_command(
        &command,
        validation_log(log_dir, index, "plist-lint").as_deref(),
    )
    .map(|_| ())
}

fn plist_value(
    path: &Utf8Path,
    key_path: &str,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    index: usize,
) -> Result<String, AppleError> {
    let mut command = CommandSpec::new(
        format!("read plist key {key_path}"),
        &toolchain.plutil,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.args = vec![
        "-extract".to_owned(),
        key_path.to_owned(),
        "raw".to_owned(),
        "-o".to_owned(),
        "-".to_owned(),
        path.to_string(),
    ];
    let output = run_command(
        &command,
        validation_log(log_dir, index, "plist-value").as_deref(),
    )?;
    let value = String::from_utf8(output.stdout).map_err(|error| AppleError::InvalidArtifact {
        path: path.to_owned(),
        reason: format!("plist key `{key_path}` is not UTF-8: {error}"),
    })?;
    Ok(value.trim().to_owned())
}

fn macho_architectures(
    path: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    index: usize,
) -> Result<Vec<String>, AppleError> {
    let mut command = CommandSpec::new(
        "inspect Mach-O architectures",
        &toolchain.xcrun,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.environment.insert(
        "DEVELOPER_DIR".to_owned(),
        toolchain.developer_dir.to_string(),
    );
    command.args = vec!["lipo".to_owned(), "-archs".to_owned(), path.to_string()];
    let output = run_command(
        &command,
        validation_log(log_dir, index, "lipo-archs").as_deref(),
    )?;
    let source = String::from_utf8(output.stdout).map_err(|error| AppleError::InvalidArtifact {
        path: path.to_owned(),
        reason: format!("lipo architecture output is not UTF-8: {error}"),
    })?;
    let mut architectures = source
        .split_whitespace()
        .filter(|value| {
            matches!(
                *value,
                "arm64" | "arm64e" | "x86_64" | "i386" | "armv7" | "armv7s"
            )
        })
        .map(ToOwned::to_owned)
        .collect::<Vec<_>>();
    architectures.sort();
    architectures.dedup();
    if architectures.is_empty() {
        return invalid(
            path,
            format!("lipo reported no recognized architecture: {source:?}"),
        );
    }
    Ok(architectures)
}

fn macho_uuids(
    path: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    index: usize,
) -> Result<Vec<String>, AppleError> {
    let mut command = CommandSpec::new(
        "inspect Mach-O build UUIDs",
        &toolchain.xcrun,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.environment.insert(
        "DEVELOPER_DIR".to_owned(),
        toolchain.developer_dir.to_string(),
    );
    command.args = vec![
        "dwarfdump".to_owned(),
        "--uuid".to_owned(),
        path.to_string(),
    ];
    let output = run_command(
        &command,
        validation_log(log_dir, index, "dwarfdump-uuid").as_deref(),
    )?;
    let source = String::from_utf8(output.stdout).map_err(|error| AppleError::InvalidArtifact {
        path: path.to_owned(),
        reason: format!("dwarfdump UUID output is not UTF-8: {error}"),
    })?;
    parse_macho_uuids(path, &source)
}

fn parse_macho_uuids(path: &Utf8Path, source: &str) -> Result<Vec<String>, AppleError> {
    let mut identities = Vec::new();
    for line in source.lines().map(str::trim) {
        let Some(rest) = line.strip_prefix("UUID:") else {
            continue;
        };
        let mut fields = rest.split_whitespace();
        let uuid = fields.next().unwrap_or_default();
        let architecture = fields
            .next()
            .and_then(|value| value.strip_prefix('('))
            .and_then(|value| value.strip_suffix(')'))
            .unwrap_or_default();
        let uuid_is_valid = uuid.len() == 36
            && uuid.chars().enumerate().all(|(index, character)| {
                if matches!(index, 8 | 13 | 18 | 23) {
                    character == '-'
                } else {
                    character.is_ascii_hexdigit()
                }
            });
        if !uuid_is_valid || architecture.is_empty() {
            return invalid(
                path,
                format!("dwarfdump reported a malformed Mach-O UUID line: {line:?}"),
            );
        }
        identities.push(format!("{}:{}", architecture, uuid.to_ascii_uppercase()));
    }
    identities.sort();
    identities.dedup();
    if identities.is_empty() {
        return invalid(
            path,
            format!("dwarfdump reported no Mach-O UUIDs: {source:?}"),
        );
    }
    Ok(identities)
}

fn macho_install_name(
    path: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    index: usize,
) -> Result<String, AppleError> {
    let mut command = CommandSpec::new(
        "inspect Mach-O install name",
        &toolchain.xcrun,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.environment.insert(
        "DEVELOPER_DIR".to_owned(),
        toolchain.developer_dir.to_string(),
    );
    command.args = vec!["otool".to_owned(), "-D".to_owned(), path.to_string()];
    let output = run_command(
        &command,
        validation_log(log_dir, index, "otool-install-name").as_deref(),
    )?;
    let output = String::from_utf8(output.stdout).map_err(|error| AppleError::InvalidArtifact {
        path: path.to_owned(),
        reason: format!("otool install-name output is not UTF-8: {error}"),
    })?;
    output
        .lines()
        .map(str::trim)
        .find(|line| line.starts_with('@'))
        .map(ToOwned::to_owned)
        .ok_or_else(|| AppleError::InvalidArtifact {
            path: path.to_owned(),
            reason: format!("otool reported no install name: {output:?}"),
        })
}

fn macho_dependencies(
    path: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    index: usize,
) -> Result<Vec<String>, AppleError> {
    let mut command = CommandSpec::new(
        "inspect Mach-O linked libraries",
        &toolchain.xcrun,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.environment.insert(
        "DEVELOPER_DIR".to_owned(),
        toolchain.developer_dir.to_string(),
    );
    command.args = vec!["otool".to_owned(), "-L".to_owned(), path.to_string()];
    let output = run_command(
        &command,
        validation_log(log_dir, index, "otool-linked-libraries").as_deref(),
    )?;
    let output = String::from_utf8(output.stdout).map_err(|error| AppleError::InvalidArtifact {
        path: path.to_owned(),
        reason: format!("otool linked-library output is not UTF-8: {error}"),
    })?;
    Ok(output
        .lines()
        .skip(1)
        .filter_map(|line| line.split_whitespace().next())
        .map(ToOwned::to_owned)
        .collect())
}

fn macho_exported_symbols(
    path: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    index: usize,
) -> Result<Vec<String>, AppleError> {
    let mut command = CommandSpec::new(
        "inspect Mach-O exported symbols",
        &toolchain.xcrun,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.environment.insert(
        "DEVELOPER_DIR".to_owned(),
        toolchain.developer_dir.to_string(),
    );
    command.args = vec!["nm".to_owned(), "-gj".to_owned(), path.to_string()];
    let output = run_command(
        &command,
        validation_log(log_dir, index, "nm-exported-symbols").as_deref(),
    )?;
    let output = String::from_utf8(output.stdout).map_err(|error| AppleError::InvalidArtifact {
        path: path.to_owned(),
        reason: format!("nm exported-symbol output is not UTF-8: {error}"),
    })?;
    Ok(output
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(ToOwned::to_owned)
        .collect())
}

fn inspect_frameworks(app_path: &Utf8Path) -> Result<Vec<Utf8PathBuf>, AppleError> {
    let directory = app_path.join("Frameworks");
    if !directory.exists() {
        return Ok(Vec::new());
    }
    validate_real_directory(&directory, "embedded Frameworks directory")?;
    let mut entries = fs::read_dir(&directory)
        .map_err(|source| io_error("inspect embedded frameworks", &directory, source))?
        .map(|entry| {
            let entry = entry
                .map_err(|source| io_error("inspect embedded framework", &directory, source))?;
            let path = Utf8PathBuf::from_path_buf(entry.path()).map_err(AppleError::NonUtf8Path)?;
            let metadata = fs::symlink_metadata(&path)
                .map_err(|source| io_error("inspect embedded framework metadata", &path, source))?;
            if metadata.file_type().is_symlink() {
                return invalid::<Utf8PathBuf>(
                    &path,
                    "top-level embedded framework/library cannot be a symbolic link".to_owned(),
                );
            }
            if metadata.is_file() && metadata.len() == 0 {
                return invalid::<Utf8PathBuf>(&path, "embedded library is empty".to_owned());
            }
            Ok(path)
        })
        .collect::<Result<Vec<_>, AppleError>>()?;
    entries.sort();
    Ok(entries)
}

fn validate_code_signature(
    path: &Utf8Path,
    expected_identifier: &str,
    expected_app_group: Option<&str>,
    deep: bool,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    log_index: usize,
) -> Result<IosCodeSignatureValidation, AppleError> {
    validate_regular_file(
        &path.join("_CodeSignature/CodeResources"),
        "sealed code-signature resources",
    )?;

    let mut verify = CommandSpec::new(
        "strictly verify iOS bundle code signature",
        &toolchain.xcrun,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    verify.environment.insert(
        "DEVELOPER_DIR".to_owned(),
        toolchain.developer_dir.to_string(),
    );
    verify.args = vec!["codesign".to_owned(), "--verify".to_owned()];
    if deep {
        verify.args.push("--deep".to_owned());
    }
    verify.args.extend([
        "--strict".to_owned(),
        "--verbose=4".to_owned(),
        "--test-requirement".to_owned(),
        format!("=identifier \"{expected_identifier}\""),
        path.to_string(),
    ]);
    run_command(
        &verify,
        validation_log(log_dir, log_index, "codesign-verify").as_deref(),
    )?;

    let entitlement_file = tempfile::NamedTempFile::new()
        .map_err(|source| io_error("create temporary entitlement output", path, source))?;
    let entitlement_path = Utf8PathBuf::from_path_buf(entitlement_file.path().to_owned())
        .map_err(AppleError::NonUtf8Path)?;
    let mut display = CommandSpec::new(
        "inspect iOS bundle code signature",
        &toolchain.xcrun,
        path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    display.environment.insert(
        "DEVELOPER_DIR".to_owned(),
        toolchain.developer_dir.to_string(),
    );
    display.args = vec![
        "codesign".to_owned(),
        "--display".to_owned(),
        "--verbose=4".to_owned(),
        "--entitlements".to_owned(),
        entitlement_path.to_string(),
        "--xml".to_owned(),
        path.to_string(),
    ];
    let output = run_command(
        &display,
        validation_log(log_dir, log_index + 1, "codesign-display").as_deref(),
    )?;
    let mut metadata =
        String::from_utf8(output.stderr).map_err(|error| AppleError::InvalidArtifact {
            path: path.to_owned(),
            reason: format!("codesign metadata is not UTF-8: {error}"),
        })?;
    if !output.stdout.is_empty() {
        metadata.push('\n');
        metadata.push_str(&String::from_utf8(output.stdout).map_err(|error| {
            AppleError::InvalidArtifact {
                path: path.to_owned(),
                reason: format!("codesign metadata is not UTF-8: {error}"),
            }
        })?);
    }
    let displayed = parse_code_signature_display(path, &metadata)?;
    if displayed.identifier != expected_identifier {
        return invalid(
            path,
            format!(
                "code-signature identifier is `{}`, expected `{expected_identifier}`",
                displayed.identifier
            ),
        );
    }
    let app_groups =
        code_signature_app_groups(path, &entitlement_path, toolchain, log_dir, log_index + 2)?;
    let expected_app_groups = expected_app_group
        .map(|group| vec![group.to_owned()])
        .unwrap_or_default();
    if app_groups != expected_app_groups {
        return invalid(
            path,
            format!(
                "signed application groups are {app_groups:?}, expected {expected_app_groups:?}"
            ),
        );
    }

    Ok(IosCodeSignatureValidation {
        identifier: displayed.identifier,
        ad_hoc: true,
        strict_verified: true,
        deep_verified: deep,
        info_plist_sealed: true,
        resources_sealed: true,
        app_groups,
    })
}

struct DisplayedCodeSignature {
    identifier: String,
}

fn parse_code_signature_display(
    path: &Utf8Path,
    source: &str,
) -> Result<DisplayedCodeSignature, AppleError> {
    let identifier = source
        .lines()
        .find_map(|line| line.trim().strip_prefix("Identifier="))
        .filter(|value| !value.is_empty())
        .map(ToOwned::to_owned)
        .ok_or_else(|| AppleError::InvalidArtifact {
            path: path.to_owned(),
            reason: format!("codesign reported no signature identifier: {source:?}"),
        })?;
    if !source.lines().any(|line| line.trim() == "Signature=adhoc") {
        return invalid(path, "code signature is not ad-hoc".to_owned());
    }
    if source.lines().any(|line| line.contains("linker-signed")) {
        return invalid(
            path,
            "code has only a linker-generated signature, not a sealed bundle signature".to_owned(),
        );
    }
    if !source
        .lines()
        .any(|line| line.trim().starts_with("Info.plist entries="))
    {
        return invalid(path, "code signature does not seal Info.plist".to_owned());
    }
    if !source
        .lines()
        .any(|line| line.trim().starts_with("Sealed Resources version="))
    {
        return invalid(
            path,
            "code signature does not seal bundle resources".to_owned(),
        );
    }
    Ok(DisplayedCodeSignature { identifier })
}

fn code_signature_app_groups(
    bundle_path: &Utf8Path,
    entitlement_path: &Utf8Path,
    toolchain: &AppleToolchain,
    log_dir: Option<&Utf8Path>,
    log_index: usize,
) -> Result<Vec<String>, AppleError> {
    let metadata = fs::metadata(entitlement_path).map_err(|source| {
        io_error(
            "inspect extracted code-signature entitlements",
            bundle_path,
            source,
        )
    })?;
    if metadata.len() == 0 {
        return Ok(Vec::new());
    }
    let mut command = CommandSpec::new(
        "convert code-signature entitlements to JSON",
        &toolchain.plutil,
        bundle_path.parent().unwrap_or_else(|| Utf8Path::new(".")),
    );
    command.args = vec![
        "-convert".to_owned(),
        "json".to_owned(),
        "-o".to_owned(),
        "-".to_owned(),
        entitlement_path.to_string(),
    ];
    let output = run_command(
        &command,
        validation_log(log_dir, log_index, "entitlements-json").as_deref(),
    )?;
    let value: serde_json::Value =
        serde_json::from_slice(&output.stdout).map_err(|error| AppleError::InvalidArtifact {
            path: bundle_path.to_owned(),
            reason: format!("signed entitlements are not valid JSON: {error}"),
        })?;
    let Some(groups) = value.get("com.apple.security.application-groups") else {
        return Ok(Vec::new());
    };
    let groups = groups
        .as_array()
        .ok_or_else(|| AppleError::InvalidArtifact {
            path: bundle_path.to_owned(),
            reason: "signed application-group entitlement is not an array".to_owned(),
        })?;
    let mut groups = groups
        .iter()
        .map(|value| {
            value
                .as_str()
                .map(ToOwned::to_owned)
                .ok_or_else(|| AppleError::InvalidArtifact {
                    path: bundle_path.to_owned(),
                    reason: "signed application-group entitlement contains a non-string value"
                        .to_owned(),
                })
        })
        .collect::<Result<Vec<_>, _>>()?;
    groups.sort();
    Ok(groups)
}

fn validate_real_directory(path: &Utf8Path, description: &str) -> Result<(), AppleError> {
    let metadata = fs::symlink_metadata(path).map_err(|source| {
        if source.kind() == std::io::ErrorKind::NotFound {
            AppleError::InvalidArtifact {
                path: path.to_owned(),
                reason: format!("{description} does not exist"),
            }
        } else {
            io_error("inspect iOS artifact directory", path, source)
        }
    })?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return invalid(path, format!("{description} is not a real directory"));
    }
    Ok(())
}

fn validate_regular_file(path: &Utf8Path, description: &str) -> Result<(), AppleError> {
    let metadata = fs::symlink_metadata(path).map_err(|source| {
        if source.kind() == std::io::ErrorKind::NotFound {
            AppleError::InvalidArtifact {
                path: path.to_owned(),
                reason: format!("{description} does not exist"),
            }
        } else {
            io_error("inspect iOS artifact file", path, source)
        }
    })?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return invalid(path, format!("{description} is not a regular file"));
    }
    if metadata.len() == 0 {
        return invalid(path, format!("{description} is empty"));
    }
    Ok(())
}

fn validate_executable(path: &Utf8Path) -> Result<(), AppleError> {
    validate_regular_file(path, "bundle executable")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = fs::metadata(path)
            .map_err(|source| io_error("inspect executable permissions", path, source))?
            .permissions()
            .mode();
        if mode & 0o111 == 0 {
            return invalid(
                path,
                "bundle executable has no executable permission bits".to_owned(),
            );
        }
    }
    Ok(())
}

fn validation_log(log_dir: Option<&Utf8Path>, index: usize, name: &str) -> Option<Utf8PathBuf> {
    log_dir.map(|directory| directory.join(format!("{index:02}-{name}.log")))
}

fn invalid<T>(path: &Utf8Path, reason: String) -> Result<T, AppleError> {
    Err(AppleError::InvalidArtifact {
        path: path.to_owned(),
        reason,
    })
}

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

    #[test]
    fn parses_macho_uuid_identity_by_architecture() {
        let path = Utf8Path::new("FerryApp");
        let parsed = parse_macho_uuids(
            path,
            "UUID: 3ecf92d7-c52e-33a0-9292-5f69e5190057 (arm64) FerryApp\n",
        )
        .unwrap();
        assert_eq!(parsed, ["arm64:3ECF92D7-C52E-33A0-9292-5F69E5190057"]);
        assert!(parse_macho_uuids(path, "UUID: malformed (arm64) FerryApp").is_err());
    }

    #[test]
    fn requires_a_sealed_non_linker_adhoc_signature() {
        let path = Utf8Path::new("RustFerry.app");
        let parsed = parse_code_signature_display(
            path,
            "Identifier=com.example.ferry\nSignature=adhoc\nInfo.plist entries=28\nSealed Resources version=2 rules=13 files=2\n",
        )
        .unwrap();
        assert_eq!(parsed.identifier, "com.example.ferry");
        assert!(
            parse_code_signature_display(
                path,
                "Identifier=ferry-bin\nSignature=adhoc\nCodeDirectory flags=0x20002(adhoc,linker-signed)\nInfo.plist=not bound\nSealed Resources=none\n",
            )
            .is_err()
        );
    }

    #[test]
    fn rejects_symlinked_app_bundle() {
        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;

            let temporary = tempfile::tempdir().unwrap();
            let root = Utf8Path::from_path(temporary.path()).unwrap();
            fs::create_dir(root.join("real.app")).unwrap();
            symlink(root.join("real.app"), root.join("linked.app")).unwrap();
            assert!(matches!(
                validate_real_directory(&root.join("linked.app"), "app"),
                Err(AppleError::InvalidArtifact { .. })
            ));
        }
    }

    #[test]
    fn activity_extension_requires_only_the_safe_model_framework() {
        let executable = Utf8Path::new("FerryLiveActivityExtension");
        assert!(
            validate_activity_extension_dependencies(
                executable,
                &[ACTIVITY_MODEL_INSTALL_NAME.to_owned()]
            )
            .unwrap()
        );
        assert!(validate_activity_extension_dependencies(executable, &[]).is_err());
        assert!(
            validate_activity_extension_dependencies(
                executable,
                &[
                    ACTIVITY_MODEL_INSTALL_NAME.to_owned(),
                    RUNTIME_BRIDGE_INSTALL_NAME.to_owned(),
                ],
            )
            .is_err()
        );
    }

    #[test]
    fn rejects_stale_activity_model_without_an_activity_extension() {
        let temporary = tempfile::tempdir().unwrap();
        let app = Utf8Path::from_path(temporary.path()).unwrap();
        assert!(reject_unexpected_activity_model(app).is_ok());
        fs::create_dir_all(app.join("Frameworks/FerryActivityModel.framework")).unwrap();
        assert!(reject_unexpected_activity_model(app).is_err());
    }
}