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
//! Secure Content extension parsing
//!
//! This module handles parsing of 3MF Secure Content extension elements including
//! keystore, consumers, resource data groups, access rights, and encryption parameters.
//! It also provides decryption support for encrypted files using test keys.
use crate::error::{Error, Result};
use crate::model::*;
use crate::opc::{ENCRYPTEDFILE_REL_TYPE, Package};
use quick_xml::Reader;
use quick_xml::events::Event;
use std::collections::HashSet;
use std::io::Read;
use super::get_local_name;
/// Valid wrapping algorithm for SecureContent (2001 version)
const VALID_WRAPPING_ALGORITHM_2001: &str = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p";
/// Valid wrapping algorithm for SecureContent (2009 version)
const VALID_WRAPPING_ALGORITHM_2009: &str = "http://www.w3.org/2009/xmlenc11#rsa-oaep";
/// Default compression value for SecureContent CEK params
const DEFAULT_COMPRESSION: &str = "none";
/// Test consumer ID from Suite 8 test specification
/// This is duplicated from the decryption module to avoid a dependency when crypto feature is disabled
const TEST_CONSUMER_ID: &str = "test3mf01";
/// Valid MGF algorithms for SecureContent kekparams
const VALID_MGF_ALGORITHMS: &[&str] = &[
"http://www.w3.org/2009/xmlenc11#mgf1sha1",
"http://www.w3.org/2009/xmlenc11#mgf1sha256",
"http://www.w3.org/2009/xmlenc11#mgf1sha384",
"http://www.w3.org/2009/xmlenc11#mgf1sha512",
];
/// Valid digest methods for SecureContent kekparams
const VALID_DIGEST_METHODS: &[&str] = &[
"http://www.w3.org/2000/09/xmldsig#sha1",
"http://www.w3.org/2001/04/xmlenc#sha256",
"http://www.w3.org/2001/04/xmlenc#sha384",
"http://www.w3.org/2001/04/xmlenc#sha512",
];
/// Default buffer capacity for XML parsing (4KB)
const XML_BUFFER_CAPACITY: usize = 4096;
/// Validate KEK params attributes
///
/// Validates wrapping algorithm, MGF algorithm, and digest method according to
/// EPX-2603 specification requirements.
pub(super) fn validate_kekparams_attributes(
wrapping_algorithm: &str,
mgf_algorithm: &str,
digest_method: &str,
sc: &mut SecureContentInfo,
) -> Result<()> {
// EPX-2603: Validate wrapping algorithm
if !wrapping_algorithm.is_empty() {
let is_valid = wrapping_algorithm == VALID_WRAPPING_ALGORITHM_2001
|| wrapping_algorithm == VALID_WRAPPING_ALGORITHM_2009;
if !is_valid {
return Err(Error::InvalidSecureContent(format!(
"Invalid wrapping algorithm '{}'. Must be either '{}' or '{}' (EPX-2603)",
wrapping_algorithm, VALID_WRAPPING_ALGORITHM_2001, VALID_WRAPPING_ALGORITHM_2009
)));
}
sc.wrapping_algorithms.push(wrapping_algorithm.to_string());
}
// EPX-2603: Validate mgfalgorithm if present
if !mgf_algorithm.is_empty() && !VALID_MGF_ALGORITHMS.contains(&mgf_algorithm) {
return Err(Error::InvalidSecureContent(format!(
"Invalid mgfalgorithm '{}'. Must be one of mgf1sha1, mgf1sha256, mgf1sha384, or mgf1sha512 (EPX-2603)",
mgf_algorithm
)));
}
// EPX-2603: Validate digestmethod if present
if !digest_method.is_empty() && !VALID_DIGEST_METHODS.contains(&digest_method) {
return Err(Error::InvalidSecureContent(format!(
"Invalid digestmethod '{}'. Must be one of sha1, sha256, sha384, or sha512 (EPX-2603)",
digest_method
)));
}
Ok(())
}
/// Load and parse Secure/keystore.xml to identify encrypted files
///
/// This provides the complete structural information needed for applications to
/// implement their own decryption logic using external cryptographic libraries.
///
/// This function also performs validation as per 3MF SecureContent specification:
/// - EPX-2601: Validates consumer index references exist
/// - EPX-2602: Validates consumers exist when access rights are defined
/// - EPX-2603: Validates encryption algorithms are valid
/// - EPX-2604: Validates consumer IDs are unique
/// - EPX-2605: Validates encrypted file paths are valid (not OPC .rels files)
/// - EPX-2607: Validates referenced files exist in the package
pub(super) fn load_keystore<R: Read + std::io::Seek>(
package: &mut Package<R>,
model: &mut Model,
_config: &ParserConfig,
) -> Result<()> {
// Discover keystore file path from relationships
// Per 3MF SecureContent spec, the keystore is identified by a relationship of type
// http://schemas.microsoft.com/3dmanufacturing/{version}/keystore
let keystore_path = match package.discover_keystore_path()? {
Some(path) => path,
None => {
// Try fallback to default paths for backward compatibility
// Check both Secure/keystore.xml and Secure/info.store
if package.has_file("Secure/keystore.xml") {
"Secure/keystore.xml".to_string()
} else if package.has_file("Secure/info.store") {
"Secure/info.store".to_string()
} else {
return Ok(()); // No keystore file, not an error
}
}
};
// EPX-2606: Validate keystore has proper relationship in root .rels
// This catches cases where the keystore file exists but only has a mustpreserve
// relationship instead of the proper keystore relationship type
package.validate_keystore_relationship(&keystore_path)?;
// EPX-2606: Validate keystore has proper content type override
// This catches cases where the keystore file exists but is missing the
// required content type declaration in [Content_Types].xml
package.validate_keystore_content_type(&keystore_path)?;
// Load the keystore file
// Use get_file_binary() to handle files that may contain encrypted/binary data
let keystore_bytes = package.get_file_binary(&keystore_path)?;
// Initialize secure_content if not already present
if model.secure_content.is_none() {
model.secure_content = Some(SecureContentInfo::default());
}
// Convert bytes to string, using lossy conversion to handle any non-UTF-8 sequences
// This allows parsing keystore files that may contain encrypted content
let keystore_xml = String::from_utf8_lossy(&keystore_bytes);
let mut reader = Reader::from_str(&keystore_xml);
reader.config_mut().trim_text(true);
let mut buf = Vec::with_capacity(XML_BUFFER_CAPACITY);
// State tracking for nested parsing
let mut current_consumer: Option<Consumer> = None;
let mut current_resource_group: Option<ResourceDataGroup> = None;
let mut current_access_right: Option<AccessRight> = None;
let mut current_resource_data: Option<ResourceData> = None;
let mut current_kek_params: Option<KEKParams> = None;
let mut current_cek_params: Option<CEKParams> = None;
let mut text_buffer = String::with_capacity(512); // Typical size for base64-encoded values
let mut encrypted_paths = HashSet::new(); // Track resourcedata paths for duplicate detection
loop {
match reader.read_event_into(&mut buf) {
Ok(Event::Empty(ref e)) => {
// Handle self-closing tags
let name = e.name();
let name_str = std::str::from_utf8(name.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
let local_name = get_local_name(name_str);
// Handle self-closing elements that need validation or tracking
if local_name == "kekparams" {
// EPX-2603: Extract and validate kekparams attributes
let mut wrapping_algorithm = String::new();
let mut mgf_algorithm = String::new();
let mut digest_method = String::new();
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!("Invalid attribute in kekparams: {}", e))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
let attr_value = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?
.to_string();
match attr_name {
"wrappingalgorithm" => wrapping_algorithm = attr_value,
"mgfalgorithm" => mgf_algorithm = attr_value,
"digestmethod" => digest_method = attr_value,
_ => {}
}
}
if let Some(ref mut sc) = model.secure_content {
validate_kekparams_attributes(
&wrapping_algorithm,
&mgf_algorithm,
&digest_method,
sc,
)?;
}
// Store the KEK params in the current access right
if let Some(ref mut access_right) = current_access_right {
access_right.kek_params = KEKParams {
wrapping_algorithm,
mgf_algorithm: if mgf_algorithm.is_empty() {
None
} else {
Some(mgf_algorithm)
},
digest_method: if digest_method.is_empty() {
None
} else {
Some(digest_method)
},
};
}
}
}
Ok(Event::Start(ref e)) => {
let name = e.name();
let name_str = std::str::from_utf8(name.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
let local_name = get_local_name(name_str);
match local_name {
"keystore" => {
// Extract UUID attribute from keystore element
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!("Invalid attribute in keystore: {}", e))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
if attr_name == "UUID" {
let uuid = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?
.to_string();
if let Some(ref mut sc) = model.secure_content {
sc.keystore_uuid = Some(uuid);
}
}
}
}
"consumer" => {
let mut consumer_id = String::new();
let mut key_id = None;
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!("Invalid attribute in consumer: {}", e))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
let attr_value = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?
.to_string();
match attr_name {
"consumerid" => consumer_id = attr_value,
"keyid" => key_id = Some(attr_value),
_ => {}
}
}
// EPX-2604: Check for duplicate consumer IDs
if let Some(ref mut sc) = model.secure_content {
if sc.consumer_ids.contains(&consumer_id) {
return Err(Error::InvalidSecureContent(format!(
"Duplicate consumer ID '{}' in keystore (EPX-2604)",
consumer_id
)));
}
sc.consumer_ids.push(consumer_id.clone());
sc.consumer_count += 1;
}
current_consumer = Some(Consumer {
consumer_id,
key_id,
key_value: None,
});
}
"keyvalue" => {
text_buffer.clear();
}
"resourcedatagroup" => {
let mut key_uuid = String::new();
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!(
"Invalid attribute in resourcedatagroup: {}",
e
))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
if attr_name == "keyuuid" {
key_uuid = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?
.to_string();
}
}
current_resource_group = Some(ResourceDataGroup {
key_uuid,
access_rights: Vec::new(),
resource_data: Vec::new(),
});
}
"accessright" => {
let mut consumer_index = 0;
// EPX-2601: Track and validate consumer index
// EPX-2606: Track accessright elements that have kekparams
// We'll check if they have cipherdata in a subsequent Text event
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!(
"Invalid attribute in accessright: {}",
e
))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
if attr_name == "consumerindex" {
let index_str = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?;
consumer_index = index_str.parse::<usize>().map_err(|_| {
Error::InvalidSecureContent(format!(
"Invalid consumer index '{}' (must be a valid number)",
index_str
))
})?;
}
}
current_access_right = Some(AccessRight {
consumer_index,
kek_params: KEKParams {
wrapping_algorithm: String::new(),
mgf_algorithm: None,
digest_method: None,
},
cipher_value: String::new(),
});
}
"kekparams" => {
// EPX-2603: Extract and validate kekparams attributes
let mut wrapping_algorithm = String::new();
let mut mgf_algorithm = None;
let mut digest_method = None;
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!("Invalid attribute in kekparams: {}", e))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
let attr_value = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?
.to_string();
match attr_name {
"wrappingalgorithm" => wrapping_algorithm = attr_value,
"mgfalgorithm" => mgf_algorithm = Some(attr_value),
"digestmethod" => digest_method = Some(attr_value),
_ => {}
}
}
current_kek_params = Some(KEKParams {
wrapping_algorithm,
mgf_algorithm,
digest_method,
});
}
"cipherdata" => {
// cipherdata contains xenc:CipherValue
}
"CipherValue" => {
text_buffer.clear();
}
"resourcedata" => {
let mut path = String::new();
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!(
"Invalid attribute in resourcedata: {}",
e
))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
if attr_name == "path" {
path = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?
.to_string();
}
}
// EPX-2605: Validate path
if path.trim().is_empty() {
return Err(Error::InvalidSecureContent(
"Resource data path attribute cannot be empty (EPX-2605)"
.to_string(),
));
}
let path_lower = path.to_lowercase();
if path_lower.contains("/_rels/") || path_lower.ends_with(".rels") {
return Err(Error::InvalidSecureContent(format!(
"Invalid encrypted file path '{}'. OPC relationship files cannot be encrypted (EPX-2605)",
path
)));
}
// EPX-2607: Validate file exists
let lookup_path = path.trim_start_matches('/');
if !package.has_file(lookup_path) {
return Err(Error::InvalidSecureContent(format!(
"Referenced encrypted file '{}' does not exist in package (EPX-2607)",
path
)));
}
// EPX-2607: Validate resourcedata paths are unique (no duplicates)
if !encrypted_paths.insert(path.clone()) {
return Err(Error::InvalidSecureContent(format!(
"Duplicate resourcedata path '{}' in keystore (EPX-2607)",
path
)));
}
// Add to encrypted_files list (for backward compatibility)
if let Some(ref mut sc) = model.secure_content {
sc.encrypted_files.push(path.clone());
}
current_resource_data = Some(ResourceData {
path,
cek_params: CEKParams {
encryption_algorithm: String::new(),
compression: DEFAULT_COMPRESSION.to_string(),
iv: None,
tag: None,
aad: None,
},
});
}
"cekparams" => {
let mut encryption_algorithm = String::new();
let mut compression = DEFAULT_COMPRESSION.to_string();
for attr in e.attributes() {
let attr = attr.map_err(|e| {
Error::InvalidXml(format!("Invalid attribute in cekparams: {}", e))
})?;
let attr_name = std::str::from_utf8(attr.key.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
let attr_value = std::str::from_utf8(&attr.value)
.map_err(|e| Error::InvalidXml(e.to_string()))?
.to_string();
match attr_name {
"encryptionalgorithm" => encryption_algorithm = attr_value,
"compression" => compression = attr_value,
_ => {}
}
}
current_cek_params = Some(CEKParams {
encryption_algorithm,
compression,
iv: None,
tag: None,
aad: None,
});
}
"iv" => {
text_buffer.clear();
}
"tag" => {
text_buffer.clear();
}
"aad" => {
text_buffer.clear();
}
_ => {}
}
}
Ok(Event::Text(ref e)) => {
let text = e.decode().map_err(|e| Error::InvalidXml(e.to_string()))?;
text_buffer.push_str(&text);
}
Ok(Event::End(ref e)) => {
let name = e.name();
let name_str = std::str::from_utf8(name.as_ref())
.map_err(|e| Error::InvalidXml(e.to_string()))?;
let local_name = get_local_name(name_str);
match local_name {
"consumer" => {
if let Some(consumer) = current_consumer.take()
&& let Some(ref mut sc) = model.secure_content
{
sc.consumers.push(consumer);
}
}
"keyvalue" => {
if let Some(ref mut consumer) = current_consumer {
consumer.key_value = Some(text_buffer.trim().to_string());
}
}
"resourcedatagroup" => {
if let Some(group) = current_resource_group.take()
&& let Some(ref mut sc) = model.secure_content
{
sc.resource_data_groups.push(group);
}
}
"accessright" => {
if let Some(access_right) = current_access_right.take()
&& let Some(ref mut group) = current_resource_group
{
group.access_rights.push(access_right);
}
}
"kekparams" => {
if let Some(kek_params) = current_kek_params.take()
&& let Some(ref mut access_right) = current_access_right
{
access_right.kek_params = kek_params;
}
}
"CipherValue" => {
if let Some(ref mut access_right) = current_access_right {
access_right.cipher_value = text_buffer.trim().to_string();
}
}
"resourcedata" => {
if let Some(resource_data) = current_resource_data.take()
&& let Some(ref mut group) = current_resource_group
{
group.resource_data.push(resource_data);
}
}
"cekparams" => {
if let Some(cek_params) = current_cek_params.take()
&& let Some(ref mut resource_data) = current_resource_data
{
resource_data.cek_params = cek_params;
}
}
"iv" => {
if let Some(ref mut cek_params) = current_cek_params {
cek_params.iv = Some(text_buffer.trim().to_string());
}
}
"tag" => {
if let Some(ref mut cek_params) = current_cek_params {
cek_params.tag = Some(text_buffer.trim().to_string());
}
}
"aad" => {
if let Some(ref mut cek_params) = current_cek_params {
cek_params.aad = Some(text_buffer.trim().to_string());
}
}
_ => {}
}
}
Ok(Event::Eof) => break,
Err(e) => {
return Err(Error::InvalidXml(format!(
"Error parsing keystore.xml: {}",
e
)));
}
_ => {}
}
buf.clear();
}
// Final validation
if let Some(ref sc) = model.secure_content {
// EPX-2602: If we have resourcedatagroups, at least one consumer must be defined
if !sc.resource_data_groups.is_empty() && sc.consumer_count == 0 {
return Err(Error::InvalidSecureContent(
"Keystore has resourcedatagroup elements but no consumer elements (EPX-2602)"
.to_string(),
));
}
// EPX-2602: Check if we have access rights but no consumers
let has_access_rights = sc
.resource_data_groups
.iter()
.any(|g| !g.access_rights.is_empty());
if has_access_rights && sc.consumer_count == 0 {
return Err(Error::InvalidSecureContent(
"Keystore has accessright elements but no consumer elements (EPX-2602)".to_string(),
));
}
// EPX-2601: Validate all consumer indices
for group in &sc.resource_data_groups {
for access_right in &group.access_rights {
if access_right.consumer_index >= sc.consumer_count {
return Err(Error::InvalidSecureContent(format!(
"Invalid consumer index {}. Only {} consumer(s) defined (EPX-2601)",
access_right.consumer_index, sc.consumer_count
)));
}
}
}
// EPX-2606: Validate encrypted files have EncryptedFile relationships
// Per 3MF SecureContent specification, all encrypted files referenced by
// resourcedata elements MUST have an EncryptedFile relationship in the OPC package
for group in &sc.resource_data_groups {
for resource_data in &group.resource_data {
let encrypted_path = &resource_data.path;
// Check if this encrypted file has an EncryptedFile relationship
// We don't specify a source file since the relationship could be in any .rels file
let has_encrypted_rel = package.has_relationship_to_target(
encrypted_path,
ENCRYPTEDFILE_REL_TYPE,
None,
)?;
if !has_encrypted_rel {
return Err(Error::InvalidSecureContent(format!(
"Encrypted file '{}' is missing required EncryptedFile relationship. \
Per 3MF SecureContent specification, all encrypted files referenced in the keystore \
must have a corresponding EncryptedFile relationship in the OPC package (EPX-2606)",
encrypted_path
)));
}
}
}
}
Ok(())
}
/// Load a file from the package, decrypting if it's an encrypted file
///
/// This function checks if the file is in the encrypted files list, and if so,
/// attempts to decrypt it using test keys (for conformance testing only).
///
/// **Security Note**: This implementation uses hardcoded test keys suitable only
/// for conformance testing. Production implementations should use proper key
/// management and never store private keys in code.
///
/// If test keys are unavailable or decryption fails, an error is returned.
/// For non-encrypted files, the file is loaded normally from the package.
pub(super) fn load_file_with_decryption<R: Read + std::io::Seek>(
package: &mut Package<R>,
normalized_path: &str,
display_path: &str,
model: &Model,
config: &ParserConfig,
) -> Result<String> {
// Check if this file is encrypted
let is_encrypted = model
.secure_content
.as_ref()
.map(|sc| {
let path_with_slash = format!("/{}", normalized_path);
sc.encrypted_files.contains(&path_with_slash)
|| sc.encrypted_files.contains(&normalized_path.to_string())
})
.unwrap_or(false);
if !is_encrypted {
// Load normally
return package.get_file(normalized_path).map_err(|e| {
Error::InvalidXml(format!("Failed to load file '{}': {}", display_path, e))
});
}
// File is encrypted - decrypt it
let secure_content = model
.secure_content
.as_ref()
.ok_or_else(|| Error::InvalidSecureContent("No secure content info".to_string()))?;
// Load the encrypted file
let encrypted_data = package.get_file_binary(normalized_path).map_err(|e| {
Error::InvalidXml(format!(
"Failed to load encrypted file '{}': {}",
display_path, e
))
})?;
// Find the resource data for this file
let path_with_slash = format!("/{}", normalized_path);
let resource_data = secure_content
.resource_data_groups
.iter()
.flat_map(|group| &group.resource_data)
.find(|rd| rd.path == path_with_slash || rd.path == normalized_path)
.ok_or_else(|| {
Error::InvalidSecureContent(format!(
"No resource data found for encrypted file '{}'",
display_path
))
})?;
// Find an access right we can use
// First, try to use custom key provider if one is configured
// Otherwise, fall back to test consumer keys
let (access_right, _consumer_index) = secure_content
.resource_data_groups
.iter()
.find_map(|group| {
// Check if this group contains our resource
if group
.resource_data
.iter()
.any(|rd| rd.path == path_with_slash || rd.path == normalized_path)
{
// If custom key provider is configured, use the first access right
if config.key_provider().is_some() {
group.access_rights.first().map(|ar| (ar.clone(), 0))
} else {
// Otherwise, find an access right for the test consumer
group
.access_rights
.iter()
.enumerate()
.find(|(idx, _)| {
if *idx < secure_content.consumers.len() {
secure_content.consumers[*idx].consumer_id == TEST_CONSUMER_ID
} else {
false
}
})
.map(|(idx, ar)| (ar.clone(), idx))
}
} else {
None
}
})
.ok_or_else(|| {
if config.key_provider().is_some() {
Error::InvalidSecureContent(format!(
"No access right found for file '{}'",
display_path
))
} else {
Error::InvalidSecureContent(format!(
"No access right found for test consumer for file '{}'",
display_path
))
}
})?;
// Decrypt the file using custom provider or test keys
let decrypted = if let Some(provider) = config.key_provider() {
provider
.decrypt(
&encrypted_data,
&resource_data.cek_params,
&access_right,
secure_content,
)
.map_err(|e| {
Error::InvalidSecureContent(format!(
"Failed to decrypt file '{}' with custom key provider: {}",
display_path, e
))
})?
} else {
#[cfg(feature = "crypto")]
{
crate::decryption::decrypt_with_test_key(
&encrypted_data,
&resource_data.cek_params,
&access_right,
secure_content,
)
.map_err(|e| {
Error::InvalidSecureContent(format!(
"Failed to decrypt file '{}': {}",
display_path, e
))
})?
}
#[cfg(not(feature = "crypto"))]
{
return Err(Error::InvalidSecureContent(
"Decryption requires the 'crypto' feature to be enabled. \
Rebuild with --features crypto to enable test key decryption, \
or provide a custom KeyProvider."
.to_string(),
));
}
};
// Convert to string
String::from_utf8(decrypted).map_err(|e| {
Error::InvalidXml(format!(
"Decrypted file '{}' is not valid UTF-8: {}",
display_path, e
))
})
}
/// Validate that an encrypted file can be loaded and decrypted
///
/// This checks that:
/// - The file exists in the package
/// - The file can be decrypted using the test consumer keys
/// - The decrypted content is valid
pub(super) fn validate_encrypted_file_can_be_loaded<R: Read + std::io::Seek>(
package: &mut Package<R>,
normalized_path: &str,
display_path: &str,
model: &Model,
config: &ParserConfig,
context: &str,
) -> Result<()> {
// Check if file exists
if !package.has_file(normalized_path) {
return Err(Error::InvalidModel(format!(
"{}: References non-existent encrypted file: {}\n\
The p:path attribute must reference a valid encrypted file in the 3MF package.",
context, display_path
)));
}
// Attempt to load and decrypt the file
// This will fail if:
// - The consumer doesn't match test keys (consumerid != "test3mf01") when no custom provider
// - The keyid doesn't match (keyid != "test3mfkek01") when no custom provider
// - The consumer has no keyid when one is required
// - Custom key provider fails to decrypt
// - Any other decryption-related issue
let _decrypted_content =
load_file_with_decryption(package, normalized_path, display_path, model, config)?;
// If we got here, decryption succeeded - the file is valid
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{
AccessRight, CEKParams, Consumer, KEKParams, ResourceData, ResourceDataGroup,
};
use crate::opc::Package;
use std::io::{Cursor, Write};
use zip::ZipWriter;
use zip::write::SimpleFileOptions;
/// Create a minimal valid 3MF ZIP package with optional extra files.
/// The package contains [Content_Types].xml, _rels/.rels, and 3D/3dmodel.model.
fn make_test_package(extra_files: &[(&str, &[u8])]) -> Vec<u8> {
let model_xml = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<model unit=\"millimeter\" xmlns=\"http://schemas.microsoft.com/3dmanufacturing/core/2015/02\">\
<resources><object id=\"1\" type=\"model\">\
<mesh><vertices>\
<vertex x=\"0\" y=\"0\" z=\"0\"/>\
<vertex x=\"1\" y=\"0\" z=\"0\"/>\
<vertex x=\"0\" y=\"1\" z=\"0\"/>\
</vertices><triangles><triangle v1=\"0\" v2=\"1\" v3=\"2\"/></triangles></mesh>\
</object></resources><build><item objectid=\"1\"/></build></model>";
let content_types = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
<Default Extension=\"model\" ContentType=\"application/vnd.ms-package.3dmanufacturing-3dmodel+xml\"/>\
</Types>";
let rels = b"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
<Relationship Id=\"rId0\" Target=\"/3D/3dmodel.model\" \
Type=\"http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel\"/>\
</Relationships>";
let mut buf = Vec::new();
{
let mut zip = ZipWriter::new(Cursor::new(&mut buf));
let opts = SimpleFileOptions::default();
zip.start_file("[Content_Types].xml", opts).unwrap();
zip.write_all(content_types).unwrap();
zip.start_file("_rels/.rels", opts).unwrap();
zip.write_all(rels).unwrap();
zip.start_file("3D/3dmodel.model", opts).unwrap();
zip.write_all(model_xml).unwrap();
for (name, content) in extra_files {
zip.start_file(*name, opts).unwrap();
zip.write_all(content).unwrap();
}
zip.finish().unwrap();
}
buf
}
// -------------------------------------------------------------------------
// Tests for validate_kekparams_attributes
// -------------------------------------------------------------------------
#[test]
fn test_validate_kekparams_empty_inputs() {
let mut sc = SecureContentInfo::default();
assert!(validate_kekparams_attributes("", "", "", &mut sc).is_ok());
// empty wrapping algorithm is not pushed
assert!(sc.wrapping_algorithms.is_empty());
}
#[test]
fn test_validate_kekparams_2009_wrapping_algorithm() {
let mut sc = SecureContentInfo::default();
assert!(
validate_kekparams_attributes(VALID_WRAPPING_ALGORITHM_2009, "", "", &mut sc).is_ok()
);
assert_eq!(sc.wrapping_algorithms[0], VALID_WRAPPING_ALGORITHM_2009);
}
#[test]
fn test_validate_kekparams_2001_wrapping_algorithm() {
let mut sc = SecureContentInfo::default();
assert!(
validate_kekparams_attributes(VALID_WRAPPING_ALGORITHM_2001, "", "", &mut sc).is_ok()
);
assert_eq!(sc.wrapping_algorithms[0], VALID_WRAPPING_ALGORITHM_2001);
}
#[test]
fn test_validate_kekparams_all_valid_mgf_algorithms() {
for mgf in VALID_MGF_ALGORITHMS {
let mut sc = SecureContentInfo::default();
assert!(
validate_kekparams_attributes("", mgf, "", &mut sc).is_ok(),
"Expected {} to be valid",
mgf
);
}
}
#[test]
fn test_validate_kekparams_all_valid_digest_methods() {
for digest in VALID_DIGEST_METHODS {
let mut sc = SecureContentInfo::default();
assert!(
validate_kekparams_attributes("", "", digest, &mut sc).is_ok(),
"Expected {} to be valid",
digest
);
}
}
#[test]
fn test_validate_kekparams_invalid_wrapping_algorithm() {
let mut sc = SecureContentInfo::default();
let result = validate_kekparams_attributes("http://invalid/algorithm", "", "", &mut sc);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("wrapping"));
}
#[test]
fn test_validate_kekparams_invalid_mgf_algorithm() {
let mut sc = SecureContentInfo::default();
let result = validate_kekparams_attributes("", "http://invalid/mgf", "", &mut sc);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("mgfalgorithm"));
}
#[test]
fn test_validate_kekparams_invalid_digest_method() {
let mut sc = SecureContentInfo::default();
let result = validate_kekparams_attributes("", "", "http://invalid/digest", &mut sc);
assert!(result.is_err());
assert!(result.unwrap_err().to_string().contains("digestmethod"));
}
// -------------------------------------------------------------------------
// Tests for load_file_with_decryption
// -------------------------------------------------------------------------
#[test]
fn test_load_file_non_encrypted_model_no_secure_content() {
// When model has no secure_content, is_encrypted is false -> load normally
let bytes = make_test_package(&[("extra/data.txt", b"hello world")]);
let mut pkg = Package::open(Cursor::new(bytes)).unwrap();
let model = Model::new();
let config = ParserConfig::new();
let result = load_file_with_decryption(
&mut pkg,
"extra/data.txt",
"extra/data.txt",
&model,
&config,
);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "hello world");
}
#[test]
fn test_load_file_non_encrypted_path_not_in_encrypted_list() {
// When model has secure_content but the path is not in encrypted_files
let bytes = make_test_package(&[("3D/plain.model", b"<model/>")]);
let mut pkg = Package::open(Cursor::new(bytes)).unwrap();
let mut model = Model::new();
let mut sc = SecureContentInfo::default();
sc.encrypted_files.push("/3D/other_file.model".to_string());
model.secure_content = Some(sc);
let config = ParserConfig::new();
let result = load_file_with_decryption(
&mut pkg,
"3D/plain.model",
"3D/plain.model",
&model,
&config,
);
assert!(
result.is_ok(),
"Expected non-encrypted load, got: {:?}",
result.err()
);
}
#[test]
fn test_load_file_encrypted_no_resource_data_found() {
// File is in encrypted_files, but no resource_data_group contains it
let bytes = make_test_package(&[("3D/enc.model", b"encrypted bytes")]);
let mut pkg = Package::open(Cursor::new(bytes)).unwrap();
let mut model = Model::new();
let mut sc = SecureContentInfo::default();
sc.encrypted_files.push("/3D/enc.model".to_string());
sc.consumer_count = 1;
sc.consumers.push(Consumer {
consumer_id: TEST_CONSUMER_ID.to_string(),
key_id: None,
key_value: None,
});
// resource_data_groups is empty -> resource_data not found
model.secure_content = Some(sc);
let config = ParserConfig::new();
let result =
load_file_with_decryption(&mut pkg, "3D/enc.model", "/3D/enc.model", &model, &config);
assert!(result.is_err());
let msg = result.unwrap_err().to_string();
assert!(msg.contains("No resource data found"), "Got: {}", msg);
}
#[test]
fn test_load_file_encrypted_no_matching_access_right() {
// File is in encrypted_files, resource_data found, but consumer is not TEST_CONSUMER_ID
let bytes = make_test_package(&[("3D/enc.model", b"encrypted bytes")]);
let mut pkg = Package::open(Cursor::new(bytes)).unwrap();
let mut model = Model::new();
let mut sc = SecureContentInfo::default();
sc.encrypted_files.push("/3D/enc.model".to_string());
sc.consumer_count = 1;
sc.consumers.push(Consumer {
consumer_id: "other_consumer".to_string(), // not TEST_CONSUMER_ID
key_id: None,
key_value: None,
});
sc.consumer_ids.push("other_consumer".to_string());
let group = ResourceDataGroup {
key_uuid: "key-uuid".to_string(),
access_rights: vec![AccessRight {
consumer_index: 0,
kek_params: KEKParams {
wrapping_algorithm: String::new(),
mgf_algorithm: None,
digest_method: None,
},
cipher_value: "AAAA".to_string(),
}],
resource_data: vec![ResourceData {
path: "/3D/enc.model".to_string(),
cek_params: CEKParams {
encryption_algorithm: "aes256".to_string(),
compression: "none".to_string(),
iv: None,
tag: None,
aad: None,
},
}],
};
sc.resource_data_groups.push(group);
model.secure_content = Some(sc);
let config = ParserConfig::new(); // no key provider
let result =
load_file_with_decryption(&mut pkg, "3D/enc.model", "/3D/enc.model", &model, &config);
assert!(result.is_err());
let msg = result.unwrap_err().to_string();
assert!(
msg.contains("No access right"),
"Expected 'No access right' error, got: {}",
msg
);
}
#[cfg(not(feature = "crypto"))]
#[test]
fn test_load_file_encrypted_no_crypto_feature() {
// File is encrypted, access right matches test consumer, but crypto feature is disabled
let bytes = make_test_package(&[("3D/enc.model", b"encrypted bytes")]);
let mut pkg = Package::open(Cursor::new(bytes)).unwrap();
let mut model = Model::new();
let mut sc = SecureContentInfo::default();
sc.encrypted_files.push("/3D/enc.model".to_string());
sc.consumer_count = 1;
sc.consumers.push(Consumer {
consumer_id: TEST_CONSUMER_ID.to_string(),
key_id: None,
key_value: None,
});
sc.consumer_ids.push(TEST_CONSUMER_ID.to_string());
let group = ResourceDataGroup {
key_uuid: "key-uuid".to_string(),
access_rights: vec![AccessRight {
consumer_index: 0,
kek_params: KEKParams {
wrapping_algorithm: String::new(),
mgf_algorithm: None,
digest_method: None,
},
cipher_value: "AAAA".to_string(),
}],
resource_data: vec![ResourceData {
path: "/3D/enc.model".to_string(),
cek_params: CEKParams {
encryption_algorithm: "aes256".to_string(),
compression: "none".to_string(),
iv: None,
tag: None,
aad: None,
},
}],
};
sc.resource_data_groups.push(group);
model.secure_content = Some(sc);
let config = ParserConfig::new(); // no key provider, no crypto feature
let result =
load_file_with_decryption(&mut pkg, "3D/enc.model", "/3D/enc.model", &model, &config);
assert!(result.is_err());
let msg = result.unwrap_err().to_string();
assert!(
msg.contains("crypto") || msg.contains("feature"),
"Expected crypto-feature error, got: {}",
msg
);
}
// -------------------------------------------------------------------------
// Tests for validate_encrypted_file_can_be_loaded
// -------------------------------------------------------------------------
#[test]
fn test_validate_encrypted_file_not_found() {
// File does not exist in the package -> error
let bytes = make_test_package(&[]);
let mut pkg = Package::open(Cursor::new(bytes)).unwrap();
let model = Model::new();
let config = ParserConfig::new();
let result = validate_encrypted_file_can_be_loaded(
&mut pkg,
"3D/missing.model",
"/3D/missing.model",
&model,
&config,
"Test context",
);
assert!(result.is_err());
let msg = result.unwrap_err().to_string();
assert!(
msg.contains("non-existent") || msg.contains("missing") || msg.contains("Test context"),
"Got: {}",
msg
);
}
#[test]
fn test_validate_encrypted_file_success_non_encrypted() {
// File exists, model has no secure_content -> load_file_with_decryption takes non-encrypted
// path, succeeds. This exercises the success path of validate_encrypted_file_can_be_loaded.
let bytes = make_test_package(&[("3D/ext.model", b"<model/>")]);
let mut pkg = Package::open(Cursor::new(bytes)).unwrap();
let model = Model::new(); // no secure_content -> is_encrypted = false
let config = ParserConfig::new();
let result = validate_encrypted_file_can_be_loaded(
&mut pkg,
"3D/ext.model",
"/3D/ext.model",
&model,
&config,
"Test context",
);
assert!(result.is_ok(), "Expected success, got: {:?}", result.err());
}
}