1use crate::cli::resolve::{self, ResolveArgs};
2use crate::config::{
3 AssetConfig, ComponentConfig, ComponentOperationConfig, FlowConfig, PackConfig,
4};
5use crate::extension_refs::{
6 default_extensions_file_path, default_extensions_lock_file_path, read_extensions_file,
7 read_extensions_lock_file, validate_extensions_lock_alignment,
8};
9use crate::extensions::{
10 validate_capabilities_extension, validate_components_extension, validate_deployer_extension,
11 validate_static_routes_extension,
12};
13use crate::flow_resolve::load_flow_resolve_summary;
14use crate::runtime::{NetworkPolicy, RuntimeContext};
15use anyhow::{Context, Result, anyhow};
16use greentic_distributor_client::{DistClient, DistOptions};
17use greentic_flow::add_step::normalize::normalize_node_map;
18use greentic_flow::compile_ygtc_file;
19use greentic_flow::loader::load_ygtc_from_path;
20use greentic_pack::builder::SbomEntry;
21use greentic_pack::pack_lock::read_pack_lock;
22use greentic_types::cbor::canonical;
23use greentic_types::component_source::ComponentSourceRef;
24use greentic_types::flow_resolve_summary::FlowResolveSummaryV1;
25use greentic_types::pack::extensions::component_manifests::{
26 ComponentManifestIndexEntryV1, ComponentManifestIndexV1, EXT_COMPONENT_MANIFEST_INDEX_V1,
27 ManifestEncoding,
28};
29use greentic_types::pack::extensions::component_sources::{
30 ArtifactLocationV1, ComponentSourceEntryV1, ComponentSourcesV1, EXT_COMPONENT_SOURCES_V1,
31 ResolvedComponentV1,
32};
33use greentic_types::pack_manifest::{ExtensionInline as PackManifestExtensionInline, ExtensionRef};
34use greentic_types::{
35 BootstrapSpec, ComponentCapability, ComponentConfigurators, ComponentId, ComponentManifest,
36 ComponentOperation, ExtensionInline, Flow, FlowId, PackDependency, PackFlowEntry, PackId,
37 PackKind, PackManifest, PackSignatures, SecretRequirement, SecretScope, SemverReq,
38 encode_pack_manifest,
39};
40use semver::Version;
41use serde::Serialize;
42use serde_cbor;
43use serde_json::json;
44use serde_yaml_bw::Value as YamlValue;
45use sha2::{Digest, Sha256};
46use std::collections::{BTreeMap, BTreeSet};
47use std::fs;
48use std::io::Write;
49use std::path::{Path, PathBuf};
50use std::str::FromStr;
51use tracing::{info, warn};
52use walkdir::WalkDir;
53use zip::write::SimpleFileOptions;
54use zip::{CompressionMethod, ZipWriter};
55
56const SBOM_FORMAT: &str = "greentic-sbom-v1";
57const EXT_BUILD_MODE_ID: &str = "greentic.pack-mode.v1";
58
59#[derive(Serialize)]
60struct SbomDocument {
61 format: String,
62 files: Vec<SbomEntry>,
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
66pub enum BundleMode {
67 Cache,
68 None,
69}
70
71#[derive(Clone)]
72pub struct BuildOptions {
73 pub pack_dir: PathBuf,
74 pub component_out: Option<PathBuf>,
75 pub manifest_out: PathBuf,
76 pub sbom_out: Option<PathBuf>,
77 pub gtpack_out: Option<PathBuf>,
78 pub lock_path: PathBuf,
79 pub bundle: BundleMode,
80 pub dry_run: bool,
81 pub secrets_req: Option<PathBuf>,
82 pub default_secret_scope: Option<String>,
83 pub allow_oci_tags: bool,
84 pub require_component_manifests: bool,
85 pub no_extra_dirs: bool,
86 pub dev: bool,
87 pub runtime: RuntimeContext,
88 pub skip_update: bool,
89 pub allow_pack_schema: bool,
90 pub validate_extension_refs: bool,
91}
92
93impl BuildOptions {
94 pub fn from_args(args: crate::BuildArgs, runtime: &RuntimeContext) -> Result<Self> {
95 let pack_dir = args
96 .input
97 .canonicalize()
98 .with_context(|| format!("failed to canonicalize pack dir {}", args.input.display()))?;
99
100 let component_out = args
101 .component_out
102 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) });
103 let manifest_out = args
104 .manifest
105 .map(|p| if p.is_relative() { pack_dir.join(p) } else { p })
106 .unwrap_or_else(|| pack_dir.join("dist").join("manifest.cbor"));
107 let sbom_out = args
108 .sbom
109 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) });
110 let default_gtpack_name = pack_dir
111 .file_name()
112 .and_then(|name| name.to_str())
113 .unwrap_or("pack");
114 let default_gtpack_out = pack_dir
115 .join("dist")
116 .join(format!("{default_gtpack_name}.gtpack"));
117 let gtpack_out = Some(
118 args.gtpack_out
119 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) })
120 .unwrap_or(default_gtpack_out),
121 );
122 let lock_path = args
123 .lock
124 .map(|p| if p.is_absolute() { p } else { pack_dir.join(p) })
125 .unwrap_or_else(|| pack_dir.join("pack.lock.cbor"));
126
127 Ok(Self {
128 pack_dir,
129 component_out,
130 manifest_out,
131 sbom_out,
132 gtpack_out,
133 lock_path,
134 bundle: args.bundle,
135 dry_run: args.dry_run,
136 secrets_req: args.secrets_req,
137 default_secret_scope: args.default_secret_scope,
138 allow_oci_tags: args.allow_oci_tags,
139 require_component_manifests: args.require_component_manifests,
140 no_extra_dirs: args.no_extra_dirs,
141 dev: args.dev,
142 runtime: runtime.clone(),
143 skip_update: args.no_update,
144 allow_pack_schema: args.allow_pack_schema,
145 validate_extension_refs: true,
146 })
147 }
148}
149
150pub async fn run(opts: &BuildOptions) -> Result<()> {
151 info!(
152 pack_dir = %opts.pack_dir.display(),
153 manifest_out = %opts.manifest_out.display(),
154 gtpack_out = ?opts.gtpack_out,
155 dry_run = opts.dry_run,
156 "building greentic pack"
157 );
158
159 if !opts.skip_update {
160 crate::cli::update::update_pack(&opts.pack_dir, false)?;
162 }
163
164 if !(opts.dry_run && opts.lock_path.exists()) {
167 resolve::handle(
168 ResolveArgs {
169 input: opts.pack_dir.clone(),
170 lock: Some(opts.lock_path.clone()),
171 },
172 &opts.runtime,
173 false,
174 )
175 .await?;
176 }
177
178 if opts.validate_extension_refs {
179 let extensions_file = default_extensions_file_path(&opts.pack_dir);
180 let source_extensions = if extensions_file.exists() {
181 Some(read_extensions_file(&extensions_file)?)
182 } else {
183 None
184 };
185 let extensions_lock = default_extensions_lock_file_path(&opts.pack_dir);
186 if extensions_lock.exists() {
187 let lock = read_extensions_lock_file(&extensions_lock)?;
188 if let Some(source) = source_extensions.as_ref() {
189 validate_extensions_lock_alignment(source, &lock)?;
190 }
191 }
192 }
193
194 let config = crate::config::load_pack_config(&opts.pack_dir)?;
195 info!(
196 id = %config.pack_id,
197 version = %config.version,
198 kind = %config.kind,
199 components = config.components.len(),
200 flows = config.flows.len(),
201 dependencies = config.dependencies.len(),
202 "loaded pack.yaml"
203 );
204 validate_components_extension(&config.extensions, opts.allow_oci_tags)?;
205 validate_deployer_extension(&config.extensions, &opts.pack_dir)?;
206 validate_static_routes_extension(&config.extensions, &opts.pack_dir)?;
207 if !opts.lock_path.exists() {
208 anyhow::bail!(
209 "pack.lock.cbor is required (run `greentic-pack resolve`); missing: {}",
210 opts.lock_path.display()
211 );
212 }
213 let pack_lock = read_pack_lock(&opts.lock_path).with_context(|| {
214 format!(
215 "failed to read pack lock {} (try `greentic-pack resolve`)",
216 opts.lock_path.display()
217 )
218 })?;
219 let mut known_component_ids = config
220 .components
221 .iter()
222 .map(|component| component.id.clone())
223 .collect::<BTreeSet<_>>();
224 known_component_ids.extend(pack_lock.components.keys().cloned());
225 let known_component_ids = known_component_ids.into_iter().collect::<Vec<_>>();
226 validate_capabilities_extension(&config.extensions, &opts.pack_dir, &known_component_ids)?;
227
228 let secret_requirements_override =
229 resolve_secret_requirements_override(&opts.pack_dir, opts.secrets_req.as_ref());
230 let secret_requirements = aggregate_secret_requirements(
231 &config.components,
232 secret_requirements_override.as_deref(),
233 opts.default_secret_scope.as_deref(),
234 )?;
235
236 let mut build = assemble_manifest(
237 &config,
238 &opts.pack_dir,
239 &secret_requirements,
240 !opts.no_extra_dirs,
241 opts.dev,
242 opts.allow_pack_schema,
243 )?;
244 build.lock_components =
245 collect_lock_component_artifacts(&pack_lock, &opts.runtime, opts.bundle, opts.dry_run)
246 .await?;
247
248 let mut bundled_paths = BTreeMap::new();
249 for entry in &build.lock_components {
250 bundled_paths.insert(entry.component_id.clone(), entry.logical_path.clone());
251 }
252
253 let materialized = materialize_flow_components(
254 &opts.pack_dir,
255 &build.manifest.flows,
256 &pack_lock,
257 &build.components,
258 &build.lock_components,
259 opts.require_component_manifests,
260 )?;
261 build.manifest.components.extend(materialized.components);
262 build.component_manifest_files = materialized.manifest_files;
263 build.manifest.components.sort_by(|a, b| a.id.cmp(&b.id));
264
265 let component_manifest_files =
266 collect_component_manifest_files(&build.components, &build.component_manifest_files);
267 build.manifest.extensions =
268 merge_component_manifest_extension(build.manifest.extensions, &component_manifest_files)?;
269 build.manifest.extensions = merge_component_sources_extension(
270 build.manifest.extensions,
271 &pack_lock,
272 &bundled_paths,
273 materialized.manifest_paths.as_ref(),
274 )?;
275 if !opts.dry_run {
276 greentic_pack::pack_lock::write_pack_lock(&opts.lock_path, &pack_lock)?;
277 }
278
279 let manifest_bytes = encode_pack_manifest(&build.manifest)?;
280 info!(len = manifest_bytes.len(), "encoded manifest.cbor");
281
282 if opts.dry_run {
283 info!("dry-run complete; no files written");
284 return Ok(());
285 }
286
287 if let Some(component_out) = opts.component_out.as_ref() {
288 write_stub_wasm(component_out)?;
289 }
290
291 write_bytes(&opts.manifest_out, &manifest_bytes)?;
292
293 if let Some(sbom_out) = opts.sbom_out.as_ref() {
294 write_bytes(sbom_out, br#"{"files":[]} "#)?;
295 }
296
297 if let Some(gtpack_out) = opts.gtpack_out.as_ref() {
298 let mut build = build;
299 if opts.dev && !secret_requirements.is_empty() {
300 let logical = "secret-requirements.json".to_string();
301 let req_path =
302 write_secret_requirements_file(&opts.pack_dir, &secret_requirements, &logical)?;
303 build.assets.push(AssetFile {
304 logical_path: logical,
305 source: req_path,
306 });
307 }
308 let warnings = package_gtpack(gtpack_out, &manifest_bytes, &build, opts.bundle, opts.dev)?;
309 for warning in warnings {
310 warn!(warning);
311 }
312 info!(gtpack_out = %gtpack_out.display(), "gtpack archive ready");
313 eprintln!("wrote {}", gtpack_out.display());
314 }
315
316 Ok(())
317}
318
319struct BuildProducts {
320 manifest: PackManifest,
321 components: Vec<ComponentBinary>,
322 lock_components: Vec<LockComponentBinary>,
323 component_manifest_files: Vec<ComponentManifestFile>,
324 flow_files: Vec<FlowFile>,
325 assets: Vec<AssetFile>,
326 extra_files: Vec<ExtraFile>,
327}
328
329#[derive(Clone)]
330struct ComponentBinary {
331 id: String,
332 source: PathBuf,
333 manifest_bytes: Vec<u8>,
334 manifest_path: String,
335 manifest_hash_sha256: String,
336}
337
338#[derive(Clone)]
339struct LockComponentBinary {
340 component_id: String,
341 logical_path: String,
342 source: PathBuf,
343}
344
345#[derive(Clone)]
346struct ComponentManifestFile {
347 component_id: String,
348 manifest_path: String,
349 manifest_bytes: Vec<u8>,
350 manifest_hash_sha256: String,
351}
352
353struct AssetFile {
354 logical_path: String,
355 source: PathBuf,
356}
357
358struct ExtraFile {
359 logical_path: String,
360 source: PathBuf,
361}
362
363#[derive(Clone)]
364struct FlowFile {
365 logical_path: String,
366 bytes: Vec<u8>,
367 media_type: &'static str,
368}
369
370fn assemble_manifest(
371 config: &PackConfig,
372 pack_root: &Path,
373 secret_requirements: &[SecretRequirement],
374 include_extra_dirs: bool,
375 dev_mode: bool,
376 allow_pack_schema: bool,
377) -> Result<BuildProducts> {
378 let components = build_components(&config.components, allow_pack_schema)?;
379 let (flows, flow_files) = build_flows(&config.flows, pack_root)?;
380 let dependencies = build_dependencies(&config.dependencies)?;
381 let assets = collect_assets(&config.assets, pack_root)?;
382 let extra_files = if include_extra_dirs {
383 collect_extra_dir_files(pack_root)?
384 } else {
385 Vec::new()
386 };
387 let component_manifests: Vec<_> = components.iter().map(|c| c.0.clone()).collect();
388 let bootstrap = build_bootstrap(config, &flows, &component_manifests)?;
389 let extensions = normalize_extensions(&config.extensions);
390
391 let mut manifest = PackManifest {
392 schema_version: "pack-v1".to_string(),
393 pack_id: PackId::new(config.pack_id.clone()).context("invalid pack_id")?,
394 name: config.name.clone(),
395 version: Version::parse(&config.version)
396 .context("invalid pack version (expected semver)")?,
397 kind: map_kind(&config.kind)?,
398 publisher: config.publisher.clone(),
399 components: component_manifests,
400 flows,
401 dependencies,
402 capabilities: derive_pack_capabilities(&components),
403 secret_requirements: secret_requirements.to_vec(),
404 signatures: PackSignatures::default(),
405 bootstrap,
406 extensions,
407 };
408
409 annotate_manifest_build_mode(&mut manifest, dev_mode);
410
411 Ok(BuildProducts {
412 manifest,
413 components: components.into_iter().map(|(_, bin)| bin).collect(),
414 lock_components: Vec::new(),
415 component_manifest_files: Vec::new(),
416 flow_files,
417 assets,
418 extra_files,
419 })
420}
421
422fn annotate_manifest_build_mode(manifest: &mut PackManifest, dev_mode: bool) {
423 let extensions = manifest.extensions.get_or_insert_with(BTreeMap::new);
424 extensions.insert(
425 EXT_BUILD_MODE_ID.to_string(),
426 ExtensionRef {
427 kind: EXT_BUILD_MODE_ID.to_string(),
428 version: "1".to_string(),
429 digest: None,
430 location: None,
431 inline: Some(PackManifestExtensionInline::Other(json!({
432 "mode": if dev_mode { "dev" } else { "prod" }
433 }))),
434 },
435 );
436}
437
438fn build_components(
439 configs: &[ComponentConfig],
440 allow_pack_schema: bool,
441) -> Result<Vec<(ComponentManifest, ComponentBinary)>> {
442 let mut seen = BTreeSet::new();
443 let mut result = Vec::new();
444
445 for cfg in configs {
446 if !seen.insert(cfg.id.clone()) {
447 warn!(
448 id = %cfg.id,
449 "duplicate component id in pack.yaml; keeping first entry and skipping duplicate"
450 );
451 continue;
452 }
453
454 info!(id = %cfg.id, wasm = %cfg.wasm.display(), "adding component");
455 let (manifest, binary) = resolve_component_artifacts(cfg, allow_pack_schema)?;
456
457 result.push((manifest, binary));
458 }
459
460 Ok(result)
461}
462
463fn resolve_component_artifacts(
464 cfg: &ComponentConfig,
465 allow_pack_schema: bool,
466) -> Result<(ComponentManifest, ComponentBinary)> {
467 let resolved_wasm = resolve_component_wasm_path(&cfg.wasm)?;
468
469 let mut manifest = if let Some(from_disk) =
470 load_component_manifest_from_disk(&resolved_wasm, &cfg.id)?
471 {
472 if from_disk.id.to_string() != cfg.id {
473 anyhow::bail!(
474 "component manifest id {} does not match pack.yaml id {}",
475 from_disk.id,
476 cfg.id
477 );
478 }
479 if from_disk.version.to_string() != cfg.version {
480 anyhow::bail!(
481 "component manifest version {} does not match pack.yaml version {}",
482 from_disk.version,
483 cfg.version
484 );
485 }
486 from_disk
487 } else if allow_pack_schema || is_legacy_pack_schema_component(&cfg.id) {
488 warn!(
489 id = %cfg.id,
490 "migration-only path enabled: deriving component manifest/schema from pack.yaml (--allow-pack-schema)"
491 );
492 manifest_from_config(cfg)?
493 } else {
494 anyhow::bail!(
495 "component {} is missing component.manifest.json; refusing to derive schema from pack.yaml on 0.6 path (migration-only override: --allow-pack-schema)",
496 cfg.id
497 );
498 };
499
500 if manifest.operations.is_empty() && !cfg.operations.is_empty() {
502 manifest.operations = cfg
503 .operations
504 .iter()
505 .map(operation_from_config)
506 .collect::<Result<Vec<_>>>()?;
507 }
508
509 let manifest_bytes = canonical::to_canonical_cbor_allow_floats(&manifest)
510 .context("encode component manifest to canonical cbor")?;
511 let mut sha = Sha256::new();
512 sha.update(&manifest_bytes);
513 let manifest_hash_sha256 = format!("sha256:{:x}", sha.finalize());
514 let manifest_path = format!("components/{}.manifest.cbor", cfg.id);
515
516 let binary = ComponentBinary {
517 id: cfg.id.clone(),
518 source: resolved_wasm,
519 manifest_bytes,
520 manifest_path,
521 manifest_hash_sha256,
522 };
523
524 Ok((manifest, binary))
525}
526
527fn is_legacy_pack_schema_component(component_id: &str) -> bool {
528 matches!(
529 component_id,
530 "ai.greentic.component-provision" | "ai.greentic.component-questions"
531 )
532}
533
534fn manifest_from_config(cfg: &ComponentConfig) -> Result<ComponentManifest> {
535 Ok(ComponentManifest {
536 id: ComponentId::new(cfg.id.clone())
537 .with_context(|| format!("invalid component id {}", cfg.id))?,
538 version: Version::parse(&cfg.version)
539 .context("invalid component version (expected semver)")?,
540 supports: cfg.supports.iter().map(|k| k.to_kind()).collect(),
541 world: cfg.world.clone(),
542 profiles: cfg.profiles.clone(),
543 capabilities: cfg.capabilities.clone(),
544 configurators: convert_configurators(cfg)?,
545 operations: cfg
546 .operations
547 .iter()
548 .map(operation_from_config)
549 .collect::<Result<Vec<_>>>()?,
550 config_schema: cfg.config_schema.clone(),
551 resources: cfg.resources.clone().unwrap_or_default(),
552 dev_flows: BTreeMap::new(),
553 })
554}
555
556fn resolve_component_wasm_path(path: &Path) -> Result<PathBuf> {
557 if path.is_file() {
558 return Ok(path.to_path_buf());
559 }
560 if !path.exists() {
561 anyhow::bail!("component path {} does not exist", path.display());
562 }
563 if !path.is_dir() {
564 anyhow::bail!(
565 "component path {} must be a file or directory",
566 path.display()
567 );
568 }
569
570 let mut component_candidates = Vec::new();
571 let mut wasm_candidates = Vec::new();
572 let mut stack = vec![path.to_path_buf()];
573 while let Some(current) = stack.pop() {
574 for entry in fs::read_dir(¤t)
575 .with_context(|| format!("failed to list components in {}", current.display()))?
576 {
577 let entry = entry?;
578 let entry_type = entry.file_type()?;
579 let entry_path = entry.path();
580 if entry_type.is_dir() {
581 stack.push(entry_path);
582 continue;
583 }
584 if entry_type.is_file() && entry_path.extension() == Some(std::ffi::OsStr::new("wasm"))
585 {
586 let file_name = entry_path
587 .file_name()
588 .and_then(|n| n.to_str())
589 .unwrap_or_default();
590 if file_name.ends_with(".component.wasm") {
591 component_candidates.push(entry_path);
592 } else {
593 wasm_candidates.push(entry_path);
594 }
595 }
596 }
597 }
598
599 let choose = |mut list: Vec<PathBuf>| -> Result<PathBuf> {
600 list.sort();
601 if list.len() == 1 {
602 Ok(list.remove(0))
603 } else {
604 let options = list
605 .iter()
606 .map(|p| p.strip_prefix(path).unwrap_or(p).display().to_string())
607 .collect::<Vec<_>>()
608 .join(", ");
609 anyhow::bail!(
610 "multiple wasm artifacts found under {}: {} (pick a single *.component.wasm or *.wasm)",
611 path.display(),
612 options
613 );
614 }
615 };
616
617 if !component_candidates.is_empty() {
618 return choose(component_candidates);
619 }
620 if !wasm_candidates.is_empty() {
621 return choose(wasm_candidates);
622 }
623
624 anyhow::bail!(
625 "no wasm artifact found under {}; expected *.component.wasm or *.wasm",
626 path.display()
627 );
628}
629
630fn load_component_manifest_from_disk(
631 path: &Path,
632 component_id: &str,
633) -> Result<Option<ComponentManifest>> {
634 let manifest_dir = if path.is_dir() {
635 path.to_path_buf()
636 } else {
637 path.parent()
638 .map(Path::to_path_buf)
639 .ok_or_else(|| anyhow!("component path {} has no parent directory", path.display()))?
640 };
641 let id_manifest_suffix = format!("{component_id}.manifest");
642
643 for dir in manifest_search_dirs(&manifest_dir) {
647 let candidates = [
648 dir.join("component.manifest.cbor"),
649 dir.join("component.manifest.json"),
650 dir.join("component.json"),
651 dir.join(format!("{id_manifest_suffix}.cbor")),
652 dir.join(format!("{id_manifest_suffix}.json")),
653 dir.join(format!("{component_id}.json")),
654 ];
655 for manifest_path in candidates {
656 if !manifest_path.exists() {
657 continue;
658 }
659 let manifest = load_component_manifest_from_file(&manifest_path)?;
660 return Ok(Some(manifest));
661 }
662 }
663
664 Ok(None)
665}
666
667fn manifest_search_dirs(manifest_dir: &Path) -> Vec<PathBuf> {
668 let has_target_ancestor = std::iter::successors(Some(manifest_dir), |d| d.parent())
669 .any(|dir| dir.file_name().is_some_and(|name| name == "target"));
670 if !has_target_ancestor {
671 return vec![manifest_dir.to_path_buf()];
672 }
673
674 let mut dirs = Vec::new();
675 let mut current = Some(manifest_dir.to_path_buf());
676 let mut saw_target = false;
677
678 while let Some(dir) = current {
679 dirs.push(dir.clone());
680 if dir.file_name().is_some_and(|name| name == "target") {
681 saw_target = true;
682 } else if saw_target {
683 break;
685 }
686 current = dir.parent().map(Path::to_path_buf);
687 }
688
689 dirs
690}
691
692fn operation_from_config(cfg: &ComponentOperationConfig) -> Result<ComponentOperation> {
693 Ok(ComponentOperation {
694 name: cfg.name.clone(),
695 input_schema: cfg.input_schema.clone(),
696 output_schema: cfg.output_schema.clone(),
697 })
698}
699
700fn convert_configurators(cfg: &ComponentConfig) -> Result<Option<ComponentConfigurators>> {
701 let Some(configurators) = cfg.configurators.as_ref() else {
702 return Ok(None);
703 };
704
705 let basic = match &configurators.basic {
706 Some(id) => Some(FlowId::new(id).context("invalid configurator flow id")?),
707 None => None,
708 };
709 let full = match &configurators.full {
710 Some(id) => Some(FlowId::new(id).context("invalid configurator flow id")?),
711 None => None,
712 };
713
714 Ok(Some(ComponentConfigurators { basic, full }))
715}
716
717fn build_bootstrap(
718 config: &PackConfig,
719 flows: &[PackFlowEntry],
720 components: &[ComponentManifest],
721) -> Result<Option<BootstrapSpec>> {
722 let Some(raw) = config.bootstrap.as_ref() else {
723 return Ok(None);
724 };
725
726 let flow_ids: BTreeSet<_> = flows.iter().map(|flow| flow.id.to_string()).collect();
727 let component_ids: BTreeSet<_> = components.iter().map(|c| c.id.to_string()).collect();
728
729 let mut spec = BootstrapSpec::default();
730
731 if let Some(install_flow) = &raw.install_flow {
732 if !flow_ids.contains(install_flow) {
733 anyhow::bail!(
734 "bootstrap.install_flow references unknown flow {}",
735 install_flow
736 );
737 }
738 spec.install_flow = Some(install_flow.clone());
739 }
740
741 if let Some(upgrade_flow) = &raw.upgrade_flow {
742 if !flow_ids.contains(upgrade_flow) {
743 anyhow::bail!(
744 "bootstrap.upgrade_flow references unknown flow {}",
745 upgrade_flow
746 );
747 }
748 spec.upgrade_flow = Some(upgrade_flow.clone());
749 }
750
751 if let Some(component) = &raw.installer_component {
752 if !component_ids.contains(component) {
753 anyhow::bail!(
754 "bootstrap.installer_component references unknown component {}",
755 component
756 );
757 }
758 spec.installer_component = Some(component.clone());
759 }
760
761 if spec.install_flow.is_none()
762 && spec.upgrade_flow.is_none()
763 && spec.installer_component.is_none()
764 {
765 return Ok(None);
766 }
767
768 Ok(Some(spec))
769}
770
771fn build_flows(
772 configs: &[FlowConfig],
773 pack_root: &Path,
774) -> Result<(Vec<PackFlowEntry>, Vec<FlowFile>)> {
775 let mut seen = BTreeSet::new();
776 let mut entries = Vec::new();
777 let mut flow_files = Vec::new();
778
779 for cfg in configs {
780 info!(id = %cfg.id, path = %cfg.file.display(), "compiling flow");
781 let yaml_bytes = fs::read(&cfg.file)
782 .with_context(|| format!("failed to read flow {}", cfg.file.display()))?;
783 let mut flow: Flow = compile_ygtc_file(&cfg.file)
784 .with_context(|| format!("failed to compile {}", cfg.file.display()))?;
785 populate_component_exec_operations(&mut flow, &cfg.file).with_context(|| {
786 format!(
787 "failed to resolve component.exec operations in {}",
788 cfg.file.display()
789 )
790 })?;
791 normalize_legacy_component_exec_ids(&mut flow)?;
792 let summary = load_flow_resolve_summary(pack_root, cfg, &flow)?;
793 apply_summary_component_ids(&mut flow, &summary).with_context(|| {
794 format!("failed to resolve component ids in {}", cfg.file.display())
795 })?;
796
797 let flow_id = flow.id.to_string();
798 if !seen.insert(flow_id.clone()) {
799 anyhow::bail!("duplicate flow id {}", flow_id);
800 }
801
802 let entrypoints = if cfg.entrypoints.is_empty() {
803 flow.entrypoints.keys().cloned().collect()
804 } else {
805 cfg.entrypoints.clone()
806 };
807
808 let flow_entry = PackFlowEntry {
809 id: flow.id.clone(),
810 kind: flow.kind,
811 flow,
812 tags: cfg.tags.clone(),
813 entrypoints,
814 };
815
816 let flow_id = flow_entry.id.to_string();
817 flow_files.push(FlowFile {
818 logical_path: format!("flows/{flow_id}/flow.ygtc"),
819 bytes: yaml_bytes,
820 media_type: "application/yaml",
821 });
822 flow_files.push(FlowFile {
823 logical_path: format!("flows/{flow_id}/flow.json"),
824 bytes: serde_json::to_vec(&flow_entry.flow).context("encode flow json")?,
825 media_type: "application/json",
826 });
827 entries.push(flow_entry);
828 }
829
830 Ok((entries, flow_files))
831}
832
833fn apply_summary_component_ids(flow: &mut Flow, summary: &FlowResolveSummaryV1) -> Result<()> {
834 for (node_id, node) in flow.nodes.iter_mut() {
835 let resolved = summary.nodes.get(node_id.as_str()).ok_or_else(|| {
836 anyhow!(
837 "flow resolve summary missing node {} (expected component id for node)",
838 node_id
839 )
840 })?;
841 let summary_id = resolved.component_id.as_str();
842 if node.component.id.as_str().is_empty() || node.component.id.as_str() == "component.exec" {
843 node.component.id = resolved.component_id.clone();
844 continue;
845 }
846 if node.component.id.as_str() != summary_id {
847 anyhow::bail!(
848 "node {} component id {} does not match resolve summary {}",
849 node_id,
850 node.component.id.as_str(),
851 summary_id
852 );
853 }
854 }
855 Ok(())
856}
857
858fn populate_component_exec_operations(flow: &mut Flow, path: &Path) -> Result<()> {
859 let needs_op = flow.nodes.values().any(|node| {
860 node.component.id.as_str() == "component.exec" && node.component.operation.is_none()
861 });
862 if !needs_op {
863 return Ok(());
864 }
865
866 let flow_doc = load_ygtc_from_path(path)?;
867 let mut operations = BTreeMap::new();
868
869 for (node_id, node_doc) in flow_doc.nodes {
870 let value = serde_json::to_value(&node_doc)
871 .with_context(|| format!("failed to normalize component.exec node {}", node_id))?;
872 let normalized = normalize_node_map(value)?;
873 if !normalized.operation.trim().is_empty() {
874 operations.insert(node_id, normalized.operation);
875 }
876 }
877
878 for (node_id, node) in flow.nodes.iter_mut() {
879 if node.component.id.as_str() != "component.exec" || node.component.operation.is_some() {
880 continue;
881 }
882 if let Some(op) = operations.get(node_id.as_str()) {
883 node.component.operation = Some(op.clone());
884 }
885 }
886
887 Ok(())
888}
889
890fn normalize_legacy_component_exec_ids(flow: &mut Flow) -> Result<()> {
891 for (node_id, node) in flow.nodes.iter_mut() {
892 if node.component.id.as_str() != "component.exec" {
893 continue;
894 }
895 let Some(op) = node.component.operation.as_deref() else {
896 continue;
897 };
898 if !op.contains('.') && !op.contains(':') {
899 continue;
900 }
901 node.component.id = ComponentId::new(op).with_context(|| {
902 format!("invalid component id {} resolved for node {}", op, node_id)
903 })?;
904 node.component.operation = None;
905 }
906 Ok(())
907}
908
909fn build_dependencies(configs: &[crate::config::DependencyConfig]) -> Result<Vec<PackDependency>> {
910 let mut deps = Vec::new();
911 let mut seen = BTreeSet::new();
912 for cfg in configs {
913 if !seen.insert(cfg.alias.clone()) {
914 anyhow::bail!("duplicate dependency alias {}", cfg.alias);
915 }
916 deps.push(PackDependency {
917 alias: cfg.alias.clone(),
918 pack_id: PackId::new(cfg.pack_id.clone()).context("invalid dependency pack_id")?,
919 version_req: SemverReq::parse(&cfg.version_req)
920 .context("invalid dependency version requirement")?,
921 required_capabilities: cfg.required_capabilities.clone(),
922 });
923 }
924 Ok(deps)
925}
926
927fn collect_assets(configs: &[AssetConfig], pack_root: &Path) -> Result<Vec<AssetFile>> {
928 let mut assets = Vec::new();
929 for cfg in configs {
930 let logical = cfg
931 .path
932 .strip_prefix(pack_root)
933 .unwrap_or(&cfg.path)
934 .components()
935 .map(|c| c.as_os_str().to_string_lossy().into_owned())
936 .collect::<Vec<_>>()
937 .join("/");
938 if logical.is_empty() {
939 anyhow::bail!("invalid asset path {}", cfg.path.display());
940 }
941 assets.push(AssetFile {
942 logical_path: logical,
943 source: cfg.path.clone(),
944 });
945 }
946 Ok(assets)
947}
948
949fn is_reserved_extra_file(logical_path: &str) -> bool {
950 matches!(logical_path, "sbom.cbor" | "sbom.json")
951}
952
953fn collect_extra_dir_files(pack_root: &Path) -> Result<Vec<ExtraFile>> {
954 let excluded = [
955 "components",
956 "flows",
957 "dist",
958 "target",
959 ".git",
960 ".github",
961 ".idea",
962 ".vscode",
963 "node_modules",
964 ];
965 let mut entries = Vec::new();
966 let mut seen = BTreeSet::new();
967 for entry in fs::read_dir(pack_root)
968 .with_context(|| format!("failed to list pack root {}", pack_root.display()))?
969 {
970 let entry = entry?;
971 let entry_type = entry.file_type()?;
972 let name = entry.file_name();
973 let name = name.to_string_lossy();
974 if entry_type.is_file() {
975 let logical = name.to_string();
976 if is_reserved_extra_file(&logical) {
977 continue;
978 }
979 if !logical.is_empty() && seen.insert(logical.clone()) {
980 entries.push(ExtraFile {
981 logical_path: logical,
982 source: entry.path(),
983 });
984 }
985 continue;
986 }
987 if !entry_type.is_dir() {
988 continue;
989 }
990 if name.starts_with('.') || excluded.contains(&name.as_ref()) {
991 continue;
992 }
993 let root = entry.path();
994 for sub in WalkDir::new(&root)
995 .into_iter()
996 .filter_entry(|walk| !walk.file_name().to_string_lossy().starts_with('.'))
997 .filter_map(Result::ok)
998 {
999 if !sub.file_type().is_file() {
1000 continue;
1001 }
1002 let logical = sub
1003 .path()
1004 .strip_prefix(pack_root)
1005 .unwrap_or(sub.path())
1006 .components()
1007 .map(|c| c.as_os_str().to_string_lossy().into_owned())
1008 .collect::<Vec<_>>()
1009 .join("/");
1010 if logical.is_empty() || !seen.insert(logical.clone()) {
1011 continue;
1012 }
1013 if is_reserved_extra_file(&logical) {
1014 continue;
1015 }
1016 entries.push(ExtraFile {
1017 logical_path: logical,
1018 source: sub.path().to_path_buf(),
1019 });
1020 }
1021 }
1022 Ok(entries)
1023}
1024
1025fn map_extra_files(
1026 extras: &[ExtraFile],
1027 asset_paths: &mut BTreeSet<String>,
1028 dev_mode: bool,
1029 warnings: &mut Vec<String>,
1030) -> Vec<(String, PathBuf)> {
1031 let mut mapped = Vec::new();
1032 for extra in extras {
1033 let logical = extra.logical_path.as_str();
1034 if logical.starts_with("assets/") {
1035 if asset_paths.insert(logical.to_string()) {
1036 mapped.push((logical.to_string(), extra.source.clone()));
1037 }
1038 continue;
1039 }
1040 if !logical.contains('/') {
1041 if is_reserved_source_file(logical) {
1042 if dev_mode || logical == "pack.lock.cbor" {
1043 mapped.push((logical.to_string(), extra.source.clone()));
1044 }
1045 continue;
1046 }
1047 let target = format!("assets/{logical}");
1048 if asset_paths.insert(target.clone()) {
1049 mapped.push((target, extra.source.clone()));
1050 } else {
1051 warnings.push(format!(
1052 "skipping root asset {logical} because assets/{logical} already exists"
1053 ));
1054 }
1055 continue;
1056 }
1057 mapped.push((logical.to_string(), extra.source.clone()));
1058 }
1059 mapped
1060}
1061
1062fn is_reserved_source_file(path: &str) -> bool {
1063 matches!(
1064 path,
1065 "pack.yaml"
1066 | "pack.manifest.json"
1067 | "pack.lock.cbor"
1068 | "manifest.json"
1069 | "manifest.cbor"
1070 | "sbom.json"
1071 | "sbom.cbor"
1072 | "provenance.json"
1073 | "secret-requirements.json"
1074 | "secrets_requirements.json"
1075 ) || path.ends_with(".ygtc")
1076}
1077
1078fn normalize_extensions(
1079 extensions: &Option<BTreeMap<String, greentic_types::ExtensionRef>>,
1080) -> Option<BTreeMap<String, greentic_types::ExtensionRef>> {
1081 extensions.as_ref().filter(|map| !map.is_empty()).cloned()
1082}
1083
1084fn merge_component_manifest_extension(
1085 extensions: Option<BTreeMap<String, ExtensionRef>>,
1086 manifest_files: &[ComponentManifestFile],
1087) -> Result<Option<BTreeMap<String, ExtensionRef>>> {
1088 if manifest_files.is_empty() {
1089 return Ok(extensions);
1090 }
1091
1092 let entries: Vec<_> = manifest_files
1093 .iter()
1094 .map(|entry| ComponentManifestIndexEntryV1 {
1095 component_id: entry.component_id.clone(),
1096 manifest_file: entry.manifest_path.clone(),
1097 encoding: ManifestEncoding::Cbor,
1098 content_hash: Some(entry.manifest_hash_sha256.clone()),
1099 })
1100 .collect();
1101
1102 let index = ComponentManifestIndexV1::new(entries);
1103 let value = index
1104 .to_extension_value()
1105 .context("serialize component manifest index extension")?;
1106
1107 let ext = ExtensionRef {
1108 kind: EXT_COMPONENT_MANIFEST_INDEX_V1.to_string(),
1109 version: "v1".to_string(),
1110 digest: None,
1111 location: None,
1112 inline: Some(ExtensionInline::Other(value)),
1113 };
1114
1115 let mut map = extensions.unwrap_or_default();
1116 map.insert(EXT_COMPONENT_MANIFEST_INDEX_V1.to_string(), ext);
1117 if map.is_empty() {
1118 Ok(None)
1119 } else {
1120 Ok(Some(map))
1121 }
1122}
1123
1124fn merge_component_sources_extension(
1125 extensions: Option<BTreeMap<String, ExtensionRef>>,
1126 lock: &greentic_pack::pack_lock::PackLockV1,
1127 bundled_paths: &BTreeMap<String, String>,
1128 manifest_paths: Option<&std::collections::BTreeMap<String, String>>,
1129) -> Result<Option<BTreeMap<String, ExtensionRef>>> {
1130 let mut entries = Vec::new();
1131 for comp in lock.components.values() {
1132 let Some(reference) = comp.r#ref.as_ref() else {
1133 continue;
1134 };
1135 if reference.starts_with("file://") {
1136 continue;
1137 }
1138 let source = match ComponentSourceRef::from_str(reference) {
1139 Ok(parsed) => parsed,
1140 Err(_) => {
1141 eprintln!(
1142 "warning: skipping pack.lock entry `{}` with unsupported ref {}",
1143 comp.component_id, reference
1144 );
1145 continue;
1146 }
1147 };
1148 let manifest_path = manifest_paths.and_then(|paths| paths.get(&comp.component_id).cloned());
1149 let artifact = if let Some(wasm_path) = bundled_paths.get(&comp.component_id) {
1150 ArtifactLocationV1::Inline {
1151 wasm_path: wasm_path.clone(),
1152 manifest_path,
1153 }
1154 } else {
1155 ArtifactLocationV1::Remote
1156 };
1157 entries.push(ComponentSourceEntryV1 {
1158 name: comp.component_id.clone(),
1159 component_id: Some(ComponentId::new(comp.component_id.clone()).map_err(|err| {
1160 anyhow!(
1161 "invalid component id {} in lock: {}",
1162 comp.component_id,
1163 err
1164 )
1165 })?),
1166 source,
1167 resolved: ResolvedComponentV1 {
1168 digest: comp.resolved_digest.clone(),
1169 signature: None,
1170 signed_by: None,
1171 },
1172 artifact,
1173 licensing_hint: None,
1174 metering_hint: None,
1175 });
1176 }
1177
1178 if entries.is_empty() {
1179 return Ok(extensions);
1180 }
1181
1182 let payload = ComponentSourcesV1::new(entries)
1183 .to_extension_value()
1184 .context("serialize component_sources extension")?;
1185
1186 let ext = ExtensionRef {
1187 kind: EXT_COMPONENT_SOURCES_V1.to_string(),
1188 version: "v1".to_string(),
1189 digest: None,
1190 location: None,
1191 inline: Some(ExtensionInline::Other(payload)),
1192 };
1193
1194 let mut map = extensions.unwrap_or_default();
1195 map.insert(EXT_COMPONENT_SOURCES_V1.to_string(), ext);
1196 if map.is_empty() {
1197 Ok(None)
1198 } else {
1199 Ok(Some(map))
1200 }
1201}
1202
1203fn derive_pack_capabilities(
1204 components: &[(ComponentManifest, ComponentBinary)],
1205) -> Vec<ComponentCapability> {
1206 let mut seen = BTreeSet::new();
1207 let mut caps = Vec::new();
1208
1209 for (component, _) in components {
1210 let mut add = |name: &str| {
1211 if seen.insert(name.to_string()) {
1212 caps.push(ComponentCapability {
1213 name: name.to_string(),
1214 description: None,
1215 });
1216 }
1217 };
1218
1219 if component.capabilities.host.secrets.is_some() {
1220 add("host:secrets");
1221 }
1222 if let Some(state) = &component.capabilities.host.state {
1223 if state.read {
1224 add("host:state:read");
1225 }
1226 if state.write {
1227 add("host:state:write");
1228 }
1229 }
1230 if component.capabilities.host.messaging.is_some() {
1231 add("host:messaging");
1232 }
1233 if component.capabilities.host.events.is_some() {
1234 add("host:events");
1235 }
1236 if component.capabilities.host.http.is_some() {
1237 add("host:http");
1238 }
1239 if component.capabilities.host.telemetry.is_some() {
1240 add("host:telemetry");
1241 }
1242 if component.capabilities.host.iac.is_some() {
1243 add("host:iac");
1244 }
1245 if let Some(fs) = component.capabilities.wasi.filesystem.as_ref() {
1246 add(&format!(
1247 "wasi:fs:{}",
1248 format!("{:?}", fs.mode).to_lowercase()
1249 ));
1250 if !fs.mounts.is_empty() {
1251 add("wasi:fs:mounts");
1252 }
1253 }
1254 if component.capabilities.wasi.random {
1255 add("wasi:random");
1256 }
1257 if component.capabilities.wasi.clocks {
1258 add("wasi:clocks");
1259 }
1260 }
1261
1262 caps
1263}
1264
1265fn map_kind(raw: &str) -> Result<PackKind> {
1266 match raw.to_ascii_lowercase().as_str() {
1267 "application" => Ok(PackKind::Application),
1268 "provider" => Ok(PackKind::Provider),
1269 "infrastructure" => Ok(PackKind::Infrastructure),
1270 "library" => Ok(PackKind::Library),
1271 other => Err(anyhow!("unknown pack kind {}", other)),
1272 }
1273}
1274
1275fn package_gtpack(
1276 out_path: &Path,
1277 manifest_bytes: &[u8],
1278 build: &BuildProducts,
1279 bundle: BundleMode,
1280 dev_mode: bool,
1281) -> Result<Vec<String>> {
1282 if let Some(parent) = out_path.parent() {
1283 fs::create_dir_all(parent)
1284 .with_context(|| format!("failed to create {}", parent.display()))?;
1285 }
1286
1287 let file = fs::File::create(out_path)
1288 .with_context(|| format!("failed to create {}", out_path.display()))?;
1289 let mut writer = ZipWriter::new(file);
1290 let options = SimpleFileOptions::default()
1291 .compression_method(CompressionMethod::Stored)
1292 .unix_permissions(0o644);
1293
1294 let mut sbom_entries = Vec::new();
1295 let mut written_paths = BTreeSet::new();
1296 let mut warnings = Vec::new();
1297 let mut asset_paths = BTreeSet::new();
1298 record_sbom_entry(
1299 &mut sbom_entries,
1300 "manifest.cbor",
1301 manifest_bytes,
1302 "application/cbor",
1303 );
1304 written_paths.insert("manifest.cbor".to_string());
1305 write_zip_entry(&mut writer, "manifest.cbor", manifest_bytes, options)?;
1306
1307 if dev_mode {
1308 let mut flow_files = build.flow_files.clone();
1309 flow_files.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
1310 for flow_file in flow_files {
1311 if written_paths.insert(flow_file.logical_path.clone()) {
1312 record_sbom_entry(
1313 &mut sbom_entries,
1314 &flow_file.logical_path,
1315 &flow_file.bytes,
1316 flow_file.media_type,
1317 );
1318 write_zip_entry(
1319 &mut writer,
1320 &flow_file.logical_path,
1321 &flow_file.bytes,
1322 options,
1323 )?;
1324 }
1325 }
1326 }
1327
1328 let mut component_wasm_paths = BTreeSet::new();
1329 if bundle != BundleMode::None {
1330 for comp in &build.components {
1331 component_wasm_paths.insert(format!("components/{}.wasm", comp.id));
1332 }
1333 }
1334 let mut manifest_component_ids = BTreeSet::new();
1335 for manifest in &build.component_manifest_files {
1336 manifest_component_ids.insert(manifest.component_id.clone());
1337 }
1338
1339 let mut lock_components = build.lock_components.clone();
1340 lock_components.sort_by(|a, b| a.logical_path.cmp(&b.logical_path));
1341 for comp in lock_components {
1342 if component_wasm_paths.contains(&comp.logical_path) {
1343 continue;
1344 }
1345 if !written_paths.insert(comp.logical_path.clone()) {
1346 continue;
1347 }
1348 let bytes = fs::read(&comp.source).with_context(|| {
1349 format!("failed to read cached component {}", comp.source.display())
1350 })?;
1351 record_sbom_entry(
1352 &mut sbom_entries,
1353 &comp.logical_path,
1354 &bytes,
1355 "application/wasm",
1356 );
1357 write_zip_entry(&mut writer, &comp.logical_path, &bytes, options)?;
1358 let describe_source = PathBuf::from(format!("{}.describe.cbor", comp.source.display()));
1359 if describe_source.exists() {
1360 let describe_bytes = fs::read(&describe_source).with_context(|| {
1361 format!(
1362 "failed to read describe cache {}",
1363 describe_source.display()
1364 )
1365 })?;
1366 let describe_logical = format!("{}.describe.cbor", comp.logical_path);
1367 if written_paths.insert(describe_logical.clone()) {
1368 record_sbom_entry(
1369 &mut sbom_entries,
1370 &describe_logical,
1371 &describe_bytes,
1372 "application/cbor",
1373 );
1374 write_zip_entry(&mut writer, &describe_logical, &describe_bytes, options)?;
1375 }
1376 }
1377
1378 if manifest_component_ids.contains(&comp.component_id) {
1379 let alias_path = format!("components/{}.wasm", comp.component_id);
1380 if written_paths.insert(alias_path.clone()) {
1381 record_sbom_entry(&mut sbom_entries, &alias_path, &bytes, "application/wasm");
1382 write_zip_entry(&mut writer, &alias_path, &bytes, options)?;
1383 }
1384 let describe_source = PathBuf::from(format!("{}.describe.cbor", comp.source.display()));
1385 if describe_source.exists() {
1386 let describe_bytes = fs::read(&describe_source).with_context(|| {
1387 format!(
1388 "failed to read describe cache {}",
1389 describe_source.display()
1390 )
1391 })?;
1392 let alias_describe = format!("{alias_path}.describe.cbor");
1393 if written_paths.insert(alias_describe.clone()) {
1394 record_sbom_entry(
1395 &mut sbom_entries,
1396 &alias_describe,
1397 &describe_bytes,
1398 "application/cbor",
1399 );
1400 write_zip_entry(&mut writer, &alias_describe, &describe_bytes, options)?;
1401 }
1402 }
1403 }
1404 }
1405
1406 let mut lock_manifests = build.component_manifest_files.clone();
1407 lock_manifests.sort_by(|a, b| a.manifest_path.cmp(&b.manifest_path));
1408 for manifest in lock_manifests {
1409 if written_paths.insert(manifest.manifest_path.clone()) {
1410 record_sbom_entry(
1411 &mut sbom_entries,
1412 &manifest.manifest_path,
1413 &manifest.manifest_bytes,
1414 "application/cbor",
1415 );
1416 write_zip_entry(
1417 &mut writer,
1418 &manifest.manifest_path,
1419 &manifest.manifest_bytes,
1420 options,
1421 )?;
1422 }
1423 }
1424
1425 if bundle != BundleMode::None {
1426 let mut components = build.components.clone();
1427 components.sort_by(|a, b| a.id.cmp(&b.id));
1428 for comp in components {
1429 let logical_wasm = format!("components/{}.wasm", comp.id);
1430 let wasm_bytes = fs::read(&comp.source)
1431 .with_context(|| format!("failed to read component {}", comp.source.display()))?;
1432 if written_paths.insert(logical_wasm.clone()) {
1433 record_sbom_entry(
1434 &mut sbom_entries,
1435 &logical_wasm,
1436 &wasm_bytes,
1437 "application/wasm",
1438 );
1439 write_zip_entry(&mut writer, &logical_wasm, &wasm_bytes, options)?;
1440 }
1441 let describe_source = PathBuf::from(format!("{}.describe.cbor", comp.source.display()));
1442 if describe_source.exists() {
1443 let describe_bytes = fs::read(&describe_source).with_context(|| {
1444 format!(
1445 "failed to read describe cache {}",
1446 describe_source.display()
1447 )
1448 })?;
1449 let describe_logical = format!("{logical_wasm}.describe.cbor");
1450 if written_paths.insert(describe_logical.clone()) {
1451 record_sbom_entry(
1452 &mut sbom_entries,
1453 &describe_logical,
1454 &describe_bytes,
1455 "application/cbor",
1456 );
1457 write_zip_entry(&mut writer, &describe_logical, &describe_bytes, options)?;
1458 }
1459 }
1460
1461 if written_paths.insert(comp.manifest_path.clone()) {
1462 record_sbom_entry(
1463 &mut sbom_entries,
1464 &comp.manifest_path,
1465 &comp.manifest_bytes,
1466 "application/cbor",
1467 );
1468 write_zip_entry(
1469 &mut writer,
1470 &comp.manifest_path,
1471 &comp.manifest_bytes,
1472 options,
1473 )?;
1474 }
1475 }
1476 }
1477
1478 let mut extra_entries: Vec<_> = Vec::new();
1479 for asset in &build.assets {
1480 let logical = format!("assets/{}", asset.logical_path);
1481 asset_paths.insert(logical.clone());
1482 extra_entries.push((logical, asset.source.clone()));
1483 }
1484 let mut mapped_extra = map_extra_files(
1485 &build.extra_files,
1486 &mut asset_paths,
1487 dev_mode,
1488 &mut warnings,
1489 );
1490 extra_entries.append(&mut mapped_extra);
1491 extra_entries.sort_by(|a, b| a.0.cmp(&b.0));
1492 for (logical, source) in extra_entries {
1493 if !written_paths.insert(logical.clone()) {
1494 continue;
1495 }
1496 let bytes = fs::read(&source)
1497 .with_context(|| format!("failed to read extra file {}", source.display()))?;
1498 record_sbom_entry(
1499 &mut sbom_entries,
1500 &logical,
1501 &bytes,
1502 "application/octet-stream",
1503 );
1504 write_zip_entry(&mut writer, &logical, &bytes, options)?;
1505 }
1506
1507 sbom_entries.sort_by(|a, b| a.path.cmp(&b.path));
1508 let sbom_doc = SbomDocument {
1509 format: SBOM_FORMAT.to_string(),
1510 files: sbom_entries,
1511 };
1512 let sbom_bytes = canonical::to_canonical_cbor_allow_floats(&sbom_doc)
1513 .context("failed to encode canonical sbom.cbor")?;
1514 write_zip_entry(&mut writer, "sbom.cbor", &sbom_bytes, options)?;
1515
1516 writer
1517 .finish()
1518 .context("failed to finalise gtpack archive")?;
1519 Ok(warnings)
1520}
1521
1522async fn collect_lock_component_artifacts(
1523 lock: &greentic_pack::pack_lock::PackLockV1,
1524 runtime: &RuntimeContext,
1525 bundle: BundleMode,
1526 allow_missing: bool,
1527) -> Result<Vec<LockComponentBinary>> {
1528 let dist = DistClient::new(DistOptions {
1529 cache_dir: runtime.cache_dir(),
1530 allow_tags: true,
1531 offline: runtime.network_policy() == NetworkPolicy::Offline,
1532 allow_insecure_local_http: false,
1533 ..DistOptions::default()
1534 });
1535
1536 let mut artifacts = Vec::new();
1537 let mut seen_paths = BTreeSet::new();
1538 for comp in lock.components.values() {
1539 let Some(reference) = comp.r#ref.as_ref() else {
1540 continue;
1541 };
1542 if reference.starts_with("file://") {
1543 continue;
1544 }
1545 let parsed = ComponentSourceRef::from_str(reference).ok();
1546 let is_tag = parsed.as_ref().map(|r| r.is_tag()).unwrap_or(false);
1547 let should_bundle = is_tag || bundle == BundleMode::Cache;
1548 if !should_bundle {
1549 continue;
1550 }
1551
1552 let resolved = if is_tag {
1553 let item = if runtime.network_policy() == NetworkPolicy::Offline {
1554 dist.open_cached(&comp.resolved_digest).map_err(|err| {
1555 anyhow!(
1556 "tag ref {} must be bundled but cache is missing ({})",
1557 reference,
1558 err
1559 )
1560 })?
1561 } else {
1562 let source = dist
1563 .parse_source(reference)
1564 .map_err(|err| anyhow!("failed to parse {}: {}", reference, err))?;
1565 let descriptor = dist
1566 .resolve(source, greentic_distributor_client::ResolvePolicy)
1567 .await
1568 .map_err(|err| anyhow!("failed to resolve {}: {}", reference, err))?;
1569 dist.fetch(&descriptor, greentic_distributor_client::CachePolicy)
1570 .await
1571 .map_err(|err| anyhow!("failed to fetch {}: {}", reference, err))?
1572 };
1573 let cache_path = item.cache_path.clone().ok_or_else(|| {
1574 anyhow!("tag ref {} resolved but cache path is missing", reference)
1575 })?;
1576 ResolvedLockItem { cache_path }
1577 } else {
1578 let mut resolved = dist
1579 .open_cached(&comp.resolved_digest)
1580 .ok()
1581 .and_then(|item| item.cache_path.clone().map(|path| (item, path)));
1582 if resolved.is_none()
1583 && runtime.network_policy() != NetworkPolicy::Offline
1584 && !allow_missing
1585 && reference.starts_with("oci://")
1586 {
1587 let source = dist
1588 .parse_source(reference)
1589 .map_err(|err| anyhow!("failed to parse {}: {}", reference, err))?;
1590 let descriptor = dist
1591 .resolve(source, greentic_distributor_client::ResolvePolicy)
1592 .await
1593 .map_err(|err| anyhow!("failed to resolve {}: {}", reference, err))?;
1594 let item = dist
1595 .fetch(&descriptor, greentic_distributor_client::CachePolicy)
1596 .await
1597 .map_err(|err| anyhow!("failed to fetch {}: {}", reference, err))?;
1598 if let Some(path) = item.cache_path.clone() {
1599 resolved = Some((item, path));
1600 }
1601 }
1602 let Some((_item, path)) = resolved else {
1603 if runtime.network_policy() == NetworkPolicy::Offline {
1604 if allow_missing {
1605 eprintln!(
1606 "warning: component {} is not cached; skipping embed",
1607 comp.component_id
1608 );
1609 continue;
1610 }
1611 anyhow::bail!(
1612 "component {} requires network access ({}) but cache is missing; offline builds cannot download artifacts",
1613 comp.component_id,
1614 reference
1615 );
1616 }
1617 eprintln!(
1618 "warning: component {} is not cached; skipping embed",
1619 comp.component_id
1620 );
1621 continue;
1622 };
1623 ResolvedLockItem { cache_path: path }
1624 };
1625
1626 let cache_path = resolved.cache_path;
1627 let bytes = fs::read(&cache_path)
1628 .with_context(|| format!("failed to read cached component {}", cache_path.display()))?;
1629 let wasm_sha256 = format!("{:x}", Sha256::digest(&bytes));
1630 let logical_path = if is_tag {
1631 format!("blobs/sha256/{}.wasm", wasm_sha256)
1632 } else {
1633 format!("components/{}.wasm", comp.component_id)
1634 };
1635
1636 if seen_paths.insert(logical_path.clone()) {
1637 artifacts.push(LockComponentBinary {
1638 component_id: comp.component_id.clone(),
1639 logical_path: logical_path.clone(),
1640 source: cache_path.clone(),
1641 });
1642 }
1643 }
1644
1645 Ok(artifacts)
1646}
1647
1648struct ResolvedLockItem {
1649 cache_path: PathBuf,
1650}
1651
1652struct MaterializedComponents {
1653 components: Vec<ComponentManifest>,
1654 manifest_files: Vec<ComponentManifestFile>,
1655 manifest_paths: Option<BTreeMap<String, String>>,
1656}
1657
1658fn record_sbom_entry(entries: &mut Vec<SbomEntry>, path: &str, bytes: &[u8], media_type: &str) {
1659 entries.push(SbomEntry {
1660 path: path.to_string(),
1661 size: bytes.len() as u64,
1662 hash_blake3: blake3::hash(bytes).to_hex().to_string(),
1663 media_type: media_type.to_string(),
1664 });
1665}
1666
1667fn write_zip_entry(
1668 writer: &mut ZipWriter<std::fs::File>,
1669 logical_path: &str,
1670 bytes: &[u8],
1671 options: SimpleFileOptions,
1672) -> Result<()> {
1673 writer
1674 .start_file(logical_path, options)
1675 .with_context(|| format!("failed to start {}", logical_path))?;
1676 writer
1677 .write_all(bytes)
1678 .with_context(|| format!("failed to write {}", logical_path))?;
1679 Ok(())
1680}
1681
1682fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
1683 if let Some(parent) = path.parent() {
1684 fs::create_dir_all(parent)
1685 .with_context(|| format!("failed to create directory {}", parent.display()))?;
1686 }
1687 fs::write(path, bytes).with_context(|| format!("failed to write {}", path.display()))?;
1688 Ok(())
1689}
1690
1691fn write_stub_wasm(path: &Path) -> Result<()> {
1692 const STUB: &[u8] = &[0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
1693 write_bytes(path, STUB)
1694}
1695
1696fn collect_component_manifest_files(
1697 components: &[ComponentBinary],
1698 extra: &[ComponentManifestFile],
1699) -> Vec<ComponentManifestFile> {
1700 let mut files: Vec<ComponentManifestFile> = components
1701 .iter()
1702 .map(|binary| ComponentManifestFile {
1703 component_id: binary.id.clone(),
1704 manifest_path: binary.manifest_path.clone(),
1705 manifest_bytes: binary.manifest_bytes.clone(),
1706 manifest_hash_sha256: binary.manifest_hash_sha256.clone(),
1707 })
1708 .collect();
1709 files.extend(extra.iter().cloned());
1710 files.sort_by(|a, b| a.component_id.cmp(&b.component_id));
1711 files.dedup_by(|a, b| a.component_id == b.component_id);
1712 files
1713}
1714
1715fn materialize_flow_components(
1716 pack_dir: &Path,
1717 flows: &[PackFlowEntry],
1718 pack_lock: &greentic_pack::pack_lock::PackLockV1,
1719 components: &[ComponentBinary],
1720 lock_components: &[LockComponentBinary],
1721 require_component_manifests: bool,
1722) -> Result<MaterializedComponents> {
1723 let referenced = collect_flow_component_ids(flows);
1724 if referenced.is_empty() {
1725 return Ok(MaterializedComponents {
1726 components: Vec::new(),
1727 manifest_files: Vec::new(),
1728 manifest_paths: None,
1729 });
1730 }
1731
1732 let mut existing = BTreeSet::new();
1733 for component in components {
1734 existing.insert(component.id.clone());
1735 }
1736
1737 let mut lock_by_id = BTreeMap::new();
1738 for (key, entry) in &pack_lock.components {
1739 lock_by_id.insert(key.clone(), entry);
1740 }
1741
1742 let mut bundle_sources_by_component = BTreeMap::new();
1743 for entry in lock_components {
1744 bundle_sources_by_component.insert(entry.component_id.clone(), entry.source.clone());
1745 }
1746
1747 let mut materialized_components = Vec::new();
1748 let mut manifest_files = Vec::new();
1749 let mut manifest_paths: BTreeMap<String, String> = BTreeMap::new();
1750
1751 for component_id in referenced {
1752 if existing.contains(&component_id) {
1753 continue;
1754 }
1755
1756 let lock_entry = lock_by_id.get(&component_id).copied();
1757 let Some(lock_entry) = lock_entry else {
1758 handle_missing_component_manifest(&component_id, None, require_component_manifests)?;
1759 continue;
1760 };
1761 let bundled_source = bundle_sources_by_component.get(&component_id);
1762 if bundled_source.is_none() {
1763 if require_component_manifests {
1764 anyhow::bail!(
1765 "component {} is not bundled; cannot materialize manifest without local artifacts",
1766 lock_entry.component_id
1767 );
1768 }
1769 eprintln!(
1770 "warning: component {} is not bundled; pack will emit PACK_COMPONENT_NOT_EXPLICIT",
1771 lock_entry.component_id
1772 );
1773 continue;
1774 }
1775
1776 let manifest =
1777 load_component_manifest_for_lock(pack_dir, &lock_entry.component_id, bundled_source)?;
1778
1779 let Some(manifest) = manifest else {
1780 handle_missing_component_manifest(&component_id, None, require_component_manifests)?;
1781 continue;
1782 };
1783
1784 if manifest.id.as_str() != lock_entry.component_id.as_str() {
1785 anyhow::bail!(
1786 "component manifest id {} does not match pack.lock component_id {}",
1787 manifest.id.as_str(),
1788 lock_entry.component_id.as_str()
1789 );
1790 }
1791
1792 let manifest_file = component_manifest_file_from_manifest(&manifest)?;
1793 manifest_paths.insert(
1794 manifest.id.as_str().to_string(),
1795 manifest_file.manifest_path.clone(),
1796 );
1797 manifest_paths.insert(
1798 lock_entry.component_id.clone(),
1799 manifest_file.manifest_path.clone(),
1800 );
1801
1802 materialized_components.push(manifest);
1803 manifest_files.push(manifest_file);
1804 }
1805
1806 let manifest_paths = if manifest_paths.is_empty() {
1807 None
1808 } else {
1809 Some(manifest_paths)
1810 };
1811
1812 Ok(MaterializedComponents {
1813 components: materialized_components,
1814 manifest_files,
1815 manifest_paths,
1816 })
1817}
1818
1819fn collect_flow_component_ids(flows: &[PackFlowEntry]) -> BTreeSet<String> {
1820 let mut ids = BTreeSet::new();
1821 for flow in flows {
1822 for node in flow.flow.nodes.values() {
1823 if node.component.pack_alias.is_some() {
1824 continue;
1825 }
1826 let id = node.component.id.as_str();
1827 if !id.is_empty() && !is_builtin_component_id(id) {
1828 ids.insert(id.to_string());
1829 }
1830 }
1831 }
1832 ids
1833}
1834
1835fn is_builtin_component_id(id: &str) -> bool {
1836 matches!(id, "session.wait" | "flow.call" | "provider.invoke") || id.starts_with("emit.")
1837}
1838
1839fn load_component_manifest_for_lock(
1840 pack_dir: &Path,
1841 component_id: &str,
1842 bundled_source: Option<&PathBuf>,
1843) -> Result<Option<ComponentManifest>> {
1844 let mut search_paths = Vec::new();
1845 search_paths.extend(component_manifest_search_paths(pack_dir, component_id));
1846 if let Some(source) = bundled_source
1847 && let Some(parent) = source.parent()
1848 {
1849 search_paths.push(parent.join("component.manifest.cbor"));
1850 search_paths.push(parent.join("component.manifest.json"));
1851 }
1852
1853 for path in search_paths {
1854 if path.exists() {
1855 return Ok(Some(load_component_manifest_from_file(&path)?));
1856 }
1857 }
1858
1859 Ok(None)
1860}
1861
1862fn component_manifest_search_paths(pack_dir: &Path, name: &str) -> Vec<PathBuf> {
1863 vec![
1864 pack_dir
1865 .join("components")
1866 .join(format!("{name}.manifest.cbor")),
1867 pack_dir
1868 .join("components")
1869 .join(format!("{name}.manifest.json")),
1870 pack_dir
1871 .join("components")
1872 .join(name)
1873 .join("component.manifest.cbor"),
1874 pack_dir
1875 .join("components")
1876 .join(name)
1877 .join("component.manifest.json"),
1878 ]
1879}
1880
1881fn load_component_manifest_from_file(path: &Path) -> Result<ComponentManifest> {
1882 let bytes = fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
1883 if path
1884 .extension()
1885 .and_then(|ext| ext.to_str())
1886 .is_some_and(|ext| ext.eq_ignore_ascii_case("cbor"))
1887 {
1888 let manifest = serde_cbor::from_slice(&bytes)
1889 .with_context(|| format!("{} is not valid CBOR", path.display()))?;
1890 return Ok(manifest);
1891 }
1892
1893 let manifest = serde_json::from_slice(&bytes)
1894 .with_context(|| format!("{} is not valid JSON", path.display()))?;
1895 Ok(manifest)
1896}
1897
1898fn component_manifest_file_from_manifest(
1899 manifest: &ComponentManifest,
1900) -> Result<ComponentManifestFile> {
1901 let manifest_bytes = canonical::to_canonical_cbor_allow_floats(manifest)
1902 .context("encode component manifest to canonical cbor")?;
1903 let mut sha = Sha256::new();
1904 sha.update(&manifest_bytes);
1905 let manifest_hash_sha256 = format!("sha256:{:x}", sha.finalize());
1906 let manifest_path = format!("components/{}.manifest.cbor", manifest.id.as_str());
1907
1908 Ok(ComponentManifestFile {
1909 component_id: manifest.id.as_str().to_string(),
1910 manifest_path,
1911 manifest_bytes,
1912 manifest_hash_sha256,
1913 })
1914}
1915
1916fn handle_missing_component_manifest(
1917 component_id: &str,
1918 component_name: Option<&str>,
1919 require_component_manifests: bool,
1920) -> Result<()> {
1921 let label = component_name.unwrap_or(component_id);
1922 if require_component_manifests {
1923 anyhow::bail!(
1924 "component manifest metadata missing for {} (supply component.manifest.json or use --require-component-manifests=false)",
1925 label
1926 );
1927 }
1928 eprintln!(
1929 "warning: component manifest metadata missing for {}; pack will emit PACK_COMPONENT_NOT_EXPLICIT",
1930 label
1931 );
1932 Ok(())
1933}
1934
1935fn aggregate_secret_requirements(
1936 components: &[ComponentConfig],
1937 override_path: Option<&Path>,
1938 default_scope: Option<&str>,
1939) -> Result<Vec<SecretRequirement>> {
1940 let default_scope = default_scope.map(parse_default_scope).transpose()?;
1941 let mut merged: BTreeMap<(String, String, String), SecretRequirement> = BTreeMap::new();
1942
1943 let mut process_req = |req: &SecretRequirement, source: &str| -> Result<()> {
1944 let mut req = req.clone();
1945 if req.scope.is_none() {
1946 if let Some(scope) = default_scope.clone() {
1947 req.scope = Some(scope);
1948 tracing::warn!(
1949 key = %secret_key_string(&req),
1950 source,
1951 "secret requirement missing scope; applying default scope"
1952 );
1953 } else {
1954 anyhow::bail!(
1955 "secret requirement {} from {} is missing scope (provide --default-secret-scope or fix the component manifest)",
1956 secret_key_string(&req),
1957 source
1958 );
1959 }
1960 }
1961 let scope = req.scope.as_ref().expect("scope present");
1962 let fmt = fmt_key(&req);
1963 let key_tuple = (req.key.clone().into(), scope_key(scope), fmt.clone());
1964 if let Some(existing) = merged.get_mut(&key_tuple) {
1965 merge_requirement(existing, &req);
1966 } else {
1967 merged.insert(key_tuple, req);
1968 }
1969 Ok(())
1970 };
1971
1972 for component in components {
1973 if let Some(secret_caps) = component.capabilities.host.secrets.as_ref() {
1974 for req in &secret_caps.required {
1975 process_req(req, &component.id)?;
1976 }
1977 }
1978 }
1979
1980 if let Some(path) = override_path {
1981 let contents = fs::read_to_string(path)
1982 .with_context(|| format!("failed to read secrets override {}", path.display()))?;
1983 let value: serde_json::Value = if path
1984 .extension()
1985 .and_then(|ext| ext.to_str())
1986 .map(|ext| ext.eq_ignore_ascii_case("yaml") || ext.eq_ignore_ascii_case("yml"))
1987 .unwrap_or(false)
1988 {
1989 let yaml: YamlValue = serde_yaml_bw::from_str(&contents)
1990 .with_context(|| format!("{} is not valid YAML", path.display()))?;
1991 serde_json::to_value(yaml).context("failed to normalise YAML secrets override")?
1992 } else {
1993 serde_json::from_str(&contents)
1994 .with_context(|| format!("{} is not valid JSON", path.display()))?
1995 };
1996
1997 let overrides: Vec<SecretRequirement> =
1998 serde_json::from_value(value).with_context(|| {
1999 format!(
2000 "{} must be an array of secret requirements (migration bridge)",
2001 path.display()
2002 )
2003 })?;
2004 for req in &overrides {
2005 process_req(req, &format!("override:{}", path.display()))?;
2006 }
2007 }
2008
2009 let mut out: Vec<SecretRequirement> = merged.into_values().collect();
2010 out.sort_by(|a, b| {
2011 let a_scope = a.scope.as_ref().map(scope_key).unwrap_or_default();
2012 let b_scope = b.scope.as_ref().map(scope_key).unwrap_or_default();
2013 (a_scope, secret_key_string(a), fmt_key(a)).cmp(&(
2014 b_scope,
2015 secret_key_string(b),
2016 fmt_key(b),
2017 ))
2018 });
2019 Ok(out)
2020}
2021
2022fn fmt_key(req: &SecretRequirement) -> String {
2023 req.format
2024 .as_ref()
2025 .map(|f| format!("{:?}", f))
2026 .unwrap_or_else(|| "unspecified".to_string())
2027}
2028
2029fn scope_key(scope: &SecretScope) -> String {
2030 format!(
2031 "{}/{}/{}",
2032 &scope.env,
2033 &scope.tenant,
2034 scope
2035 .team
2036 .as_deref()
2037 .map(|t| t.to_string())
2038 .unwrap_or_else(|| "_".to_string())
2039 )
2040}
2041
2042fn secret_key_string(req: &SecretRequirement) -> String {
2043 let key: String = req.key.clone().into();
2044 key
2045}
2046
2047fn merge_requirement(base: &mut SecretRequirement, incoming: &SecretRequirement) {
2048 if base.description.is_none() {
2049 base.description = incoming.description.clone();
2050 }
2051 if let Some(schema) = &incoming.schema {
2052 if base.schema.is_none() {
2053 base.schema = Some(schema.clone());
2054 } else if base.schema.as_ref() != Some(schema) {
2055 tracing::warn!(
2056 key = %secret_key_string(base),
2057 "conflicting secret schema encountered; keeping first"
2058 );
2059 }
2060 }
2061
2062 if !incoming.examples.is_empty() {
2063 for example in &incoming.examples {
2064 if !base.examples.contains(example) {
2065 base.examples.push(example.clone());
2066 }
2067 }
2068 }
2069
2070 base.required = base.required || incoming.required;
2071}
2072
2073fn parse_default_scope(raw: &str) -> Result<SecretScope> {
2074 let parts: Vec<_> = raw.split('/').collect();
2075 if parts.len() < 2 || parts.len() > 3 {
2076 anyhow::bail!(
2077 "default secret scope must be ENV/TENANT or ENV/TENANT/TEAM (got {})",
2078 raw
2079 );
2080 }
2081 Ok(SecretScope {
2082 env: parts[0].to_string(),
2083 tenant: parts[1].to_string(),
2084 team: parts.get(2).map(|s| s.to_string()),
2085 })
2086}
2087
2088fn write_secret_requirements_file(
2089 pack_root: &Path,
2090 requirements: &[SecretRequirement],
2091 logical_name: &str,
2092) -> Result<PathBuf> {
2093 let path = pack_root.join(".packc").join(logical_name);
2094 if let Some(parent) = path.parent() {
2095 fs::create_dir_all(parent)
2096 .with_context(|| format!("failed to create {}", parent.display()))?;
2097 }
2098 let data = serde_json::to_vec_pretty(&requirements)
2099 .context("failed to serialise secret requirements")?;
2100 fs::write(&path, data).with_context(|| format!("failed to write {}", path.display()))?;
2101 Ok(path)
2102}
2103
2104fn resolve_secret_requirements_override(
2105 pack_root: &Path,
2106 override_path: Option<&PathBuf>,
2107) -> Option<PathBuf> {
2108 if let Some(path) = override_path {
2109 return Some(path.clone());
2110 }
2111 find_secret_requirements_file(pack_root)
2112}
2113
2114fn find_secret_requirements_file(pack_root: &Path) -> Option<PathBuf> {
2115 for name in ["secrets_requirements.json", "secret-requirements.json"] {
2116 let candidate = pack_root.join(name);
2117 if candidate.is_file() {
2118 return Some(candidate);
2119 }
2120 }
2121 None
2122}
2123
2124#[cfg(test)]
2125mod tests {
2126 use super::*;
2127 use crate::config::BootstrapConfig;
2128 use crate::runtime::resolve_runtime;
2129 use greentic_pack::pack_lock::{LockedComponent, PackLockV1};
2130 use greentic_types::cbor::canonical;
2131 use greentic_types::decode_pack_manifest;
2132 use greentic_types::flow::FlowKind;
2133 use greentic_types::schemas::common::schema_ir::{AdditionalProperties, SchemaIr};
2134 use greentic_types::schemas::component::v0_6_0::{
2135 ComponentDescribe, ComponentInfo, ComponentOperation, ComponentRunInput,
2136 ComponentRunOutput, schema_hash,
2137 };
2138 use serde_json::json;
2139 use sha2::{Digest, Sha256};
2140 use std::collections::{BTreeMap, BTreeSet};
2141 use std::fs::File;
2142 use std::io::Read;
2143 use std::path::Path;
2144 use std::{fs, path::PathBuf};
2145 use tempfile::tempdir;
2146 use zip::ZipArchive;
2147
2148 fn sample_hex(ch: char) -> String {
2149 std::iter::repeat_n(ch, 64).collect()
2150 }
2151
2152 fn sample_lock_component(
2153 component_id: &str,
2154 reference: Option<&str>,
2155 digest_hex: char,
2156 ) -> LockedComponent {
2157 LockedComponent {
2158 component_id: component_id.to_string(),
2159 r#ref: reference.map(|value| value.to_string()),
2160 abi_version: "0.6.0".to_string(),
2161 resolved_digest: format!("sha256:{}", sample_hex(digest_hex)),
2162 describe_hash: sample_hex(digest_hex),
2163 operations: Vec::new(),
2164 world: None,
2165 component_version: None,
2166 role: None,
2167 }
2168 }
2169
2170 fn write_describe_sidecar(wasm_path: &Path, component_id: &str) {
2171 let input_schema = SchemaIr::String {
2172 min_len: None,
2173 max_len: None,
2174 regex: None,
2175 format: None,
2176 };
2177 let output_schema = SchemaIr::String {
2178 min_len: None,
2179 max_len: None,
2180 regex: None,
2181 format: None,
2182 };
2183 let config_schema = SchemaIr::Object {
2184 properties: BTreeMap::new(),
2185 required: Vec::new(),
2186 additional: AdditionalProperties::Forbid,
2187 };
2188 let hash = schema_hash(&input_schema, &output_schema, &config_schema).expect("schema hash");
2189 let operation = ComponentOperation {
2190 id: "run".to_string(),
2191 display_name: None,
2192 input: ComponentRunInput {
2193 schema: input_schema,
2194 },
2195 output: ComponentRunOutput {
2196 schema: output_schema,
2197 },
2198 defaults: BTreeMap::new(),
2199 redactions: Vec::new(),
2200 constraints: BTreeMap::new(),
2201 schema_hash: hash,
2202 };
2203 let describe = ComponentDescribe {
2204 info: ComponentInfo {
2205 id: component_id.to_string(),
2206 version: "0.1.0".to_string(),
2207 role: "tool".to_string(),
2208 display_name: None,
2209 },
2210 provided_capabilities: Vec::new(),
2211 required_capabilities: Vec::new(),
2212 metadata: BTreeMap::new(),
2213 operations: vec![operation],
2214 config_schema,
2215 };
2216 let bytes = canonical::to_canonical_cbor_allow_floats(&describe).expect("encode describe");
2217 let describe_path = PathBuf::from(format!("{}.describe.cbor", wasm_path.display()));
2218 fs::write(describe_path, bytes).expect("write describe cache");
2219 }
2220
2221 #[test]
2222 fn map_kind_accepts_known_values() {
2223 assert!(matches!(
2224 map_kind("application").unwrap(),
2225 PackKind::Application
2226 ));
2227 assert!(matches!(map_kind("provider").unwrap(), PackKind::Provider));
2228 assert!(matches!(
2229 map_kind("infrastructure").unwrap(),
2230 PackKind::Infrastructure
2231 ));
2232 assert!(matches!(map_kind("library").unwrap(), PackKind::Library));
2233 assert!(map_kind("unknown").is_err());
2234 }
2235
2236 #[test]
2237 fn collect_assets_preserves_relative_paths() {
2238 let root = PathBuf::from("/packs/demo");
2239 let assets = vec![AssetConfig {
2240 path: root.join("assets").join("foo.txt"),
2241 }];
2242 let collected = collect_assets(&assets, &root).expect("collect assets");
2243 assert_eq!(collected[0].logical_path, "assets/foo.txt");
2244 }
2245
2246 fn write_sample_manifest(path: &Path, component_id: &str) {
2247 let manifest: ComponentManifest = serde_json::from_value(json!({
2248 "id": component_id,
2249 "version": "0.1.0",
2250 "supports": [],
2251 "world": "greentic:component/component@0.5.0",
2252 "profiles": { "default": "stateless", "supported": ["stateless"] },
2253 "capabilities": { "wasi": {}, "host": {} },
2254 "operations": [],
2255 "resources": {},
2256 "dev_flows": {}
2257 }))
2258 .expect("manifest");
2259 let bytes = serde_cbor::to_vec(&manifest).expect("encode manifest");
2260 fs::write(path, bytes).expect("write manifest");
2261 }
2262
2263 #[test]
2264 fn load_component_manifest_from_disk_supports_id_specific_files() {
2265 let temp = tempdir().expect("temp dir");
2266 let components = temp.path().join("components");
2267 fs::create_dir_all(&components).expect("create components dir");
2268 let wasm = components.join("component.wasm");
2269 fs::write(&wasm, b"wasm").expect("write wasm");
2270 let manifest_name = components.join("foo.component.manifest.cbor");
2271 write_sample_manifest(&manifest_name, "foo.component");
2272
2273 let manifest =
2274 load_component_manifest_from_disk(&wasm, "foo.component").expect("load manifest");
2275 let manifest = manifest.expect("manifest present");
2276 assert_eq!(manifest.id.to_string(), "foo.component");
2277 }
2278
2279 #[test]
2280 fn load_component_manifest_from_disk_accepts_generic_names() {
2281 let temp = tempdir().expect("temp dir");
2282 let components = temp.path().join("components");
2283 fs::create_dir_all(&components).expect("create components dir");
2284 let wasm = components.join("component.wasm");
2285 fs::write(&wasm, b"wasm").expect("write wasm");
2286 let manifest_name = components.join("component.manifest.cbor");
2287 write_sample_manifest(&manifest_name, "component");
2288
2289 let manifest =
2290 load_component_manifest_from_disk(&wasm, "component").expect("load manifest");
2291 let manifest = manifest.expect("manifest present");
2292 assert_eq!(manifest.id.to_string(), "component");
2293 }
2294
2295 #[test]
2296 fn load_component_manifest_from_disk_walks_up_from_nested_target_paths() {
2297 let temp = tempdir().expect("temp dir");
2298 let component_root = temp.path().join("components/demo-component");
2299 let release_dir = component_root.join("target/wasm32-wasip2/release");
2300 fs::create_dir_all(&release_dir).expect("create release dir");
2301 let wasm = release_dir.join("demo_component.wasm");
2302 fs::write(&wasm, b"wasm").expect("write wasm");
2303 let manifest_name = component_root.join("component.manifest.cbor");
2304 write_sample_manifest(&manifest_name, "dev.local.demo-component");
2305
2306 let manifest = load_component_manifest_from_disk(&wasm, "dev.local.demo-component")
2307 .expect("load manifest");
2308 let manifest = manifest.expect("manifest present");
2309 assert_eq!(manifest.id.to_string(), "dev.local.demo-component");
2310 }
2311
2312 #[test]
2313 fn load_component_manifest_from_disk_does_not_pick_unrelated_parent_manifest() {
2314 let temp = tempdir().expect("temp dir");
2315 let parent_manifest = temp.path().join("component.manifest.cbor");
2316 write_sample_manifest(&parent_manifest, "wrong.parent.component");
2317
2318 let isolated = temp.path().join("isolated");
2319 fs::create_dir_all(&isolated).expect("create isolated dir");
2320 let wasm = isolated.join("component.wasm");
2321 fs::write(&wasm, b"wasm").expect("write wasm");
2322
2323 let manifest =
2324 load_component_manifest_from_disk(&wasm, "expected.component").expect("load manifest");
2325 assert!(
2326 manifest.is_none(),
2327 "must not read unrelated parent manifest"
2328 );
2329 }
2330
2331 #[test]
2332 fn resolve_component_artifacts_requires_manifest_unless_migration_flag_set() {
2333 let temp = tempdir().expect("temp dir");
2334 let wasm = temp.path().join("component.wasm");
2335 fs::write(&wasm, [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).expect("write wasm");
2336
2337 let cfg: ComponentConfig = serde_json::from_value(json!({
2338 "id": "demo.component",
2339 "version": "0.1.0",
2340 "world": "greentic:component/component@0.6.0",
2341 "supports": [],
2342 "profiles": { "default": "stateless", "supported": ["stateless"] },
2343 "capabilities": { "wasi": {}, "host": {} },
2344 "operations": [],
2345 "wasm": wasm.to_string_lossy()
2346 }))
2347 .expect("component config");
2348
2349 let err = match resolve_component_artifacts(&cfg, false) {
2350 Ok(_) => panic!("missing manifest must fail"),
2351 Err(err) => err,
2352 };
2353 assert!(
2354 err.to_string().contains("missing component.manifest.json"),
2355 "unexpected error: {err}"
2356 );
2357
2358 let (manifest, _binary) =
2359 resolve_component_artifacts(&cfg, true).expect("migration flag allows fallback");
2360 assert_eq!(manifest.id.to_string(), "demo.component");
2361 }
2362
2363 #[test]
2364 fn collect_extra_dir_files_skips_hidden_and_known_dirs() {
2365 let temp = tempdir().expect("temp dir");
2366 let root = temp.path();
2367 fs::create_dir_all(root.join("schemas")).expect("schemas dir");
2368 fs::create_dir_all(root.join("schemas").join(".nested")).expect("nested hidden dir");
2369 fs::create_dir_all(root.join(".hidden")).expect("hidden dir");
2370 fs::create_dir_all(root.join("assets")).expect("assets dir");
2371 fs::write(root.join("README.txt"), b"root").expect("root file");
2372 fs::write(root.join("schemas").join("config.schema.json"), b"{}").expect("schema file");
2373 fs::write(
2374 root.join("schemas").join(".nested").join("skip.json"),
2375 b"{}",
2376 )
2377 .expect("nested hidden file");
2378 fs::write(root.join(".hidden").join("secret.txt"), b"nope").expect("hidden file");
2379 fs::write(root.join("assets").join("asset.txt"), b"nope").expect("asset file");
2380
2381 let collected = collect_extra_dir_files(root).expect("collect extra dirs");
2382 let paths: BTreeSet<_> = collected.iter().map(|e| e.logical_path.as_str()).collect();
2383 assert!(paths.contains("README.txt"));
2384 assert!(paths.contains("schemas/config.schema.json"));
2385 assert!(!paths.contains("schemas/.nested/skip.json"));
2386 assert!(!paths.contains(".hidden/secret.txt"));
2387 assert!(paths.contains("assets/asset.txt"));
2388 }
2389
2390 #[test]
2391 fn collect_extra_dir_files_skips_reserved_sbom_files() {
2392 let temp = tempdir().expect("temp dir");
2393 let root = temp.path();
2394 fs::write(root.join("sbom.cbor"), b"binary").expect("sbom file");
2395 fs::write(root.join("sbom.json"), b"{}").expect("sbom json");
2396 fs::write(root.join("README.md"), b"hello").expect("root file");
2397
2398 let collected = collect_extra_dir_files(root).expect("collect extra dirs");
2399 let paths: BTreeSet<_> = collected.iter().map(|e| e.logical_path.as_str()).collect();
2400 assert!(paths.contains("README.md"));
2401 assert!(!paths.contains("sbom.cbor"));
2402 assert!(!paths.contains("sbom.json"));
2403 }
2404
2405 #[test]
2406 fn build_bootstrap_requires_known_references() {
2407 let config = pack_config_with_bootstrap(BootstrapConfig {
2408 install_flow: Some("flow.a".to_string()),
2409 upgrade_flow: None,
2410 installer_component: Some("component.a".to_string()),
2411 });
2412 let flows = vec![flow_entry("flow.a")];
2413 let components = vec![minimal_component_manifest("component.a")];
2414
2415 let bootstrap = build_bootstrap(&config, &flows, &components)
2416 .expect("bootstrap populated")
2417 .expect("bootstrap present");
2418
2419 assert_eq!(bootstrap.install_flow.as_deref(), Some("flow.a"));
2420 assert_eq!(bootstrap.upgrade_flow, None);
2421 assert_eq!(
2422 bootstrap.installer_component.as_deref(),
2423 Some("component.a")
2424 );
2425 }
2426
2427 #[test]
2428 fn build_bootstrap_rejects_unknown_flow() {
2429 let config = pack_config_with_bootstrap(BootstrapConfig {
2430 install_flow: Some("missing".to_string()),
2431 upgrade_flow: None,
2432 installer_component: Some("component.a".to_string()),
2433 });
2434 let flows = vec![flow_entry("flow.a")];
2435 let components = vec![minimal_component_manifest("component.a")];
2436
2437 let err = build_bootstrap(&config, &flows, &components).unwrap_err();
2438 assert!(
2439 err.to_string()
2440 .contains("bootstrap.install_flow references unknown flow"),
2441 "unexpected error: {err}"
2442 );
2443 }
2444
2445 #[test]
2446 fn component_manifest_without_dev_flows_defaults_to_empty() {
2447 let manifest: ComponentManifest = serde_json::from_value(json!({
2448 "id": "component.dev",
2449 "version": "1.0.0",
2450 "supports": ["messaging"],
2451 "world": "greentic:demo@1.0.0",
2452 "profiles": { "default": "default", "supported": ["default"] },
2453 "capabilities": { "wasi": {}, "host": {} },
2454 "operations": [],
2455 "resources": {}
2456 }))
2457 .expect("manifest without dev_flows");
2458
2459 assert!(manifest.dev_flows.is_empty());
2460
2461 let pack_manifest = pack_manifest_with_component(manifest.clone());
2462 let encoded = encode_pack_manifest(&pack_manifest).expect("encode manifest");
2463 let decoded: PackManifest =
2464 greentic_types::decode_pack_manifest(&encoded).expect("decode manifest");
2465 let stored = decoded
2466 .components
2467 .iter()
2468 .find(|item| item.id == manifest.id)
2469 .expect("component present");
2470 assert!(stored.dev_flows.is_empty());
2471 }
2472
2473 #[test]
2474 fn dev_flows_round_trip_in_manifest_and_gtpack() {
2475 let component = manifest_with_dev_flow();
2476 let pack_manifest = pack_manifest_with_component(component.clone());
2477 let manifest_bytes = encode_pack_manifest(&pack_manifest).expect("encode manifest");
2478
2479 let decoded: PackManifest =
2480 greentic_types::decode_pack_manifest(&manifest_bytes).expect("decode manifest");
2481 let decoded_component = decoded
2482 .components
2483 .iter()
2484 .find(|item| item.id == component.id)
2485 .expect("component present");
2486 assert_eq!(decoded_component.dev_flows, component.dev_flows);
2487
2488 let temp = tempdir().expect("temp dir");
2489 let wasm_path = temp.path().join("component.wasm");
2490 write_stub_wasm(&wasm_path).expect("write stub wasm");
2491
2492 let build = BuildProducts {
2493 manifest: pack_manifest,
2494 components: vec![ComponentBinary {
2495 id: component.id.to_string(),
2496 source: wasm_path,
2497 manifest_bytes: serde_cbor::to_vec(&component).expect("component cbor"),
2498 manifest_path: format!("components/{}.manifest.cbor", component.id),
2499 manifest_hash_sha256: {
2500 let mut sha = Sha256::new();
2501 sha.update(serde_cbor::to_vec(&component).expect("component cbor"));
2502 format!("sha256:{:x}", sha.finalize())
2503 },
2504 }],
2505 lock_components: Vec::new(),
2506 component_manifest_files: Vec::new(),
2507 flow_files: Vec::new(),
2508 assets: Vec::new(),
2509 extra_files: Vec::new(),
2510 };
2511
2512 let out = temp.path().join("demo.gtpack");
2513 let warnings = package_gtpack(&out, &manifest_bytes, &build, BundleMode::Cache, false)
2514 .expect("package gtpack");
2515 assert!(warnings.is_empty(), "expected no packaging warnings");
2516
2517 let mut archive = ZipArchive::new(fs::File::open(&out).expect("open gtpack"))
2518 .expect("read gtpack archive");
2519 let mut manifest_entry = archive.by_name("manifest.cbor").expect("manifest.cbor");
2520 let mut stored = Vec::new();
2521 manifest_entry
2522 .read_to_end(&mut stored)
2523 .expect("read manifest");
2524 let decoded: PackManifest =
2525 greentic_types::decode_pack_manifest(&stored).expect("decode packaged manifest");
2526
2527 let stored_component = decoded
2528 .components
2529 .iter()
2530 .find(|item| item.id == component.id)
2531 .expect("component preserved");
2532 assert_eq!(stored_component.dev_flows, component.dev_flows);
2533 }
2534
2535 #[test]
2536 fn prod_gtpack_excludes_forbidden_files() {
2537 let component = manifest_with_dev_flow();
2538 let pack_manifest = pack_manifest_with_component(component.clone());
2539 let manifest_bytes = encode_pack_manifest(&pack_manifest).expect("encode manifest");
2540
2541 let temp = tempdir().expect("temp dir");
2542 let wasm_path = temp.path().join("component.wasm");
2543 write_stub_wasm(&wasm_path).expect("write stub wasm");
2544
2545 let pack_yaml = temp.path().join("pack.yaml");
2546 fs::write(&pack_yaml, "pack").expect("write pack.yaml");
2547 let pack_manifest_json = temp.path().join("pack.manifest.json");
2548 fs::write(&pack_manifest_json, "{}").expect("write manifest json");
2549
2550 let build = BuildProducts {
2551 manifest: pack_manifest,
2552 components: vec![ComponentBinary {
2553 id: component.id.to_string(),
2554 source: wasm_path,
2555 manifest_bytes: serde_cbor::to_vec(&component).expect("component cbor"),
2556 manifest_path: format!("components/{}.manifest.cbor", component.id),
2557 manifest_hash_sha256: {
2558 let mut sha = Sha256::new();
2559 sha.update(serde_cbor::to_vec(&component).expect("component cbor"));
2560 format!("sha256:{:x}", sha.finalize())
2561 },
2562 }],
2563 lock_components: Vec::new(),
2564 component_manifest_files: Vec::new(),
2565 flow_files: Vec::new(),
2566 assets: Vec::new(),
2567 extra_files: vec![
2568 ExtraFile {
2569 logical_path: "pack.yaml".to_string(),
2570 source: pack_yaml,
2571 },
2572 ExtraFile {
2573 logical_path: "pack.manifest.json".to_string(),
2574 source: pack_manifest_json,
2575 },
2576 ],
2577 };
2578
2579 let out = temp.path().join("prod.gtpack");
2580 let warnings = package_gtpack(&out, &manifest_bytes, &build, BundleMode::Cache, false)
2581 .expect("package gtpack");
2582 assert!(
2583 warnings.is_empty(),
2584 "no warnings expected for forbidden drop"
2585 );
2586
2587 let mut archive = ZipArchive::new(fs::File::open(&out).expect("open gtpack"))
2588 .expect("read gtpack archive");
2589 assert!(archive.by_name("pack.yaml").is_err());
2590 assert!(archive.by_name("pack.manifest.json").is_err());
2591 }
2592
2593 #[test]
2594 fn asset_mapping_prefers_assets_version_on_conflict() {
2595 let component = manifest_with_dev_flow();
2596 let pack_manifest = pack_manifest_with_component(component.clone());
2597 let manifest_bytes = encode_pack_manifest(&pack_manifest).expect("encode manifest");
2598
2599 let temp = tempdir().expect("temp dir");
2600 let wasm_path = temp.path().join("component.wasm");
2601 write_stub_wasm(&wasm_path).expect("write stub wasm");
2602
2603 let assets_dir = temp.path().join("assets");
2604 fs::create_dir_all(&assets_dir).expect("create assets dir");
2605 let asset_file = assets_dir.join("README.md");
2606 fs::write(&asset_file, "asset").expect("write asset");
2607 let root_asset = temp.path().join("README.md");
2608 fs::write(&root_asset, "root").expect("write root file");
2609
2610 let build = BuildProducts {
2611 manifest: pack_manifest,
2612 components: vec![ComponentBinary {
2613 id: component.id.to_string(),
2614 source: wasm_path,
2615 manifest_bytes: serde_cbor::to_vec(&component).expect("component cbor"),
2616 manifest_path: format!("components/{}.manifest.cbor", component.id),
2617 manifest_hash_sha256: {
2618 let mut sha = Sha256::new();
2619 sha.update(serde_cbor::to_vec(&component).expect("component cbor"));
2620 format!("sha256:{:x}", sha.finalize())
2621 },
2622 }],
2623 lock_components: Vec::new(),
2624 component_manifest_files: Vec::new(),
2625 flow_files: Vec::new(),
2626 assets: Vec::new(),
2627 extra_files: vec![
2628 ExtraFile {
2629 logical_path: "assets/README.md".to_string(),
2630 source: asset_file,
2631 },
2632 ExtraFile {
2633 logical_path: "README.md".to_string(),
2634 source: root_asset,
2635 },
2636 ],
2637 };
2638
2639 let out = temp.path().join("conflict.gtpack");
2640 let warnings = package_gtpack(&out, &manifest_bytes, &build, BundleMode::Cache, false)
2641 .expect("package gtpack");
2642 assert!(
2643 warnings
2644 .iter()
2645 .any(|w| w.contains("skipping root asset README.md"))
2646 );
2647
2648 let mut archive = ZipArchive::new(fs::File::open(&out).expect("open gtpack"))
2649 .expect("read gtpack archive");
2650 assert!(archive.by_name("README.md").is_err());
2651 assert!(archive.by_name("assets/README.md").is_ok());
2652 }
2653
2654 #[test]
2655 fn root_files_map_under_assets_directory() {
2656 let component = manifest_with_dev_flow();
2657 let pack_manifest = pack_manifest_with_component(component.clone());
2658 let manifest_bytes = encode_pack_manifest(&pack_manifest).expect("encode manifest");
2659
2660 let temp = tempdir().expect("temp dir");
2661 let wasm_path = temp.path().join("component.wasm");
2662 write_stub_wasm(&wasm_path).expect("write stub wasm");
2663 let root_asset = temp.path().join("notes.txt");
2664 fs::write(&root_asset, "notes").expect("write root asset");
2665
2666 let build = BuildProducts {
2667 manifest: pack_manifest,
2668 components: vec![ComponentBinary {
2669 id: component.id.to_string(),
2670 source: wasm_path,
2671 manifest_bytes: serde_cbor::to_vec(&component).expect("component cbor"),
2672 manifest_path: format!("components/{}.manifest.cbor", component.id),
2673 manifest_hash_sha256: {
2674 let mut sha = Sha256::new();
2675 sha.update(serde_cbor::to_vec(&component).expect("component cbor"));
2676 format!("sha256:{:x}", sha.finalize())
2677 },
2678 }],
2679 lock_components: Vec::new(),
2680 component_manifest_files: Vec::new(),
2681 flow_files: Vec::new(),
2682 assets: Vec::new(),
2683 extra_files: vec![ExtraFile {
2684 logical_path: "notes.txt".to_string(),
2685 source: root_asset,
2686 }],
2687 };
2688
2689 let out = temp.path().join("root-assets.gtpack");
2690 let warnings = package_gtpack(&out, &manifest_bytes, &build, BundleMode::Cache, false)
2691 .expect("package gtpack");
2692 assert!(
2693 warnings.iter().all(|w| !w.contains("notes.txt")),
2694 "root asset mapping should not warn without conflict"
2695 );
2696
2697 let mut archive = ZipArchive::new(fs::File::open(&out).expect("open gtpack"))
2698 .expect("read gtpack archive");
2699 assert!(archive.by_name("assets/notes.txt").is_ok());
2700 assert!(archive.by_name("notes.txt").is_err());
2701 }
2702
2703 #[test]
2704 fn prod_gtpack_embeds_secret_requirements_cbor_only() {
2705 let component = manifest_with_dev_flow();
2706 let mut pack_manifest = pack_manifest_with_component(component.clone());
2707 let secret_requirement: SecretRequirement = serde_json::from_value(json!({
2708 "key": "demo/token",
2709 "required": true,
2710 "description": "demo secret",
2711 "scope": { "env": "dev", "tenant": "demo" }
2712 }))
2713 .expect("parse secret requirement");
2714 pack_manifest.secret_requirements = vec![secret_requirement.clone()];
2715 let manifest_bytes = encode_pack_manifest(&pack_manifest).expect("encode manifest");
2716
2717 let temp = tempdir().expect("temp dir");
2718 let wasm_path = temp.path().join("component.wasm");
2719 write_stub_wasm(&wasm_path).expect("write stub wasm");
2720 let secret_file = temp.path().join("secret-requirements.json");
2721 fs::write(&secret_file, "[{}]").expect("write secret json");
2722
2723 let build = BuildProducts {
2724 manifest: pack_manifest,
2725 components: vec![ComponentBinary {
2726 id: component.id.to_string(),
2727 source: wasm_path,
2728 manifest_bytes: serde_cbor::to_vec(&component).expect("component cbor"),
2729 manifest_path: format!("components/{}.manifest.cbor", component.id),
2730 manifest_hash_sha256: {
2731 let mut sha = Sha256::new();
2732 sha.update(serde_cbor::to_vec(&component).expect("component cbor"));
2733 format!("sha256:{:x}", sha.finalize())
2734 },
2735 }],
2736 lock_components: Vec::new(),
2737 component_manifest_files: Vec::new(),
2738 flow_files: Vec::new(),
2739 assets: Vec::new(),
2740 extra_files: vec![ExtraFile {
2741 logical_path: "secret-requirements.json".to_string(),
2742 source: secret_file,
2743 }],
2744 };
2745
2746 let out = temp.path().join("secrets.gtpack");
2747 package_gtpack(&out, &manifest_bytes, &build, BundleMode::Cache, false)
2748 .expect("package gtpack");
2749
2750 let mut archive = ZipArchive::new(fs::File::open(&out).expect("open gtpack"))
2751 .expect("read gtpack archive");
2752 assert!(archive.by_name("secret-requirements.json").is_err());
2753 assert!(archive.by_name("assets/secret-requirements.json").is_err());
2754 assert!(archive.by_name("secrets_requirements.json").is_err());
2755 assert!(archive.by_name("assets/secrets_requirements.json").is_err());
2756
2757 let mut manifest_entry = archive
2758 .by_name("manifest.cbor")
2759 .expect("manifest.cbor present");
2760 let mut manifest_buf = Vec::new();
2761 manifest_entry
2762 .read_to_end(&mut manifest_buf)
2763 .expect("read manifest bytes");
2764 let decoded = decode_pack_manifest(&manifest_buf).expect("decode manifest");
2765 assert_eq!(decoded.secret_requirements, vec![secret_requirement]);
2766 }
2767
2768 #[test]
2769 fn component_sources_extension_respects_bundle() {
2770 let mut components = BTreeMap::new();
2771 components.insert(
2772 "demo.tagged".to_string(),
2773 sample_lock_component(
2774 "demo.tagged",
2775 Some("oci://ghcr.io/demo/component:1.0.0"),
2776 'a',
2777 ),
2778 );
2779 let lock_tag = PackLockV1::new(components);
2780
2781 let mut bundled_paths = BTreeMap::new();
2782 bundled_paths.insert(
2783 "demo.tagged".to_string(),
2784 "blobs/sha256/deadbeef.wasm".to_string(),
2785 );
2786
2787 let ext_none =
2788 merge_component_sources_extension(None, &lock_tag, &bundled_paths, None).expect("ext");
2789 let value = match ext_none
2790 .unwrap()
2791 .get(EXT_COMPONENT_SOURCES_V1)
2792 .and_then(|e| e.inline.as_ref())
2793 {
2794 Some(ExtensionInline::Other(v)) => v.clone(),
2795 _ => panic!("missing inline"),
2796 };
2797 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2798 assert!(matches!(
2799 decoded.components[0].artifact,
2800 ArtifactLocationV1::Inline { .. }
2801 ));
2802
2803 let mut components = BTreeMap::new();
2804 components.insert(
2805 "demo.component".to_string(),
2806 sample_lock_component(
2807 "demo.component",
2808 Some("oci://ghcr.io/demo/component@sha256:deadbeef"),
2809 'b',
2810 ),
2811 );
2812 let lock_digest = PackLockV1::new(components);
2813
2814 let ext_none =
2815 merge_component_sources_extension(None, &lock_digest, &BTreeMap::new(), None)
2816 .expect("ext");
2817 let value = match ext_none
2818 .unwrap()
2819 .get(EXT_COMPONENT_SOURCES_V1)
2820 .and_then(|e| e.inline.as_ref())
2821 {
2822 Some(ExtensionInline::Other(v)) => v.clone(),
2823 _ => panic!("missing inline"),
2824 };
2825 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2826 assert!(matches!(
2827 decoded.components[0].artifact,
2828 ArtifactLocationV1::Remote
2829 ));
2830
2831 let mut components = BTreeMap::new();
2832 components.insert(
2833 "demo.component".to_string(),
2834 sample_lock_component(
2835 "demo.component",
2836 Some("oci://ghcr.io/demo/component@sha256:deadbeef"),
2837 'c',
2838 ),
2839 );
2840 let lock_digest_bundled = PackLockV1::new(components);
2841
2842 let mut bundled_paths = BTreeMap::new();
2843 bundled_paths.insert(
2844 "demo.component".to_string(),
2845 "components/demo.component.wasm".to_string(),
2846 );
2847
2848 let ext_cache =
2849 merge_component_sources_extension(None, &lock_digest_bundled, &bundled_paths, None)
2850 .expect("ext");
2851 let value = match ext_cache
2852 .unwrap()
2853 .get(EXT_COMPONENT_SOURCES_V1)
2854 .and_then(|e| e.inline.as_ref())
2855 {
2856 Some(ExtensionInline::Other(v)) => v.clone(),
2857 _ => panic!("missing inline"),
2858 };
2859 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2860 assert!(matches!(
2861 decoded.components[0].artifact,
2862 ArtifactLocationV1::Inline { .. }
2863 ));
2864 }
2865
2866 #[test]
2867 fn component_sources_extension_skips_file_refs() {
2868 let mut components = BTreeMap::new();
2869 components.insert(
2870 "local.component".to_string(),
2871 sample_lock_component("local.component", Some("file:///tmp/component.wasm"), 'd'),
2872 );
2873 let lock = PackLockV1::new(components);
2874
2875 let ext_none =
2876 merge_component_sources_extension(None, &lock, &BTreeMap::new(), None).expect("ext");
2877 assert!(ext_none.is_none(), "file refs should be omitted");
2878
2879 let mut components = BTreeMap::new();
2880 components.insert(
2881 "local.component".to_string(),
2882 sample_lock_component("local.component", Some("file:///tmp/component.wasm"), 'e'),
2883 );
2884 components.insert(
2885 "remote.component".to_string(),
2886 sample_lock_component(
2887 "remote.component",
2888 Some("oci://ghcr.io/demo/component:2.0.0"),
2889 'f',
2890 ),
2891 );
2892 let lock = PackLockV1::new(components);
2893
2894 let ext_some =
2895 merge_component_sources_extension(None, &lock, &BTreeMap::new(), None).expect("ext");
2896 let value = match ext_some
2897 .unwrap()
2898 .get(EXT_COMPONENT_SOURCES_V1)
2899 .and_then(|e| e.inline.as_ref())
2900 {
2901 Some(ExtensionInline::Other(v)) => v.clone(),
2902 _ => panic!("missing inline"),
2903 };
2904 let decoded = ComponentSourcesV1::from_extension_value(&value).expect("decode");
2905 assert_eq!(decoded.components.len(), 1);
2906 assert!(matches!(
2907 decoded.components[0].source,
2908 ComponentSourceRef::Oci(_)
2909 ));
2910 }
2911
2912 #[test]
2913 fn build_embeds_lock_components_from_cache() {
2914 let rt = tokio::runtime::Runtime::new().expect("runtime");
2915 rt.block_on(async {
2916 let temp = tempdir().expect("temp dir");
2917 let pack_dir = temp.path().join("pack");
2918 fs::create_dir_all(pack_dir.join("flows")).expect("flows dir");
2919 fs::create_dir_all(pack_dir.join("components")).expect("components dir");
2920
2921 let wasm_path = pack_dir.join("components/dummy.wasm");
2922 fs::write(&wasm_path, [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
2923 .expect("write wasm");
2924
2925 let flow_path = pack_dir.join("flows/main.ygtc");
2926 fs::write(
2927 &flow_path,
2928 r#"id: main
2929type: messaging
2930start: call
2931nodes:
2932 call:
2933 handle_message:
2934 text: "hi"
2935 routing: out
2936"#,
2937 )
2938 .expect("write flow");
2939
2940 let cache_dir = temp.path().join("cache");
2941 let cached_bytes = b"cached-component";
2942 let seed_path = temp.path().join("cached-component.wasm");
2943 fs::write(&seed_path, cached_bytes).expect("write seed");
2944 let dist = DistClient::new(DistOptions {
2945 cache_dir: cache_dir.clone(),
2946 allow_tags: true,
2947 offline: false,
2948 allow_insecure_local_http: false,
2949 ..DistOptions::default()
2950 });
2951 let source = dist
2952 .parse_source(&format!("file://{}", seed_path.display()))
2953 .expect("parse source");
2954 let descriptor = dist
2955 .resolve(source, greentic_distributor_client::ResolvePolicy)
2956 .await
2957 .expect("resolve source");
2958 let cached = dist
2959 .fetch(&descriptor, greentic_distributor_client::CachePolicy)
2960 .await
2961 .expect("seed cache");
2962 let digest = cached.descriptor.digest.clone();
2963 let cache_path = cached.cache_path.expect("cache path");
2964 write_describe_sidecar(&cache_path, "dummy.component");
2965
2966 let summary = serde_json::json!({
2967 "schema_version": 1,
2968 "flow": "main.ygtc",
2969 "nodes": {
2970 "call": {
2971 "component_id": "dummy.component",
2972 "source": {
2973 "kind": "oci",
2974 "ref": format!("oci://ghcr.io/demo/component@{digest}")
2975 },
2976 "digest": digest
2977 }
2978 }
2979 });
2980 fs::write(
2981 flow_path.with_extension("ygtc.resolve.summary.json"),
2982 serde_json::to_vec_pretty(&summary).expect("summary json"),
2983 )
2984 .expect("write summary");
2985
2986 let pack_yaml = r#"pack_id: demo.lock-bundle
2987version: 0.1.0
2988kind: application
2989publisher: Test
2990components:
2991 - id: dummy.component
2992 version: "0.1.0"
2993 world: "greentic:component/component@0.5.0"
2994 supports: ["messaging"]
2995 profiles:
2996 default: "stateless"
2997 supported: ["stateless"]
2998 capabilities:
2999 wasi: {}
3000 host: {}
3001 operations:
3002 - name: "handle_message"
3003 input_schema: {}
3004 output_schema: {}
3005 wasm: "components/dummy.wasm"
3006flows:
3007 - id: main
3008 file: flows/main.ygtc
3009 tags: [default]
3010 entrypoints: [main]
3011"#;
3012 fs::write(pack_dir.join("pack.yaml"), pack_yaml).expect("pack.yaml");
3013
3014 let runtime = crate::runtime::resolve_runtime(
3015 Some(pack_dir.as_path()),
3016 Some(cache_dir.as_path()),
3017 true,
3018 None,
3019 )
3020 .expect("runtime");
3021
3022 let opts = BuildOptions {
3023 pack_dir: pack_dir.clone(),
3024 component_out: None,
3025 manifest_out: pack_dir.join("dist/manifest.cbor"),
3026 sbom_out: None,
3027 gtpack_out: Some(pack_dir.join("dist/pack.gtpack")),
3028 lock_path: pack_dir.join("pack.lock.cbor"),
3029 bundle: BundleMode::Cache,
3030 dry_run: false,
3031 secrets_req: None,
3032 default_secret_scope: None,
3033 allow_oci_tags: false,
3034 require_component_manifests: false,
3035 no_extra_dirs: false,
3036 dev: false,
3037 runtime,
3038 skip_update: false,
3039 allow_pack_schema: true,
3040 validate_extension_refs: true,
3041 };
3042
3043 run(&opts).await.expect("build");
3044
3045 let gtpack_path = opts.gtpack_out.expect("gtpack path");
3046 let mut archive = ZipArchive::new(File::open(>pack_path).expect("open gtpack"))
3047 .expect("read gtpack");
3048 assert!(
3049 archive.by_name("components/dummy.component.wasm").is_ok(),
3050 "missing lock component artifact in gtpack"
3051 );
3052 });
3053 }
3054
3055 #[test]
3056 #[ignore = "requires network access to fetch OCI component"]
3057 fn build_fetches_and_embeds_lock_components_online() {
3058 if std::env::var("GREENTIC_PACK_ONLINE").is_err() {
3059 return;
3060 }
3061 let rt = tokio::runtime::Runtime::new().expect("runtime");
3062 rt.block_on(async {
3063 let temp = tempdir().expect("temp dir");
3064 let pack_dir = temp.path().join("pack");
3065 fs::create_dir_all(pack_dir.join("flows")).expect("flows dir");
3066 fs::create_dir_all(pack_dir.join("components")).expect("components dir");
3067
3068 let wasm_path = pack_dir.join("components/dummy.wasm");
3069 fs::write(&wasm_path, [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00])
3070 .expect("write wasm");
3071
3072 let flow_path = pack_dir.join("flows/main.ygtc");
3073 fs::write(
3074 &flow_path,
3075 r#"id: main
3076type: messaging
3077start: call
3078nodes:
3079 call:
3080 handle_message:
3081 text: "hi"
3082 routing: out
3083"#,
3084 )
3085 .expect("write flow");
3086
3087 let digest = "sha256:0904bee6ecd737506265e3f38f3e4fe6b185c20fd1b0e7c06ce03cdeedc00340";
3088 let summary = serde_json::json!({
3089 "schema_version": 1,
3090 "flow": "main.ygtc",
3091 "nodes": {
3092 "call": {
3093 "component_id": "dummy.component",
3094 "source": {
3095 "kind": "oci",
3096 "ref": format!("oci://ghcr.io/greenticai/components/templates@{digest}")
3097 },
3098 "digest": digest
3099 }
3100 }
3101 });
3102 fs::write(
3103 flow_path.with_extension("ygtc.resolve.summary.json"),
3104 serde_json::to_vec_pretty(&summary).expect("summary json"),
3105 )
3106 .expect("write summary");
3107
3108 let pack_yaml = r#"pack_id: demo.lock-online
3109version: 0.1.0
3110kind: application
3111publisher: Test
3112components:
3113 - id: dummy.component
3114 version: "0.1.0"
3115 world: "greentic:component/component@0.5.0"
3116 supports: ["messaging"]
3117 profiles:
3118 default: "stateless"
3119 supported: ["stateless"]
3120 capabilities:
3121 wasi: {}
3122 host: {}
3123 operations:
3124 - name: "handle_message"
3125 input_schema: {}
3126 output_schema: {}
3127 wasm: "components/dummy.wasm"
3128flows:
3129 - id: main
3130 file: flows/main.ygtc
3131 tags: [default]
3132 entrypoints: [main]
3133"#;
3134 fs::write(pack_dir.join("pack.yaml"), pack_yaml).expect("pack.yaml");
3135
3136 let cache_dir = temp.path().join("cache");
3137 let runtime = crate::runtime::resolve_runtime(
3138 Some(pack_dir.as_path()),
3139 Some(cache_dir.as_path()),
3140 false,
3141 None,
3142 )
3143 .expect("runtime");
3144
3145 let opts = BuildOptions {
3146 pack_dir: pack_dir.clone(),
3147 component_out: None,
3148 manifest_out: pack_dir.join("dist/manifest.cbor"),
3149 sbom_out: None,
3150 gtpack_out: Some(pack_dir.join("dist/pack.gtpack")),
3151 lock_path: pack_dir.join("pack.lock.cbor"),
3152 bundle: BundleMode::Cache,
3153 dry_run: false,
3154 secrets_req: None,
3155 default_secret_scope: None,
3156 allow_oci_tags: false,
3157 require_component_manifests: false,
3158 no_extra_dirs: false,
3159 dev: false,
3160 runtime,
3161 skip_update: false,
3162 allow_pack_schema: true,
3163 validate_extension_refs: true,
3164 };
3165
3166 run(&opts).await.expect("build");
3167
3168 let gtpack_path = opts.gtpack_out.expect("gtpack path");
3169 let mut archive = ZipArchive::new(File::open(>pack_path).expect("open gtpack"))
3170 .expect("read gtpack");
3171 assert!(
3172 archive.by_name("components/dummy.component.wasm").is_ok(),
3173 "missing lock component artifact in gtpack"
3174 );
3175 });
3176 }
3177
3178 #[test]
3179 fn aggregate_secret_requirements_dedupes_and_sorts() {
3180 let component: ComponentConfig = serde_json::from_value(json!({
3181 "id": "component.a",
3182 "version": "1.0.0",
3183 "world": "greentic:demo@1.0.0",
3184 "supports": [],
3185 "profiles": { "default": "default", "supported": ["default"] },
3186 "capabilities": {
3187 "wasi": {},
3188 "host": {
3189 "secrets": {
3190 "required": [
3191 {
3192 "key": "db/password",
3193 "required": true,
3194 "scope": { "env": "dev", "tenant": "t1" },
3195 "format": "text",
3196 "description": "primary"
3197 }
3198 ]
3199 }
3200 }
3201 },
3202 "wasm": "component.wasm",
3203 "operations": [],
3204 "resources": {}
3205 }))
3206 .expect("component config");
3207
3208 let dupe: ComponentConfig = serde_json::from_value(json!({
3209 "id": "component.b",
3210 "version": "1.0.0",
3211 "world": "greentic:demo@1.0.0",
3212 "supports": [],
3213 "profiles": { "default": "default", "supported": ["default"] },
3214 "capabilities": {
3215 "wasi": {},
3216 "host": {
3217 "secrets": {
3218 "required": [
3219 {
3220 "key": "db/password",
3221 "required": true,
3222 "scope": { "env": "dev", "tenant": "t1" },
3223 "format": "text",
3224 "description": "secondary",
3225 "examples": ["example"]
3226 }
3227 ]
3228 }
3229 }
3230 },
3231 "wasm": "component.wasm",
3232 "operations": [],
3233 "resources": {}
3234 }))
3235 .expect("component config");
3236
3237 let reqs = aggregate_secret_requirements(&[component, dupe], None, None)
3238 .expect("aggregate secrets");
3239 assert_eq!(reqs.len(), 1);
3240 let req = &reqs[0];
3241 assert_eq!(req.description.as_deref(), Some("primary"));
3242 assert!(req.examples.contains(&"example".to_string()));
3243 }
3244
3245 fn pack_config_with_bootstrap(bootstrap: BootstrapConfig) -> PackConfig {
3246 PackConfig {
3247 pack_id: "demo.pack".to_string(),
3248 version: "1.0.0".to_string(),
3249 kind: "application".to_string(),
3250 publisher: "demo".to_string(),
3251 name: None,
3252 bootstrap: Some(bootstrap),
3253 components: Vec::new(),
3254 dependencies: Vec::new(),
3255 flows: Vec::new(),
3256 assets: Vec::new(),
3257 extensions: None,
3258 }
3259 }
3260
3261 fn flow_entry(id: &str) -> PackFlowEntry {
3262 let flow: Flow = serde_json::from_value(json!({
3263 "schema_version": "flow/v1",
3264 "id": id,
3265 "kind": "messaging"
3266 }))
3267 .expect("flow json");
3268
3269 PackFlowEntry {
3270 id: FlowId::new(id).expect("flow id"),
3271 kind: FlowKind::Messaging,
3272 flow,
3273 tags: Vec::new(),
3274 entrypoints: Vec::new(),
3275 }
3276 }
3277
3278 fn minimal_component_manifest(id: &str) -> ComponentManifest {
3279 serde_json::from_value(json!({
3280 "id": id,
3281 "version": "1.0.0",
3282 "supports": [],
3283 "world": "greentic:demo@1.0.0",
3284 "profiles": { "default": "default", "supported": ["default"] },
3285 "capabilities": { "wasi": {}, "host": {} },
3286 "operations": [],
3287 "resources": {}
3288 }))
3289 .expect("component manifest")
3290 }
3291
3292 fn manifest_with_dev_flow() -> ComponentManifest {
3293 serde_json::from_str(include_str!(
3294 "../tests/fixtures/component_manifest_with_dev_flows.json"
3295 ))
3296 .expect("fixture manifest")
3297 }
3298
3299 fn pack_manifest_with_component(component: ComponentManifest) -> PackManifest {
3300 let flow = serde_json::from_value(json!({
3301 "schema_version": "flow/v1",
3302 "id": "flow.dev",
3303 "kind": "messaging"
3304 }))
3305 .expect("flow json");
3306
3307 PackManifest {
3308 schema_version: "pack-v1".to_string(),
3309 pack_id: PackId::new("demo.pack").expect("pack id"),
3310 name: None,
3311 version: Version::parse("1.0.0").expect("version"),
3312 kind: PackKind::Application,
3313 publisher: "demo".to_string(),
3314 components: vec![component],
3315 flows: vec![PackFlowEntry {
3316 id: FlowId::new("flow.dev").expect("flow id"),
3317 kind: FlowKind::Messaging,
3318 flow,
3319 tags: Vec::new(),
3320 entrypoints: Vec::new(),
3321 }],
3322 dependencies: Vec::new(),
3323 capabilities: Vec::new(),
3324 secret_requirements: Vec::new(),
3325 signatures: PackSignatures::default(),
3326 bootstrap: None,
3327 extensions: None,
3328 }
3329 }
3330
3331 #[tokio::test]
3332 async fn offline_build_requires_cached_remote_component() {
3333 let temp = tempdir().expect("temp dir");
3334 let cache_dir = temp.path().join("cache");
3335 fs::create_dir_all(&cache_dir).expect("create cache dir");
3336 let project_root = Path::new(env!("CARGO_MANIFEST_DIR"))
3337 .parent()
3338 .expect("workspace root");
3339 let runtime = resolve_runtime(Some(project_root), Some(cache_dir.as_path()), true, None)
3340 .expect("resolve runtime");
3341
3342 let mut components = BTreeMap::new();
3343 components.insert(
3344 "remote.component".to_string(),
3345 LockedComponent {
3346 component_id: "remote.component".to_string(),
3347 r#ref: Some("oci://example/remote@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".to_string()),
3348 abi_version: "0.6.0".to_string(),
3349 resolved_digest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
3350 .to_string(),
3351 describe_hash: sample_hex('a'),
3352 operations: Vec::new(),
3353 world: None,
3354 component_version: None,
3355 role: None,
3356 },
3357 );
3358 let lock = PackLockV1::new(components);
3359
3360 let err = match collect_lock_component_artifacts(&lock, &runtime, BundleMode::Cache, false)
3361 .await
3362 {
3363 Ok(_) => panic!("expected offline build to fail without cached component"),
3364 Err(err) => err,
3365 };
3366 let msg = err.to_string();
3367 assert!(
3368 msg.contains("requires network access"),
3369 "error message should describe missing network access, got {}",
3370 msg
3371 );
3372 }
3373}