greentic-pack-lib 1.1.1

Greentic pack builder and reader
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
use std::collections::BTreeSet;
use std::path::PathBuf;
use std::sync::Arc;

#[cfg(feature = "native")]
use std::fs;
#[cfg(feature = "native")]
use std::io::Write;
#[cfg(feature = "native")]
use std::path::Path;

#[cfg(feature = "native")]
use anyhow::Context;
#[cfg(feature = "native")]
use anyhow::anyhow;
use anyhow::{Result, bail};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use blake3::Hasher;
#[cfg(feature = "native")]
use ed25519_dalek::Signer as _;
#[cfg(feature = "native")]
use ed25519_dalek::SigningKey;
#[cfg(feature = "native")]
use getrandom::fill as fill_random;
use greentic_types::cbor::canonical;
#[cfg(feature = "native")]
use pkcs8::EncodePrivateKey;
#[cfg(feature = "native")]
use rcgen::{CertificateParams, DistinguishedName, DnType, KeyPair, PKCS_ED25519};
#[cfg(feature = "native")]
use rustls_pki_types::PrivatePkcs8KeyDer;
use schemars::JsonSchema;
use semver::Version;
use serde::{Deserialize, Serialize};
use serde_json::{Map as JsonMap, Value as JsonValue};
#[cfg(feature = "native")]
use time::OffsetDateTime;
#[cfg(feature = "native")]
use time::format_description::well_known::Rfc3339;
#[cfg(feature = "native")]
use zip::write::SimpleFileOptions;
#[cfg(feature = "native")]
use zip::{CompressionMethod, DateTime as ZipDateTime, ZipWriter};

use crate::events::EventsSection;
use crate::kind::PackKind;
use crate::messaging::MessagingSection;
use crate::repo::{InterfaceBinding, RepoPackSection};

// On native builds, re-export the canonical types from greentic-flow.
// On wasm (no-default-features), define minimal compatible types locally so
// that the entries() API surface compiles without pulling in wasmtime.
#[cfg(feature = "native")]
pub use greentic_flow::flow_bundle::{ComponentPin, FlowBundle, NodeRef};

#[cfg(not(feature = "native"))]
mod flow_bundle_wasm {
    use serde::{Deserialize, Serialize};
    use serde_json::Value;

    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct ComponentPin {
        pub name: String,
        pub version_req: String,
    }

    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct NodeRef {
        pub node_id: String,
        pub component: ComponentPin,
        pub schema_id: Option<String>,
    }

    #[derive(Clone, Debug, Serialize, Deserialize)]
    pub struct FlowBundle {
        pub id: String,
        pub kind: String,
        pub entry: String,
        pub yaml: String,
        pub json: Value,
        pub hash_blake3: String,
        pub nodes: Vec<NodeRef>,
    }
}

#[cfg(not(feature = "native"))]
pub use flow_bundle_wasm::{ComponentPin, FlowBundle, NodeRef};

pub(crate) const SBOM_FORMAT: &str = "greentic-sbom-v1";
pub(crate) const SIGNATURE_PATH: &str = "signatures/pack.sig";
pub(crate) const SIGNATURE_CHAIN_PATH: &str = "signatures/chain.pem";
pub const PACK_VERSION: u32 = 1;

