helm-schema 0.0.7

Generate an accurate JSON schema for any helm chart
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Component, Path};

use flate2::read::GzDecoder;
use serde::Deserialize;
use tracing::instrument;
use vfs::VfsPath;

use super::paths::scope_values_path;
use super::types::{ChartContext, ChartDependencyActivation};
use crate::error::{CliError, EngineResult};
use crate::load_budget::{LoadBudget, read_to_end_capped};

#[derive(Debug, Deserialize)]
struct ChartYaml {
    name: Option<String>,

    version: Option<String>,

    #[serde(rename = "apiVersion")]
    api_version: Option<String>,

    #[serde(rename = "appVersion")]
    app_version: Option<String>,

    description: Option<String>,

    home: Option<String>,

    icon: Option<String>,

    #[serde(rename = "type")]
    chart_type: Option<String>,

    annotations: Option<BTreeMap<String, String>>,

    dependencies: Option<Vec<ChartDependency>>,
}

#[derive(Debug, Deserialize)]
struct ChartDependency {
    name: String,
    alias: Option<String>,
    condition: Option<String>,
    tags: Option<Vec<String>>,
}

#[derive(Debug, Deserialize)]
struct RequirementsYaml {
    dependencies: Option<Vec<ChartDependency>>,
}

#[derive(Debug, Clone)]
struct DependencyMetadata {
    values_key: String,
    activation: ChartDependencyActivation,
}

#[instrument(skip_all)]
pub fn discover_chart_contexts(root_chart_dir: &VfsPath) -> EngineResult<Vec<ChartContext>> {
    discover_chart_contexts_with_budget(root_chart_dir, LoadBudget::default())
}

#[instrument(skip_all)]
pub(crate) fn discover_chart_contexts_with_budget(
    root_chart_dir: &VfsPath,
    load_budget: LoadBudget,
) -> EngineResult<Vec<ChartContext>> {
    let mut out = Vec::new();
    discover_chart_contexts_inner(root_chart_dir, &[], &[], load_budget, &mut out)?;
    Ok(out)
}

fn discover_chart_contexts_inner(
    chart_dir: &VfsPath,
    parent_prefix: &[String],
    dependency_activation_chain: &[ChartDependencyActivation],
    load_budget: LoadBudget,
    out: &mut Vec<ChartContext>,
) -> EngineResult<()> {
    let chart_yaml = read_chart_yaml(chart_dir)?;

    let is_library = chart_yaml
        .chart_type
        .as_deref()
        .is_some_and(|chart_type| chart_type.eq_ignore_ascii_case("library"));
    let static_root_strings = chart_static_root_strings(&chart_yaml);

    out.push(ChartContext {
        chart_dir: chart_dir.clone(),
        values_prefix: parent_prefix.to_vec(),
        is_library,
        static_root_strings,
        dependency_activation_chain: dependency_activation_chain.to_vec(),
    });

    let dependency_metadata_by_name = dependency_metadata_map(&chart_yaml, parent_prefix);

    let vendor_charts_dir = chart_dir.join("charts")?;
    if !vendor_charts_dir.is_dir()? {
        return Ok(());
    }

    // VFS backends do not promise read_dir ordering. Keep dependency traversal
    // stable because DefineIndex and helper graph construction use
    // last-write-wins semantics for duplicate helper definitions.
    let mut vendor_entries: Vec<VfsPath> = vendor_charts_dir.read_dir()?.collect();
    vendor_entries.sort_by_key(VfsPath::filename);

    let mut installed_charts = Vec::new();
    for entry in vendor_entries {
        let sub_dir = if entry.is_dir()? {
            let chart_yaml_path = entry.join("Chart.yaml")?;
            let chart_template_yaml_path = entry.join("Chart.template.yaml")?;
            if !chart_yaml_path.is_file()? && !chart_template_yaml_path.is_file()? {
                continue;
            }
            entry
        } else if entry.is_file()? {
            if !is_chart_archive(&entry.filename()) {
                continue;
            }

            extract_chart_archive(&entry, load_budget)?
        } else {
            continue;
        };

        let sub_chart_yaml = read_chart_yaml(&sub_dir)?;
        let sub_name = sub_chart_yaml
            .name
            .clone()
            .or_else(|| {
                let name = sub_dir.filename();
                if name.is_empty() { None } else { Some(name) }
            })
            .ok_or_else(|| CliError::SubchartNameMissing {
                path: sub_dir.as_str().to_string(),
            })?;

        installed_charts.push((sub_dir, sub_name));
    }

    reject_duplicate_installed_dependency_names(&installed_charts, &vendor_charts_dir)?;

    for (sub_dir, sub_name) in installed_charts {
        let dependency_metadata = dependency_metadata_by_name
            .get(&sub_name)
            .cloned()
            .unwrap_or_else(|| {
                vec![DependencyMetadata {
                    values_key: sub_name.clone(),
                    activation: ChartDependencyActivation::default(),
                }]
            });

        for dependency_metadata in dependency_metadata {
            let mut prefix = parent_prefix.to_vec();
            prefix.push(dependency_metadata.values_key);

            // Only condition/tag-carrying edges add an activation level; an
            // unconditional dependency keeps its parent's chain, so a child's
            // chain always extends its parent's as a prefix.
            let mut chain = dependency_activation_chain.to_vec();
            let activation = dependency_metadata.activation;
            if !activation.condition_paths.is_empty() || !activation.tag_paths.is_empty() {
                chain.push(activation);
            }

            discover_chart_contexts_inner(&sub_dir, &prefix, &chain, load_budget, out)?;
        }
    }

    Ok(())
}

