helm-schema-gen 0.0.6

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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use test_util::prelude::sim_assert_eq;

use super::*;

/// Destructured map ranges should keep the chart input as a map, even when the
/// rendered output lands in a K8s array field like `env:`.
#[test]
fn destructured_range_map_input_does_not_become_output_array() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        spec:
          containers:
            - name: test
              image: busybox
              env:
                {{- range $key, $value := .Values.environment }}
                - name: {{ $key }}
                  value: {{ $value | quote }}
                {{- end }}
    "};
    let values_yaml = indoc! {"
        environment:
          INBUCKET_LOGLEVEL: debug
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    let environment = schema
        .pointer("/properties/environment")
        .expect("environment present");
    let map_arm = ranged_arm_of_type(environment, "object")
        .unwrap_or_else(|| panic!("environment object arm missing, got {environment}"));
    sim_assert_eq!(
        have: map_arm
            .pointer("/additionalProperties/type")
            .and_then(Value::as_str),
        want: Some("string"),
        "environment should generalize to an open string map when the chart ranges over its entries, got {environment}"
    );
    // Two-variable ranges cannot iterate integers ("can't use 2 to
    // iterate over more than one variable"), so the runtime widening
    // stays integer-free here.
    assert!(
        ranged_arm_of_type(environment, "integer").is_none(),
        "a destructured range must not admit integer counts, got {environment}"
    );
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "the complete fixture scenario is clearest as one contiguous test"
)]
fn destructured_range_with_len_guard_preserves_shape_erased_members() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        spec:
          containers:
            - name: test
              image: busybox
              {{- if (gt (len .Values.environment) 0) }}
              env:
                {{- range $key, $value := .Values.environment }}
                - name: {{ $key }}
                  value: {{ $value | quote }}
                {{- end }}
              {{- end }}
    "};
    let values_yaml = indoc! {"
        environment:
          INBUCKET_LOGLEVEL: debug
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    let mut properties = serde_json::Map::new();
    properties.insert(
        "environment".to_string(),
        serde_json::json!({
            "allOf": [{
                "if": {
                    "anyOf": [
                        { "type": "object" },
                        { "$ref": "#/$defs/t" },
                    ]
                },
                "then": {
                    "type": ["array", "null", "object"]
                }
            }]
        }),
    );
    // The coalesced document reads an absent (null-deleted) collection as
    // nil — Helm-falsy — so the range condition keys the collection's own
    // truthiness, with the mapping-coalesce widening beside it.
    let range_condition = serde_json::json!({
        "properties": {
            "environment": {
                "anyOf": [
                    { "type": "object" },
                    { "$ref": "#/$defs/t" },
                ]
            }
        },
        "required": ["environment"],
        "type": "object",
    });
    // The strict member implication already owns the iterable domain. The
    // remaining sibling preserves the fragment/default falsy arm without a
    // third, weaker range-only conditional that cannot narrow the result.
    let all_of = vec![
        serde_json::json!({
            "if": range_condition,
            "then": { "allOf": [
                // The KEY renders raw into the unquoted `name:` slot, so a key
                // holding `: `, ` #`, a line break, or a leading indicator
                // breaks the token Helm decodes.
                root_property_schema(
                    "environment",
                    serde_json::json!({
                        "anyOf": [
                            {
                                "propertyNames": {
                                    "allOf": plain_token_exclusions(true),
                                },
                                "type": "object",
                            },
                            { "type": "array" },
                            { "type": "null" },
                        ]
                    }),
                ),
                root_property_schema(
                    "environment",
                    serde_json::json!({ "type": ["array", "null", "object"] }),
                ),
            ] },
        }),
        // The range KEY renders at the string-only `name:` slot, so a
        // non-empty list's integer keys are excluded.
        root_property_schema(
            "environment",
            serde_json::json!({
                "anyOf": [
                    { "type": "object" },
                    { "maxItems": 0, "type": "array" },
                    { "type": "null" },
                ]
            }),
        ),
        root_property_schema(
            "environment",
            serde_json::json!({ "not": { "type": "boolean" } }),
        ),
        root_property_schema(
            "environment",
            serde_json::json!({ "not": { "type": "integer" } }),
        ),
        root_property_schema(
            "environment",
            serde_json::json!({ "not": { "type": "number" } }),
        ),
        // `len` answers "len of nil pointer" for a null-deleted collection,
        // so the guard itself demands the key before the range can be
        // dormant.
        navigated_host_clause(&["environment"]),
    ];
    sim_assert_eq!(
        have: &schema,
        want: &expected_values_schema(properties, all_of, true)
    );

    // The len guard is exact, but `quote` shape-erases each ranged value;
    // the live collection contract must not reintroduce string-only values.
    for environment in [
        serde_json::json!({ "LOG_LEVEL": "debug" }),
        serde_json::json!({ "RETRIES": 7 }),
    ] {
        assert!(
            schema_accepts_instance(&schema, &serde_json::json!({ "environment": environment })),
            "quoted range values accept every input shape: {schema}"
        );
    }
}