fn default_pack_version() -> u32 {
    PACK_VERSION
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PackMeta {
    #[serde(rename = "packVersion", default = "default_pack_version")]
    pub pack_version: u32,
    pub pack_id: String,
    pub version: Version,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<PackKind>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub authors: Vec<String>,
    #[serde(default)]
    pub license: Option<String>,
    #[serde(default)]
    pub homepage: Option<String>,
    #[serde(default)]
    pub support: Option<String>,
    #[serde(default)]
    pub vendor: Option<String>,
    #[serde(default)]
    pub imports: Vec<ImportRef>,
    pub entry_flows: Vec<String>,
    pub created_at_utc: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub events: Option<EventsSection>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repo: Option<RepoPackSection>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub messaging: Option<MessagingSection>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub interfaces: Vec<InterfaceBinding>,
    #[serde(default)]
    pub annotations: JsonMap<String, JsonValue>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub distribution: Option<DistributionSection>,
    #[serde(default)]
    pub components: Vec<ComponentDescriptor>,
}

impl PackMeta {
    fn validate(&self) -> Result<()> {
        if self.pack_version != PACK_VERSION {
            bail!(
                "unsupported packVersion {}; expected {}",
                self.pack_version,
                PACK_VERSION
            );
        }
        if self.pack_id.trim().is_empty() {
            bail!("pack_id is required");
        }
        if self.name.trim().is_empty() {
            bail!("name is required");
        }
        if self.entry_flows.is_empty() {
            bail!("at least one entry flow is required");
        }
        if self.created_at_utc.trim().is_empty() {
            bail!("created_at_utc is required");
        }
        if let Some(kind) = &self.kind {
            kind.validate_allowed()?;
        }
        if let Some(events) = &self.events {
            events.validate()?;
        }
        if let Some(repo) = &self.repo {
            repo.validate()?;
        }
        if let Some(messaging) = &self.messaging {
            messaging.validate()?;
        }
        for binding in &self.interfaces {
            binding.validate("interfaces")?;
        }
        validate_distribution(self.kind.as_ref(), self.distribution.as_ref())?;
        validate_components(&self.components)?;
        Ok(())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ImportRef {
    pub pack_id: String,
    pub version_req: String,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct ComponentDescriptor {
    pub component_id: String,
    pub version: String,
    pub digest: String,
    pub artifact_path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub artifact_type: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platform: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entrypoint: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct DistributionSection {
    #[serde(default)]
    pub bundle_id: Option<String>,
    #[serde(default)]
    pub tenant: JsonMap<String, JsonValue>,
    pub environment_ref: String,
    pub desired_state_version: String,
    #[serde(default)]
    pub components: Vec<ComponentDescriptor>,
    #[serde(default)]
    pub platform_components: Vec<ComponentDescriptor>,
}

#[derive(Clone, Debug)]
pub struct ComponentArtifact {
    pub name: String,
    pub version: Version,
    pub wasm_path: PathBuf,
    pub schema_json: Option<String>,
    pub manifest_json: Option<String>,
    pub capabilities: Option<JsonValue>,
    pub world: Option<String>,
    pub hash_blake3: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Provenance {
    pub builder: String,
    #[serde(default)]
    pub git_commit: Option<String>,
    #[serde(default)]
    pub git_repo: Option<String>,
    #[serde(default)]
    pub toolchain: Option<String>,
    pub built_at_utc: String,
    #[serde(default)]
    pub host: Option<String>,
    #[serde(default)]
    pub notes: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExternalSignature {
    pub alg: String,
    pub sig: Vec<u8>,
}

pub trait Signer: Send + Sync {
    fn sign(&self, message: &[u8]) -> Result<ExternalSignature>;
    fn chain_pem(&self) -> Result<Vec<u8>>;
}

type DynSigner = dyn Signer + Send + Sync + 'static;

#[derive(Clone)]
pub enum Signing {
    #[cfg(feature = "native")]
    Dev,
    None,
    External(Arc<DynSigner>),
}

// Manual impl instead of derive because the default variant differs by feature flag.
#[allow(clippy::derivable_impls)]
impl Default for Signing {
    fn default() -> Self {
        #[cfg(feature = "native")]
        {
            Signing::Dev
        }
        #[cfg(not(feature = "native"))]
        {
            Signing::None
        }
    }
}

pub struct PackBuilder {
    meta: PackMeta,
    flows: Vec<FlowBundle>,
    components: Vec<ComponentArtifact>,
    assets: Vec<Asset>,
    signing: Signing,
    provenance: Option<Provenance>,
    component_descriptors: Vec<ComponentDescriptor>,
    distribution: Option<DistributionSection>,
}

#[derive(Clone)]
struct Asset {
    path: String,
    bytes: Vec<u8>,
}

#[derive(Debug, Clone)]
pub struct BuildResult {
    pub out_path: PathBuf,
    pub manifest_hash_blake3: String,
    pub files: Vec<SbomEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SbomEntry {
    pub path: String,
    pub size: u64,
    pub hash_blake3: String,
    pub media_type: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackManifest {
    pub meta: PackMeta,
    pub flows: Vec<FlowEntry>,
    pub components: Vec<ComponentEntry>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub distribution: Option<DistributionSection>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub component_descriptors: Vec<ComponentDescriptor>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowEntry {
    pub id: String,
    pub kind: String,
    pub entry: String,
    pub file_yaml: String,
    pub file_json: String,
    pub hash_blake3: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentEntry {
    pub name: String,
    pub version: Version,
    pub file_wasm: String,
    pub hash_blake3: String,
    pub schema_file: Option<String>,
    pub manifest_file: Option<String>,
    pub world: Option<String>,
    pub capabilities: Option<JsonValue>,
}

#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct SignatureEnvelope {
    pub alg: String,
    pub sig: String,
    pub digest: String,
    pub signed_at_utc: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_fingerprint: Option<String>,
}

impl SignatureEnvelope {
    fn new(
        alg: impl Into<String>,
        sig_bytes: &[u8],
        digest: &blake3::Hash,
        key_fingerprint: Option<String>,
    ) -> Self {
        #[cfg(feature = "native")]
        let signed_at = OffsetDateTime::now_utc()
            .format(&Rfc3339)
            .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string());
        #[cfg(not(feature = "native"))]
        let signed_at = "1970-01-01T00:00:00Z".to_string();

        Self {
            alg: alg.into(),
            sig: URL_SAFE_NO_PAD.encode(sig_bytes),
            digest: digest.to_hex().to_string(),
            signed_at_utc: signed_at,
            key_fingerprint,
        }
    }
}

struct PendingFile {
    path: String,
    media_type: String,
    bytes: Vec<u8>,
}

impl PendingFile {
    fn new(path: String, media_type: impl Into<String>, bytes: Vec<u8>) -> Self {
        Self {
            path,
            media_type: media_type.into(),
            bytes,
        }
    }

    fn size(&self) -> u64 {
        self.bytes.len() as u64
    }

    fn hash(&self) -> String {
        hex_hash(&self.bytes)
    }
}

impl PackBuilder {
    pub fn new(meta: PackMeta) -> Self {
        Self {
            component_descriptors: meta.components.clone(),
            distribution: meta.distribution.clone(),
            meta,
            flows: Vec::new(),
            components: Vec::new(),
            assets: Vec::new(),
            signing: Signing::default(),
            provenance: None,
        }
    }

    pub fn with_flow(mut self, flow: FlowBundle) -> Self {
        self.flows.push(flow);
        self
    }

    pub fn with_component(mut self, component: ComponentArtifact) -> Self {
        self.components.push(component);
        self
    }

    pub fn with_component_wasm(
        self,
        name: impl Into<String>,
        version: Version,
        wasm_path: impl Into<PathBuf>,
    ) -> Self {
        self.with_component(ComponentArtifact {
            name: name.into(),
            version,
            wasm_path: wasm_path.into(),
            schema_json: None,
            manifest_json: None,
            capabilities: None,
            world: None,
            hash_blake3: None,
        })
    }

    pub fn with_asset_bytes(mut self, path_in_pack: impl Into<String>, bytes: Vec<u8>) -> Self {
        self.assets.push(Asset {
            path: path_in_pack.into(),
            bytes,
        });
        self
    }

    pub fn with_signing(mut self, signing: Signing) -> Self {
        self.signing = signing;
        self
    }

    pub fn with_provenance(mut self, provenance: Provenance) -> Self {
        self.provenance = Some(provenance);
        self
    }

    pub fn with_component_descriptors(
        mut self,
        descriptors: impl IntoIterator<Item = ComponentDescriptor>,
    ) -> Self {
        self.component_descriptors.extend(descriptors);
        self
    }

    pub fn with_distribution(mut self, distribution: DistributionSection) -> Self {
        self.distribution = Some(distribution);
        self
    }

    /// Returns every in-archive file keyed by archive path, in deterministic (sorted) order.
    /// Includes flows, components, assets, manifest.cbor/json, provenance.json, sbom.json,
    /// and signature files when signing is not None.
    pub fn entries(&self) -> Result<std::collections::BTreeMap<String, Vec<u8>>> {
        let meta = &self.meta;
        meta.validate()?;
        let distribution = self
            .distribution
            .clone()
            .or_else(|| meta.distribution.clone());
        let component_descriptors = if self.component_descriptors.is_empty() {
            meta.components.clone()
        } else {
            self.component_descriptors.clone()
        };

        if self.flows.is_empty() {
            bail!("at least one flow must be provided");
        }

        let mut flow_entries = Vec::new();
        let mut pending_files: Vec<PendingFile> = Vec::new();
        let mut seen_flow_ids = BTreeSet::new();

        for flow in &self.flows {
            validate_identifier(&flow.id, "flow id")?;
            if flow.entry.trim().is_empty() {
                bail!("flow {} is missing an entry node", flow.id);
            }
            if !seen_flow_ids.insert(flow.id.clone()) {
                bail!("duplicate flow id detected: {}", flow.id);
            }

            let yaml_path = normalize_relative_path(&["flows", &flow.id, "flow.ygtc"])?;
            let yaml_bytes = normalize_newlines(&flow.yaml).into_bytes();
            pending_files.push(PendingFile::new(
                yaml_path.clone(),
                "application/yaml",
                yaml_bytes,
            ));

            let json_path = normalize_relative_path(&["flows", &flow.id, "flow.json"])?;
            let json_bytes = serde_json::to_vec(&flow.json)?;
            pending_files.push(PendingFile::new(
                json_path.clone(),
                "application/json",
                json_bytes,
            ));

            flow_entries.push(FlowEntry {
                id: flow.id.clone(),
                kind: flow.kind.clone(),
                entry: flow.entry.clone(),
                file_yaml: yaml_path,
                file_json: json_path,
                hash_blake3: flow.hash_blake3.clone(),
            });
        }

        for entry in &meta.entry_flows {
            if !seen_flow_ids.contains(entry) {
                bail!("entry flow `{}` not present in provided flows", entry);
            }
        }

        flow_entries.sort_by(|a, b| a.id.cmp(&b.id));

        let mut component_entries: Vec<ComponentEntry> = Vec::new();
        #[cfg(feature = "native")]
        let mut seen_components: BTreeSet<String> = BTreeSet::new();

        #[cfg(feature = "native")]
        for component in &self.components {
            validate_identifier(&component.name, "component name")?;
            let key = format!("{}@{}", component.name, component.version);
            if !seen_components.insert(key.clone()) {
                bail!("duplicate component artifact detected: {}", key);
            }

            let wasm_bytes = fs::read(&component.wasm_path).with_context(|| {
                format!(
                    "failed to read component wasm at {}",
                    component.wasm_path.display()
                )
            })?;
            let wasm_hash = hex_hash(&wasm_bytes);
            if let Some(expected) = component.hash_blake3.as_deref()
                && !equals_ignore_case(expected, &wasm_hash)
            {
                bail!(
                    "component {} hash mismatch: expected {}, got {}",
                    key,
                    expected,
                    wasm_hash
                );
            }

            let wasm_path = normalize_relative_path(&["components", &key, "component.wasm"])?;
            pending_files.push(PendingFile::new(
                wasm_path.clone(),
                "application/wasm",
                wasm_bytes,
            ));

            let mut schema_file = None;
            if let Some(schema) = component.schema_json.as_ref() {
                let schema_path = normalize_relative_path(&["schemas", &key, "node.schema.json"])?;
                pending_files.push(PendingFile::new(
                    schema_path.clone(),
                    "application/schema+json",
                    normalize_newlines(schema).into_bytes(),
                ));
                schema_file = Some(schema_path);
            }

            let mut manifest_file = None;
            if let Some(manifest_json) = component.manifest_json.as_ref() {
                let manifest_path =
                    normalize_relative_path(&["components", &key, "manifest.json"])?;
                pending_files.push(PendingFile::new(
                    manifest_path.clone(),
                    "application/json",
                    normalize_newlines(manifest_json).into_bytes(),
                ));
                manifest_file = Some(manifest_path);
            }

            component_entries.push(ComponentEntry {
                name: component.name.clone(),
                version: component.version.clone(),
                file_wasm: wasm_path,
                hash_blake3: wasm_hash,
                schema_file,
                manifest_file,
                world: component.world.clone(),
                capabilities: component.capabilities.clone(),
            });
        }
        #[cfg(not(feature = "native"))]
        if !self.components.is_empty() {
            bail!("component wasm loading requires the `native` feature");
        }

        component_entries
            .sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.version.cmp(&b.version)));

        for asset in &self.assets {
            let path = normalize_relative_path(&["assets", &asset.path])?;
            pending_files.push(PendingFile::new(
                path,
                "application/octet-stream",
                asset.bytes.clone(),
            ));
        }

        let manifest_model = PackManifest {
            meta: meta.clone(),
            flows: flow_entries,
            components: component_entries,
            distribution,
            component_descriptors,
        };

        let manifest_cbor = encode_manifest_cbor(&manifest_model)?;
        let manifest_json = serde_json::to_vec_pretty(&manifest_model)?;

        pending_files.push(PendingFile::new(
            "manifest.cbor".to_string(),
            "application/cbor",
            manifest_cbor.clone(),
        ));
        pending_files.push(PendingFile::new(
            "manifest.json".to_string(),
            "application/json",
            manifest_json,
        ));

        let provenance = finalize_provenance(self.provenance.clone());
        let provenance_json = serde_json::to_vec_pretty(&provenance)?;
        pending_files.push(PendingFile::new(
            "provenance.json".to_string(),
            "application/json",
            provenance_json,
        ));

        let mut sbom_entries = Vec::new();
        for file in pending_files.iter() {
            sbom_entries.push(SbomEntry {
                path: file.path.clone(),
                size: file.size(),
                hash_blake3: file.hash(),
                media_type: file.media_type.clone(),
            });
        }

        let sbom_document = serde_json::json!({
            "format": SBOM_FORMAT,
            "files": sbom_entries,
        });
        let sbom_bytes = serde_json::to_vec_pretty(&sbom_document)?;
        pending_files.push(PendingFile::new(
            "sbom.json".to_string(),
            "application/json",
            sbom_bytes.clone(),
        ));

        let mut signature_files = Vec::new();
        if !matches!(self.signing, Signing::None) {
            let digest = signature_digest_from_entries(&sbom_entries, &manifest_cbor, &sbom_bytes);
            let (signature_doc, chain_bytes) = match &self.signing {
                #[cfg(feature = "native")]
                Signing::Dev => dev_signature(&digest)?,
                Signing::None => bail!("internal: signing block entered with Signing::None"),
                Signing::External(signer) => external_signature(&**signer, &digest)?,
            };

            let sig_bytes = serde_json::to_vec_pretty(&signature_doc)?;
            signature_files.push(PendingFile::new(
                SIGNATURE_PATH.to_string(),
                "application/json",
                sig_bytes,
            ));

            if let Some(chain) = chain_bytes {
                signature_files.push(PendingFile::new(
                    SIGNATURE_CHAIN_PATH.to_string(),
                    "application/x-pem-file",
                    chain,
                ));
            }
        }

        let mut all_files = pending_files;
        all_files.extend(signature_files);

        // BTreeMap provides sorted iteration by key — matches the original sort_by path.
        let mut map = std::collections::BTreeMap::new();
        for f in all_files {
            map.insert(f.path, f.bytes);
        }
        Ok(map)
    }

    #[cfg(feature = "native")]
    pub fn build(self, out_path: impl AsRef<Path>) -> Result<BuildResult> {
        let entries = self.entries()?;

        // build_files = SBOM of content files only (excludes sbom.json and signature files),
        // matching what the original code captured before adding those to pending_files.
        let excluded = ["sbom.json", SIGNATURE_PATH, SIGNATURE_CHAIN_PATH];
        let build_files: Vec<SbomEntry> = entries
            .iter()
            .filter(|(path, _)| !excluded.contains(&path.as_str()))
            .map(|(path, bytes)| SbomEntry {
                path: path.clone(),
                size: bytes.len() as u64,
                hash_blake3: hex_hash(bytes),
                media_type: media_type_for(path).to_string(),
            })
            .collect();

        let manifest_hash = entries
            .get("manifest.cbor")
            .map(|b| hex_hash(b))
            .ok_or_else(|| anyhow!("manifest.cbor missing from PackBuilder::entries()"))?;

        let pending: Vec<PendingFile> = entries
            .into_iter()
            .map(|(path, bytes)| {
                let mt = media_type_for(&path);
                PendingFile::new(path, mt, bytes)
            })
            .collect();

        let out_path = out_path.as_ref().to_path_buf();
        if let Some(parent) = out_path.parent() {
            fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory {}", parent.display()))?;
        }

        write_zip(&out_path, &pending)?;

        Ok(BuildResult {
            out_path,
            manifest_hash_blake3: manifest_hash,
            files: build_files,
        })
    }
}

#[cfg(feature = "native")]
fn equals_ignore_case(expected: &str, actual: &str) -> bool {
    expected.trim().eq_ignore_ascii_case(actual.trim())
}

fn normalize_newlines(input: &str) -> String {
    input.replace("\r\n", "\n")
}

fn normalize_relative_path(parts: &[&str]) -> Result<String> {
    let mut segments = Vec::new();
    for part in parts {
        let normalized = part.replace('\\', "/");
        for piece in normalized.split('/') {
            if piece.is_empty() {
                bail!("invalid path segment");
            }
            if piece == "." || piece == ".." {
                bail!("path traversal is not permitted");
            }
            segments.push(piece.to_string());
        }
    }
    Ok(segments.join("/"))
}

fn validate_identifier(value: &str, label: &str) -> Result<()> {
    if value.trim().is_empty() {
        bail!("{} must not be empty", label);
    }
    if value.contains("..") {
        bail!("{} must not contain '..'", label);
    }
    Ok(())
}

fn encode_manifest_cbor(manifest: &PackManifest) -> Result<Vec<u8>> {
    canonical::to_canonical_cbor_allow_floats(manifest).map_err(Into::into)
}

fn validate_digest(digest: &str) -> Result<()> {
    if digest.trim().is_empty() {
        bail!("component digest must not be empty");
    }
    if !digest.starts_with("sha256:") {
        bail!("component digest must start with sha256:");
    }
    Ok(())
}

fn validate_component_descriptor(component: &ComponentDescriptor) -> Result<()> {
    if component.component_id.trim().is_empty() {
        bail!("component_id must not be empty");
    }
    if component.version.trim().is_empty() {
        bail!("component version must not be empty");
    }
    if component.artifact_path.trim().is_empty() {
        bail!("component artifact_path must not be empty");
    }
    validate_digest(&component.digest)?;
    if let Some(kind) = &component.kind
        && kind.trim().is_empty()
    {
        bail!("component kind must not be empty when provided");
    }
    if let Some(artifact_type) = &component.artifact_type
        && artifact_type.trim().is_empty()
    {
        bail!("component artifact_type must not be empty when provided");
    }
    if let Some(platform) = &component.platform
        && platform.trim().is_empty()
    {
        bail!("component platform must not be empty when provided");
    }
    if let Some(entrypoint) = &component.entrypoint
        && entrypoint.trim().is_empty()
    {
        bail!("component entrypoint must not be empty when provided");
    }
    for tag in &component.tags {
        if tag.trim().is_empty() {
            bail!("component tags must not contain empty entries");
        }
    }
    Ok(())
}

pub fn validate_components(components: &[ComponentDescriptor]) -> Result<()> {
    let mut seen = BTreeSet::new();
    for component in components {
        validate_component_descriptor(component)?;
        let key = (component.component_id.clone(), component.version.clone());
        if !seen.insert(key) {
            bail!("duplicate component entry detected");
        }
    }
    Ok(())
}

pub fn validate_distribution(
    kind: Option<&PackKind>,
    distribution: Option<&DistributionSection>,
) -> Result<()> {
    match (kind, distribution) {
        (Some(PackKind::DistributionBundle), Some(section)) => {
            if let Some(bundle_id) = &section.bundle_id
                && bundle_id.trim().is_empty()
            {
                bail!("distribution.bundle_id must not be empty when provided");
            }
            if section.environment_ref.trim().is_empty() {
                bail!("distribution.environment_ref must not be empty");
            }
            if section.desired_state_version.trim().is_empty() {
                bail!("distribution.desired_state_version must not be empty");
            }
            validate_components(&section.components)?;
            validate_components(&section.platform_components)?;
        }
        (Some(PackKind::DistributionBundle), None) => {
            bail!("distribution section is required for kind distribution-bundle");
        }
        (_, Some(_)) => {
            bail!("distribution section is only allowed when kind is distribution-bundle");
        }
        _ => {}
    }
    Ok(())
}

fn finalize_provenance(provenance: Option<Provenance>) -> Provenance {
    let builder_default = format!("greentic-pack@{}", env!("CARGO_PKG_VERSION"));

    #[cfg(feature = "native")]
    let now = OffsetDateTime::now_utc()
        .format(&Rfc3339)
        .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string());
    #[cfg(not(feature = "native"))]
    let now = "1970-01-01T00:00:00Z".to_string();

    match provenance {
        Some(mut prov) => {
            if prov.builder.trim().is_empty() {
                prov.builder = builder_default;
            }
            if prov.built_at_utc.trim().is_empty() {
                prov.built_at_utc = now;
            }
            prov
        }
        None => Provenance {
            builder: builder_default,
            git_commit: None,
            git_repo: None,
            toolchain: None,
            built_at_utc: now,
            host: None,
            notes: None,
        },
    }
}

pub(crate) fn signature_digest_from_entries(
    entries: &[SbomEntry],
    manifest_cbor: &[u8],
    sbom_bytes: &[u8],
) -> blake3::Hash {
    let mut hasher = Hasher::new();
    hasher.update(manifest_cbor);
    hasher.update(sbom_bytes);

    let mut records: Vec<(String, String)> = entries
        .iter()
        .map(|entry| (entry.path.clone(), entry.hash_blake3.clone()))
        .collect();
    records.sort_by(|a, b| a.0.cmp(&b.0));

    for (path, hash) in records {
        hasher.update(path.as_bytes());
        hasher.update(b"\n");
        hasher.update(hash.as_bytes());
    }

    hasher.finalize()
}

#[cfg(feature = "native")]
fn dev_signature(digest: &blake3::Hash) -> Result<(SignatureEnvelope, Option<Vec<u8>>)> {
    let mut secret = [0u8; 32];
    fill_random(&mut secret).map_err(|err| anyhow!("failed to generate dev signing key: {err}"))?;
    let signing_key = SigningKey::from_bytes(&secret);
    let signature = signing_key.sign(digest.as_bytes());
    let signature_bytes = signature.to_bytes();

    let pkcs8_doc = signing_key
        .to_pkcs8_der()
        .map_err(|err| anyhow!("failed to encode dev keypair: {err}"))?;
    let pkcs8_der = PrivatePkcs8KeyDer::from(pkcs8_doc.as_bytes().to_vec());
    let key_pair = KeyPair::from_pkcs8_der_and_sign_algo(&pkcs8_der, &PKCS_ED25519)
        .map_err(|err| anyhow!("failed to load dev keypair for certificate: {err}"))?;

    let mut params = CertificateParams::new(Vec::<String>::new())?;
    params.distinguished_name = DistinguishedName::new();
    params
        .distinguished_name
        .push(DnType::CommonName, "greentic-dev-local");
    let cert = params.self_signed(&key_pair)?;
    let chain = normalize_newlines(&cert.pem()).into_bytes();
    let fingerprint = hex_hash(signing_key.verifying_key().as_bytes());

    let envelope = SignatureEnvelope::new("ed25519", &signature_bytes, digest, Some(fingerprint));
    Ok((envelope, Some(chain)))
}

fn external_signature(
    signer: &DynSigner,
    digest: &blake3::Hash,
) -> Result<(SignatureEnvelope, Option<Vec<u8>>)> {
    let ExternalSignature { alg, sig } = signer.sign(digest.as_bytes())?;
    let chain = signer.chain_pem()?;
    let chain_bytes = if chain.is_empty() {
        None
    } else {
        let chain_str = String::from_utf8(chain)?;
        Some(normalize_newlines(&chain_str).into_bytes())
    };
    let envelope = SignatureEnvelope::new(alg, &sig, digest, None);
    Ok((envelope, chain_bytes))
}

pub(crate) fn hex_hash(bytes: &[u8]) -> String {
    blake3::hash(bytes).to_hex().to_string()
}

#[cfg(feature = "native")]
fn media_type_for(path: &str) -> &'static str {
    if path.ends_with(".ygtc") {
        "application/yaml"
    } else if path.starts_with("schemas/") && path.ends_with(".json") {
        "application/schema+json"
    } else if path.ends_with(".json") {
        "application/json"
    } else if path.ends_with(".cbor") {
        "application/cbor"
    } else if path.ends_with(".wasm") {
        "application/wasm"
    } else if path.ends_with(".pem") {
        "application/x-pem-file"
    } else {
        "application/octet-stream"
    }
}

#[cfg(feature = "native")]
fn write_zip(out_path: &Path, files: &[PendingFile]) -> Result<()> {
    let file = fs::File::create(out_path)
        .with_context(|| format!("failed to create {}", out_path.display()))?;
    let mut writer = ZipWriter::new(file);
    let timestamp = zip_timestamp();

    for entry in files {
        let options = SimpleFileOptions::default()
            .compression_method(CompressionMethod::Stored)
            .last_modified_time(timestamp)
            .unix_permissions(0o644)
            .large_file(false);
        writer
            .start_file(&entry.path, options)
            .with_context(|| format!("failed to add {} to archive", entry.path))?;
        writer
            .write_all(&entry.bytes)
            .with_context(|| format!("failed to write {}", entry.path))?;
    }

    writer.finish().context("failed to finish gtpack archive")?;
    Ok(())
}

#[cfg(feature = "native")]
fn zip_timestamp() -> ZipDateTime {
    ZipDateTime::from_date_and_time(1980, 1, 1, 0, 0, 0).unwrap_or_else(|_| ZipDateTime::default())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use tempfile::tempdir;
    use zip::ZipArchive;

    use std::fs::{self, File};
    use std::io::Read;

    #[test]
    fn deterministic_build_without_signing() {
        let temp = tempdir().unwrap();
        let wasm_path = temp.path().join("component.wasm");
        fs::write(&wasm_path, test_wasm_bytes()).unwrap();

        let builder = || {
            PackBuilder::new(sample_meta())
                .with_flow(sample_flow())
                .with_component(sample_component(&wasm_path))
                .with_signing(Signing::None)
                .with_provenance(sample_provenance())
        };

        let out_a = temp.path().join("a.gtpack");
        let out_b = temp.path().join("b.gtpack");

        builder().build(&out_a).unwrap();
        builder().build(&out_b).unwrap();

        let bytes_a = fs::read(&out_a).unwrap();
        let bytes_b = fs::read(&out_b).unwrap();
        assert_eq!(bytes_a, bytes_b, "gtpack output should be deterministic");

        let result = PackBuilder::new(sample_meta())
            .with_flow(sample_flow())
            .with_component(sample_component(&wasm_path))
            .with_signing(Signing::None)
            .with_provenance(sample_provenance())
            .build(temp.path().join("result.gtpack"))
            .unwrap();

        assert!(
            result
                .files
                .iter()
                .any(|entry| entry.path == "components/oauth@1.0.0/component.wasm")
        );
    }

    #[test]
    fn dev_signing_writes_signature_files() {
        let temp = tempdir().unwrap();
        let wasm_path = temp.path().join("component.wasm");
        fs::write(&wasm_path, test_wasm_bytes()).unwrap();

        let out_path = temp.path().join("signed.gtpack");
        PackBuilder::new(sample_meta())
            .with_flow(sample_flow())
            .with_component(sample_component(&wasm_path))
            .with_signing(Signing::Dev)
            .with_provenance(sample_provenance())
            .build(&out_path)
            .unwrap();

        let reader = File::open(&out_path).unwrap();
        let mut archive = ZipArchive::new(reader).unwrap();
        let mut signature_found = false;
        let mut chain_found = false;

        for i in 0..archive.len() {
            let mut file = archive.by_index(i).unwrap();
            match file.name() {
                SIGNATURE_PATH => {
                    signature_found = true;
                    let mut contents = String::new();
                    file.read_to_string(&mut contents).unwrap();
                    assert!(contents.contains("\"alg\": \"ed25519\""));
                }
                SIGNATURE_CHAIN_PATH => {
                    chain_found = true;
                }
                _ => {}
            }
        }

        assert!(signature_found, "signature should be present");
        assert!(chain_found, "certificate chain should be present");
    }

    fn sample_meta() -> PackMeta {
        PackMeta {
            pack_version: PACK_VERSION,
            pack_id: "ai.greentic.demo.test".to_string(),
            version: Version::parse("0.1.0").unwrap(),
            name: "Test Pack".to_string(),
            kind: None,
            description: Some("integration test".to_string()),
            authors: vec!["Greentic".to_string()],
            license: Some("MIT".to_string()),
            homepage: None,
            support: None,
            vendor: None,
            imports: Vec::new(),
            entry_flows: vec!["main".to_string()],
            created_at_utc: "2025-01-01T00:00:00Z".to_string(),
            events: None,
            repo: None,
            messaging: None,
            interfaces: Vec::new(),
            annotations: JsonMap::new(),
            distribution: None,
            components: Vec::new(),
        }
    }

    fn sample_flow() -> FlowBundle {
        let flow_json = json!({
            "id": "main",
            "kind": "flow/v1",
            "entry": "start",
            "nodes": []
        });
        let hash = blake3::hash(&serde_json::to_vec(&flow_json).unwrap())
            .to_hex()
            .to_string();
        FlowBundle {
            id: "main".to_string(),
            kind: "flow/v1".to_string(),
            entry: "start".to_string(),
            yaml: "id: main\nentry: start\n".to_string(),
            json: flow_json,
            hash_blake3: hash,
            nodes: Vec::new(),
        }
    }

    fn sample_component(wasm_path: &Path) -> ComponentArtifact {
        ComponentArtifact {
            name: "oauth".to_string(),
            version: Version::parse("1.0.0").unwrap(),
            wasm_path: wasm_path.to_path_buf(),
            schema_json: None,
            manifest_json: None,
            capabilities: None,
            world: Some("component:tool".to_string()),
            hash_blake3: None,
        }
    }

    fn test_wasm_bytes() -> Vec<u8> {
        vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]
    }

    fn sample_provenance() -> Provenance {
        Provenance {
            builder: "greentic-pack@test".to_string(),
            git_commit: Some("abc123".to_string()),
            git_repo: Some("https://example.com/repo.git".to_string()),
            toolchain: Some("rustc 1.85.0".to_string()),
            built_at_utc: "2025-01-01T00:00:00Z".to_string(),
            host: Some("ci".to_string()),
            notes: None,
        }
    }

    #[test]
    fn entries_contains_manifest_and_assets_without_fs() {
        let meta = sample_meta();
        let builder = PackBuilder::new(meta)
            .with_signing(Signing::None)
            .with_flow(sample_flow())
            .with_asset_bytes("x.json", b"{}".to_vec());
        let entries = builder.entries().expect("entries");
        assert!(entries.contains_key("manifest.cbor"));
        assert!(entries.contains_key("manifest.json"));
        assert!(entries.contains_key("assets/x.json"));
        // deterministic ordering
        let keys: Vec<_> = entries.keys().cloned().collect();
        let mut sorted = keys.clone();
        sorted.sort();
        assert_eq!(keys, sorted);
    }
}