fn chart_static_root_strings(chart: &ChartYaml) -> BTreeMap<Vec<String>, String> {
    let mut strings = BTreeMap::new();
    for (field, value) in [
        ("Name", chart.name.as_ref()),
        ("Version", chart.version.as_ref()),
        ("APIVersion", chart.api_version.as_ref()),
        ("AppVersion", chart.app_version.as_ref()),
        ("Description", chart.description.as_ref()),
        ("Home", chart.home.as_ref()),
        ("Icon", chart.icon.as_ref()),
        ("Type", chart.chart_type.as_ref()),
    ] {
        if let Some(value) = value {
            strings.insert(vec!["Chart".to_string(), field.to_string()], value.clone());
        }
    }
    for (key, value) in chart.annotations.as_ref().into_iter().flatten() {
        strings.insert(
            vec!["Chart".to_string(), "Annotations".to_string(), key.clone()],
            value.clone(),
        );
    }
    strings
}

pub(crate) fn is_chart_archive(file_name: &str) -> bool {
    let path = Path::new(file_name);
    let is_tgz = path
        .extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| extension.eq_ignore_ascii_case("tgz"));
    let is_tar_gz = path
        .extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| extension.eq_ignore_ascii_case("gz"))
        && path
            .file_stem()
            .and_then(|stem| Path::new(stem).extension())
            .and_then(|extension| extension.to_str())
            .is_some_and(|extension| extension.eq_ignore_ascii_case("tar"));

    is_tgz || is_tar_gz
}