/// Element- and list-preserving collection transforms keep item provenance,
/// so a total stringification widens source items without erasing a separate
/// strict item consumer.
#[test]
fn collection_selection_projects_item_conversion_to_source_items() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          containers:
            - name: test
              image: busybox
              env:
                {{- range initial .Values.teams }}
                - name: TEAM
                  value: {{ . | quote }}
                {{- end }}
                - name: LAST_TEAM
                  value: {{ .Values.teams | last | quote }}
                {{- if .Values.strict }}
                {{- range .Values.teams }}
                - name: STRICT_TEAM
                  value: {{ . | b64enc | quote }}
                {{- end }}
                {{- end }}
    "};
    let values_yaml = indoc! {"
        teams:
          - first
          - last
        strict: false
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for teams in [
        serde_json::json!([]),
        serde_json::json!([7, 8]),
        serde_json::json!([{ "name": "first" }, { "name": "last" }]),
    ] {
        let instance = serde_json::json!({ "teams": teams, "strict": false });
        assert!(
            schema_accepts_instance(&schema, &instance),
            "initial/range and last/quote observe formatted item text: \
             instance={instance}; schema={schema}"
        );
    }
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({ "teams": [7], "strict": true })
        ),
        "a live independent b64enc consumer still requires string items: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({ "teams": ["secret"], "strict": true })
        ),
        "string items satisfy the independent strict consumer: {schema}"
    );
}