pub(crate) fn extract_chart_archive(
    path: &VfsPath,
    load_budget: LoadBudget,
) -> EngineResult<VfsPath> {
    let mut file = path.open_file()?;
    let bytes = read_to_end_capped(
        &mut file,
        load_budget.max_chart_archive_bytes,
        path.as_str().to_string(),
    )?;

    let gz = GzDecoder::new(bytes.as_slice());
    let mut archive = tar::Archive::new(gz);

    let root = VfsPath::new(vfs::MemoryFS::new());
    let mut extracted_entries = 0usize;
    let mut extracted_bytes = 0usize;
    for entry in archive.entries()? {
        let mut entry = entry?;
        if !entry.header().entry_type().is_file() {
            continue;
        }
        extracted_entries = extracted_entries.saturating_add(1);
        if extracted_entries > load_budget.max_chart_archive_entries {
            return Err(CliError::LoadEntryBudgetExceeded {
                subject: path.as_str().to_string(),
                limit_entries: load_budget.max_chart_archive_entries,
            });
        }
        let entry_path = entry.path()?;
        validate_archive_entry_path(path.as_str(), &entry_path)?;
        let path_str = entry_path.to_string_lossy();
        let out = root.join(path_str.as_ref())?;
        out.parent().create_dir_all()?;
        let mut file = out.create_file()?;
        let copied = std::io::copy(&mut entry, &mut file)?;
        extracted_bytes =
            extracted_bytes.saturating_add(usize::try_from(copied).unwrap_or(usize::MAX));
        if extracted_bytes > load_budget.max_chart_archive_unpacked_bytes {
            return Err(CliError::LoadBudgetExceeded {
                subject: format!("expanded {}", path.as_str()),
                limit_bytes: load_budget.max_chart_archive_unpacked_bytes,
            });
        }
    }

    find_chart_dir(&root)?.ok_or_else(|| CliError::NoChartYamlInArchive {
        archive: path.as_str().to_string(),
    })
}

pub(crate) fn validate_archive_entry_path(archive: &str, entry_path: &Path) -> EngineResult<()> {
    // `components()` parses with the HOST's separator rules, but tar entry
    // names are platform-independent `/`-separated strings: an entry named
    // `..\evil` parses as a traversal on Windows and as one opaque filename
    // on Unix. Chart archives never legitimately contain backslashes (Helm
    // requires `/`-separated member names), so reject them outright — the
    // same entries then pass or fail identically on every platform.
    let is_safe = entry_path.components().all(|component| match component {
        Component::Normal(name) => !name.to_string_lossy().contains('\\'),
        Component::CurDir => true,
        _ => false,
    });
    if is_safe {
        return Ok(());
    }

    Err(CliError::UnsafeArchiveEntryPath {
        archive: archive.to_string(),
        entry_path: entry_path.display().to_string(),
    })
}

fn find_chart_dir(root: &VfsPath) -> EngineResult<Option<VfsPath>> {
    let direct = root.join("Chart.yaml")?;
    let direct_template = root.join("Chart.template.yaml")?;
    if direct.is_file()? || direct_template.is_file()? {
        return Ok(Some(root.clone()));
    }

    // Multi-chart archives are rare, but choosing alphabetically keeps the
    // fallback deterministic across filesystems.
    let mut entries: Vec<VfsPath> = root.read_dir()?.collect();
    entries.sort_by_key(VfsPath::filename);
    for entry in entries {
        if !entry.is_dir()? {
            continue;
        }
        let chart_yaml = entry.join("Chart.yaml")?;
        let chart_template_yaml = entry.join("Chart.template.yaml")?;
        if chart_yaml.is_file()? || chart_template_yaml.is_file()? {
            return Ok(Some(entry));
        }
    }

    Ok(None)
}

fn dependency_metadata_map(
    chart_yaml: &ChartYaml,
    parent_prefix: &[String],
) -> BTreeMap<String, Vec<DependencyMetadata>> {
    let mut out = BTreeMap::new();
    let deps = chart_yaml.dependencies.as_deref().unwrap_or_default();

    for dependency in deps {
        let values_key = dependency
            .alias
            .clone()
            .unwrap_or_else(|| dependency.name.clone());
        out.entry(dependency.name.clone())
            .or_insert_with(Vec::new)
            .push(DependencyMetadata {
                values_key,
                activation: dependency_activation(dependency, parent_prefix),
            });
    }

    out
}

fn dependency_activation(
    dependency: &ChartDependency,
    parent_prefix: &[String],
) -> ChartDependencyActivation {
    let condition_paths = dependency
        .condition
        .as_deref()
        .map(|condition| dependency_condition_paths(condition, parent_prefix))
        .unwrap_or_default();

    let tag_paths = dependency
        .tags
        .as_deref()
        .map(dependency_tag_paths)
        .unwrap_or_default();

    ChartDependencyActivation {
        condition_paths,
        tag_paths,
    }
}