/// A scalar-item range that directly renders the sequence items should keep the
/// provider array metadata on the destination field, not collapse to a bare
/// `items.type` array inferred only from the item uses.
#[test]
fn scalar_item_range_keeps_provider_array_metadata() {
    let src = indoc! {r"
        apiVersion: v1
        kind: PersistentVolumeClaim
        metadata:
          name: test
        spec:
          accessModes:
          {{- range .Values.accessModes }}
            - {{ . | quote }}
          {{- end }}
    "};
    let values_yaml = indoc! {"
        accessModes:
          - ReadWriteOnce
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    let access_modes = schema
        .pointer("/properties/accessModes")
        .expect("accessModes present");
    let array_arm = schema_variant_matching(access_modes, |variant| {
        variant.get("type").and_then(Value::as_str) == Some("array")
            && variant.get("description").is_some()
    })
    .unwrap_or_else(|| panic!("provider array arm missing, got {access_modes}"));
    sim_assert_eq!(
        have: array_arm.get("items"),
        want: Some(&serde_json::json!({})),
        "quoted items render any input through strval, so the provider string typing must not flow back, got {access_modes}"
    );
    assert!(
        array_arm
            .pointer("/description")
            .and_then(Value::as_str)
            .is_some(),
        "accessModes should keep the provider description, got {access_modes}"
    );
    sim_assert_eq!(
        have: array_arm
            .pointer("/x-kubernetes-list-type")
            .and_then(Value::as_str),
        want: Some("atomic"),
        "accessModes should keep the provider list metadata, got {access_modes}"
    );
}

/// An input list wrapped into object-valued output items keeps the preimage of
/// the rendered scalar field rather than inheriting its resource object.
#[test]
fn scalar_range_wrapped_into_object_items_keeps_scalar_preimage() {
    let src = indoc! {r"
        apiVersion: networking.k8s.io/v1
        kind: Ingress
        metadata:
          name: test
        spec:
          rules:
          {{- range .Values.hosts }}
            - host: {{ .host | quote }}
              http:
                paths:
                {{- range .paths }}
                  - path: {{ . }}
                    pathType: Prefix
                    backend:
                      service:
                        name: app
                        port:
                          number: 80
                {{- end }}
          {{- end }}
    "};
    let values_yaml = indoc! {"
        hosts:
          - host: example.test
            paths:
              - /
    "};
    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    let hosts = schema.pointer("/properties/hosts").expect("hosts present");
    let hosts_arm = ranged_arm_of_type(hosts, "array")
        .unwrap_or_else(|| panic!("hosts array arm missing, got {hosts}"));
    let host_paths = hosts_arm
        .pointer("/items/properties/paths")
        .expect("hosts[].paths present");
    let paths_arm = ranged_arm_of_type(host_paths, "array")
        .unwrap_or_else(|| panic!("hosts[].paths array arm missing, got {host_paths}"));
    let path_items = paths_arm.get("items").expect("hosts[].paths items");
    assert!(
        schema_contains_type(path_items, "string"),
        "hosts[].paths items should retain the provider string branch, got {host_paths}"
    );
    assert!(
        schema_accepts_instance(path_items, &serde_json::json!({ "segment": "value" })),
        "a YAML-safe Go-formatted mapping still renders as a scalar, got {host_paths}"
    );
    assert!(
        !schema_accepts_instance(path_items, &serde_json::json!(["/nested"])),
        "a Go-formatted sequence renders as a flow sequence, got {host_paths}"
    );
}

#[test]
fn scalar_range_with_root_helper_stays_scalar_array() {
    let src = indoc! {r#"
        apiVersion: networking.k8s.io/v1
        kind: Ingress
        metadata:
          name: test
        spec:
          rules:
          {{- range .Values.hosts }}
            {{- $url := splitList "/" . }}
            - host: {{ first $url }}
              http:
                paths:
                  - path: /{{ rest $url | join "/" }}
                    pathType: Prefix
                    backend:
                      service:
                        name: {{ include "fullname" $ }}
                        port:
                          number: 80
          {{- end }}
    "#};
    let helpers = indoc! {r#"
        {{- define "fullname" -}}
        {{- .Chart.Name -}}
        {{- end -}}
    "#};
    let values_yaml = indoc! {"
        hosts:
          - /
    "};
    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    let hosts = schema.pointer("/properties/hosts").expect("hosts present");
    let array_arm = ranged_arm_of_type(hosts, "array")
        .unwrap_or_else(|| panic!("hosts array arm missing, got {hosts}"));
    sim_assert_eq!(
        have: array_arm.pointer("/items/type").and_then(Value::as_str),
        want: Some("string"),
        "hosts items should stay strings, got {hosts}"
    );
    assert!(
        array_arm.pointer("/items/properties/Chart").is_none(),
        "root helper fields must not be projected onto range items, got {hosts}"
    );
}

#[test]
fn map_entry_range_over_values_path_keeps_object_map_schema() {
    let src = indoc! {r"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        data:
        {{- range $key, $value := .Values.controller.config }}
          {{- $key | nindent 2 }}: {{ tpl (toString $value) $ | quote }}
        {{- end }}
    "};
    let values_yaml = indoc! {"
        controller:
          config: {}
    "};
    let contract = parse_ir(src);
    let signals = schema_signals_for(&contract);
    let facts = signals
        .evidence_for("controller.config")
        .map(|evidence| evidence.facts)
        .expect("controller.config fact present");
    assert!(
        facts.is_ranged_source,
        "range header should mark controller.config as a ranged source, facts={facts:#?}"
    );
    assert!(
        facts.used_as_fragment,
        "map-entry range should mark controller.config as a rendered fragment, facts={facts:#?}"
    );

    let schema = schema_for_values_yaml(&contract, Some(values_yaml));
    let config = schema
        .pointer("/properties/controller/properties/config")
        .expect("controller.config schema present");
    assert!(
        schema_contains_type(config, "object"),
        "controller.config should retain an object-valued branch, got {config}"
    );
    assert!(
        !schema_contains_type(config, "string"),
        "controller.config should not collapse to a scalar string branch, got {config}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({"controller": {"config": {"allow-snippet-annotations": "true"}}}),
        ),
        "controller.config should accept arbitrary ConfigMap data keys: {schema:#}"
    );
    assert!(
        !schema_accepts_instance(
            &schema,
            &serde_json::json!({"controller": {"config": "allow-snippet-annotations=true"}}),
        ),
        "controller.config should not collapse to a scalar string: {schema:#}"
    );
}

#[test]
fn wildcard_source_path_types_both_collection_lanes_without_empty_variant() {
    let uses = vec![ContractUse {
        source_expr: "image.pullSecrets.*".to_string(),
        path: helm_schema_ir::YamlPath(vec![
            "spec".to_string(),
            "imagePullSecrets[*]".to_string(),
            "name".to_string(),
        ]),
        kind: ValueKind::Scalar,
        condition: helm_schema_core::GuardDnf::from_guards(Vec::new()),
        resource: Some(ResourceRef::concrete("v1".to_string(), "Pod".to_string())),
        provenance: Vec::new(),
        stringified: false,
        template_supplied_member_keys: std::collections::BTreeSet::default(),
        split_segment: None,
        merge_layers: None,
        range_key: false,
        nil_omitting: false,
        omitted_members: std::collections::BTreeMap::default(),
        digest: false,
        merge_operand: false,
    }];
    let values_yaml = indoc! {"
        image:
          pullSecrets: []
    "};

    let schema = schema_for_values_yaml(&uses, Some(values_yaml));
    let pull_secrets = schema
        .pointer("/properties/image/properties/pullSecrets")
        .expect("image.pullSecrets present");

    // A bare `*` member row proves members exist, not which collection lane
    // hosts them (`range` iterates arrays and maps alike), so both lanes
    // carry the rendered name's scalar typing and no untyped artifact arm
    // survives.
    let array_items = pull_secrets
        .pointer("/anyOf/0/items")
        .expect("array items carry the rendered scalar preimage");
    let map_values = pull_secrets
        .pointer("/anyOf/1/additionalProperties")
        .expect("map values carry the rendered scalar preimage");
    sim_assert_eq!(have: array_items, want: map_values);
    for value in [
        serde_json::json!("secret"),
        serde_json::json!("secret # comment"),
    ] {
        assert!(
            schema_accepts_instance(array_items, &value),
            "both safe scalar spellings satisfy the rendered name preimage: {array_items}"
        );
    }
    for value in [
        serde_json::json!(7),
        serde_json::json!(true),
        serde_json::json!([]),
    ] {
        assert!(
            !schema_accepts_instance(array_items, &value),
            "the rendered name preimage rejects non-string node kinds: {array_items}"
        );
    }
    assert!(
        schema_accepts_instance(array_items, &serde_json::json!({})),
        "an empty mapping is Go-formatted into a YAML string: {array_items}"
    );
    let arms = pull_secrets
        .get("anyOf")
        .and_then(Value::as_array)
        .expect("two-lane union");
    sim_assert_eq!(have: arms.len(), want: 2);
    assert!(
        arms.iter()
            .all(|arm| !crate::schema_model::is_empty_schema(arm)),
        "no empty artifact arm may survive: {pull_secrets}"
    );
}