fn dependency_condition_paths(condition: &str, parent_prefix: &[String]) -> Vec<String> {
    let mut seen = BTreeSet::new();
    let mut paths = Vec::new();
    for path in condition
        .split(',')
        .map(str::trim)
        .filter(|path| !path.is_empty())
        .map(|path| scope_chart_yaml_value_path(path, parent_prefix))
    {
        if seen.insert(path.clone()) {
            paths.push(path);
        }
    }
    paths
}

fn dependency_tag_paths(tags: &[String]) -> Vec<String> {
    tags.iter()
        .map(|tag| tag.trim())
        .filter(|tag| !tag.is_empty())
        .map(|tag| format!("tags.{tag}"))
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect()
}

fn scope_chart_yaml_value_path(path: &str, prefix: &[String]) -> String {
    let path = path.trim();
    if path == "tags" || path.starts_with("tags.") {
        return path.to_string();
    }
    scope_values_path(path, prefix)
}

fn read_chart_yaml(chart_dir: &VfsPath) -> EngineResult<ChartYaml> {
    let chart_yaml = chart_dir.join("Chart.yaml")?;
    let chart_template_yaml = chart_dir.join("Chart.template.yaml")?;

    let path = if chart_yaml.is_file()? {
        chart_yaml
    } else if chart_template_yaml.is_file()? {
        chart_template_yaml
    } else {
        chart_yaml
    };

    let mut metadata: ChartYaml = serde_yaml::from_str(&path.read_to_string()?)?;
    let mut dependency_source = path.as_str().to_string();
    if metadata.dependencies.is_none() {
        let requirements_yaml = chart_dir.join("requirements.yaml")?;
        if requirements_yaml.is_file()? {
            let requirements: RequirementsYaml =
                serde_yaml::from_str(&requirements_yaml.read_to_string()?)?;
            metadata.dependencies = requirements.dependencies;
            dependency_source = requirements_yaml.as_str().to_string();
        }
    }
    reject_duplicate_dependency_values_keys(
        metadata.dependencies.as_deref().unwrap_or_default(),
        dependency_source,
    )?;
    Ok(metadata)
}

fn reject_duplicate_dependency_values_keys(
    dependencies: &[ChartDependency],
    path: String,
) -> EngineResult<()> {
    let mut declarations_by_values_key = BTreeMap::new();
    for dependency in dependencies {
        let values_key = dependency.alias.as_deref().unwrap_or(&dependency.name);
        declarations_by_values_key
            .entry(values_key)
            .or_insert_with(Vec::new)
            .push(dependency.name.as_str());
    }
    let details = declarations_by_values_key
        .into_iter()
        .filter(|(_, names)| names.len() > 1)
        .map(|(values_key, names)| {
            let declarations = names
                .iter()
                .map(|name| format!("`{name}`"))
                .collect::<Vec<_>>()
                .join(", ");
            format!(
                "  `{values_key}`: {} declarations ({declarations})",
                names.len()
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    if details.is_empty() {
        return Ok(());
    }
    Err(CliError::DuplicateDependencyValuesKeys { path, details })
}

fn reject_duplicate_installed_dependency_names(
    installed_charts: &[(VfsPath, String)],
    charts_dir: &VfsPath,
) -> EngineResult<()> {
    let mut entries_by_name = BTreeMap::new();
    for (chart_dir, name) in installed_charts {
        entries_by_name
            .entry(name)
            .or_insert_with(Vec::new)
            .push(chart_dir.as_str());
    }
    let details = entries_by_name
        .into_iter()
        .filter(|(_, paths)| paths.len() > 1)
        .map(|(name, paths)| format!("  `{name}`: {}", paths.join(", ")))
        .collect::<Vec<_>>()
        .join("\n");
    if details.is_empty() {
        return Ok(());
    }
    Err(CliError::DuplicateInstalledDependencyNames {
        path: charts_dir.as_str().to_string(),
        details,
    })
}