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
use super::*;
use color_eyre::eyre::{self, OptionExt as _};
use helm_schema_core::ConditionalOverlayFlavor;
use test_util::prelude::sim_assert_eq;

#[test]
fn contract_builder_emits_typed_kind_branch_evidence() -> eyre::Result<()> {
    let source = indoc! {r#"
        apiVersion: apps/v1
        kind: {{ .Values.workload.kind }}
        metadata:
          name: test
        spec:
          {{- if eq .Values.workload.kind "Deployment" }}
          strategy: {{- toYaml .Values.workload.strategy | nindent 4 }}
          {{- else if eq .Values.workload.kind "StatefulSet" }}
          updateStrategy: {{- toYaml .Values.workload.strategy | nindent 4 }}
          {{- end }}
    "#};
    let signals = schema_signals_for(parse_ir(source));
    let evidence = signals
        .evidence_for("workload.strategy")
        .ok_or_eyre("workload strategy evidence missing")?;

    eyre::ensure!(!evidence.conditional_overlays.is_empty());
    for overlay in &evidence.conditional_overlays {
        sim_assert_eq!(have: overlay.flavor, want: ConditionalOverlayFlavor::KindBranch);
        eyre::ensure!(!overlay.evidence.provider_schema_uses.is_empty());
        for use_ in &overlay.evidence.provider_schema_uses {
            eyre::ensure!(use_.resource.kind_branches.is_empty());
            eyre::ensure!(use_.resource.kind_candidates.is_empty());
        }
    }
    Ok(())
}

#[test]
fn contract_builder_retains_literal_control_kind_branches() -> eyre::Result<()> {
    let source = indoc! {r#"
        {{- if eq .Values.local.kind "ConfigMap" }}
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: test
        immutable: {{ .Values.local.setting }}
        {{- else if eq .Values.local.kind "Service" }}
        apiVersion: v1
        kind: Service
        metadata:
          name: test
        spec:
          type: {{ .Values.local.setting }}
        {{- end }}
    "#};
    let signals = schema_signals_for(parse_ir(source));
    let evidence = signals
        .evidence_for("local.setting")
        .ok_or_eyre("local setting evidence missing")?;

    eyre::ensure!(
        evidence
            .conditional_overlays
            .iter()
            .all(|overlay| overlay.flavor == ConditionalOverlayFlavor::KindBranch),
        "literal kind branches were not retained: {evidence:#?}"
    );
    Ok(())
}

fn strict_provider() -> Chain {
    Chain::new(vec![Box::new(
        KubernetesJsonSchemaProvider::new("v1.29.0-standalone-strict")
            .with_cache_dir(super::bundle_cache_dir())
            .with_allow_download(false),
    )])
}

/// bitnami-redis master: a values-selected `kind:` crossed with a
/// helper-resolved apiVersion partitions the strategy slot per kind. The
/// Deployment arm places `spec.strategy` (no `rollingUpdate.partition`),
/// every other arm places `spec.updateStrategy` (no `maxSurge`), and the
/// provider projection must follow the selected partition instead of
/// blending the kinds.
#[test]
fn values_selected_kind_partitions_strategy_provider_projection() {
    let helpers = indoc! {r#"
        {{- define "common.capabilities.statefulset.apiVersion" -}}
        {{- print "apps/v1" -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: {{ include "common.capabilities.statefulset.apiVersion" . }}
        kind: {{ .Values.master.kind }}
        metadata:
          name: test
        spec:
          {{- if not (eq .Values.master.kind "DaemonSet") }}
          replicas: {{ .Values.master.count }}
          {{- end }}
          {{- if (eq .Values.master.kind "StatefulSet") }}
          serviceName: test-headless
          {{- end }}
          {{- if .Values.master.updateStrategy }}
          {{- if (eq .Values.master.kind "Deployment") }}
          strategy: {{- toYaml .Values.master.updateStrategy | nindent 4 }}
          {{- else }}
          updateStrategy: {{- toYaml .Values.master.updateStrategy | nindent 4 }}
          {{- end }}
          {{- end }}
    "#};
    let values_yaml = indoc! {"
        master:
          kind: StatefulSet
          count: 1
          updateStrategy:
            type: RollingUpdate
    "};
    let signals = schema_signals_for(parse_ir_with_helpers(src, helpers));
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&signals, &strict_provider())
            .with_values_documents(&prepared_values_documents(Some(values_yaml))),
    );

    for instance in [
        serde_json::json!({ "master": { "kind": "Deployment", "updateStrategy": { "rollingUpdate": { "maxSurge": "25%" } } } }),
        serde_json::json!({ "master": { "kind": "StatefulSet", "updateStrategy": { "rollingUpdate": { "partition": 1 } } } }),
        serde_json::json!({ "master": { "kind": "StatefulSet", "updateStrategy": { "type": "RollingUpdate" } } }),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance),
            "the strategy field set matching the selected kind renders and validates: \
             instance={instance}; schema={schema}"
        );
    }
    for instance in [
        serde_json::json!({ "master": { "kind": "Deployment", "updateStrategy": { "rollingUpdate": { "partition": 1 } } } }),
        serde_json::json!({ "master": { "kind": "StatefulSet", "updateStrategy": { "rollingUpdate": { "maxSurge": "25%" } } } }),
    ] {
        assert!(
            !schema_accepts_instance(&schema, &instance),
            "a strategy field from the OTHER kind's schema is rejected on this partition: \
             instance={instance}; schema={schema}"
        );
    }
}

/// airflow's scheduler: an INLINE LOCAL selects the workload kind
/// (`kind: {{ if $stateful }}StatefulSet{{ else }}Deployment{{ end }}`)
/// and the body's strategy slots are guarded by the same local. The kind
/// arms carry the selecting predicate, so rows entailed by one arm
/// concretize to that arm's kind and the provider projection follows the
/// partition: the Deployment arm owns `spec.strategy`, the `StatefulSet` arm
/// `spec.updateStrategy`, and each rejects the shape it cannot hold.
#[test]
fn inline_local_kind_partition_projects_per_arm_provider_schemas() {
    let src = indoc! {r#"
        {{- $stateful := and (contains "Local" .Values.executor) .Values.persistence.enabled }}
        apiVersion: apps/v1
        kind: {{ if $stateful }}StatefulSet{{ else }}Deployment{{ end }}
        metadata:
          name: test
        spec:
          replicas: {{ .Values.replicas }}
          {{- if and $stateful .Values.updateStrategy }}
          updateStrategy: {{- toYaml .Values.updateStrategy | nindent 4 }}
          {{- end }}
          {{- if and (not $stateful) .Values.strategy }}
          strategy: {{- toYaml .Values.strategy | nindent 4 }}
          {{- end }}
    "#};
    let values_yaml = indoc! {"
        executor: CeleryExecutor
        persistence:
          enabled: false
        replicas: 1
        updateStrategy: ~
        strategy: ~
    "};
    let signals = schema_signals_for(parse_ir(src));
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&signals, &strict_provider())
            .with_values_documents(&prepared_values_documents(Some(values_yaml))),
    );

    // Cases compose over the declared defaults: `contains "Local"
    // .Values.executor` reads the executor on every render and aborts on a
    // nil operand.
    for overrides in [
        serde_json::json!({ "strategy": { "rollingUpdate": { "maxSurge": "25%" } } }),
        serde_json::json!({ "strategy": { "type": "RollingUpdate" } }),
        serde_json::json!({
            "executor": "LocalExecutor",
            "persistence": { "enabled": true },
            "updateStrategy": { "rollingUpdate": { "partition": 1 } },
        }),
        // The strategy value from the OTHER kind's arm is harmless while
        // its own arm is dead: the template never renders it.
        serde_json::json!({
            "executor": "LocalExecutor",
            "persistence": { "enabled": true },
            "strategy": 7,
        }),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance),
            "the arm-matching strategy shape renders and validates: \
             instance={instance}; schema={schema}"
        );
    }
    for instance in [
        serde_json::json!({ "strategy": 7 }),
        serde_json::json!({ "strategy": { "rollingUpdate": { "partition": 1 } } }),
        serde_json::json!({
            "executor": "LocalExecutor",
            "persistence": { "enabled": true },
            "updateStrategy": { "rollingUpdate": { "maxSurge": "25%" } },
        }),
    ] {
        assert!(
            !schema_accepts_instance(&schema, &instance),
            "a strategy shape outside the LIVE arm's kind is rejected: \
             instance={instance}; schema={schema}"
        );
    }
}

/// Both arms of an inline-local kind chain write the SAME manifest slot
/// (`spec.updateStrategy`) from different values paths, and both kinds
/// hold that slot with different member sets (`StatefulSet` `partition`,
/// `DaemonSet` `maxSurge`). Pointer-miss fallback cannot pick the arm here
/// — only the row conjunction entailing the arm's selecting predicate
/// resolves each row to ITS kind's schema.
#[test]
fn shared_slot_kind_arms_resolve_through_selecting_predicates() {
    let src = indoc! {r#"
        {{- $stateful := and (contains "Local" .Values.executor) .Values.persistence.enabled }}
        apiVersion: apps/v1
        kind: {{ if $stateful }}StatefulSet{{ else }}DaemonSet{{ end }}
        metadata:
          name: test
        spec:
          {{- if and $stateful .Values.updateStrategy }}
          updateStrategy: {{- toYaml .Values.updateStrategy | nindent 4 }}
          {{- end }}
          {{- if and (not $stateful) .Values.daemonUpdateStrategy }}
          updateStrategy: {{- toYaml .Values.daemonUpdateStrategy | nindent 4 }}
          {{- end }}
    "#};
    let values_yaml = indoc! {"
        executor: CeleryExecutor
        persistence:
          enabled: false
        updateStrategy: ~
        daemonUpdateStrategy: ~
    "};
    let signals = schema_signals_for(parse_ir(src));
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&signals, &strict_provider())
            .with_values_documents(&prepared_values_documents(Some(values_yaml))),
    );

    // Cases compose over the declared defaults: `contains "Local"
    // .Values.executor` reads the executor on every render and aborts on a
    // nil operand.
    for overrides in [
        // The default executor keeps the DaemonSet arm live: its slot
        // accepts maxSurge, which the primary (first-literal) StatefulSet
        // schema would reject.
        serde_json::json!({ "daemonUpdateStrategy": { "rollingUpdate": { "maxSurge": 1 } } }),
        serde_json::json!({
            "executor": "LocalExecutor",
            "persistence": { "enabled": true },
            "updateStrategy": { "rollingUpdate": { "partition": 1 } },
        }),
    ] {
        let instance = composed_instance(values_yaml, overrides);
        assert!(
            schema_accepts_instance(&schema, &instance),
            "each arm's row resolves to its OWN kind's slot schema: \
             instance={instance}; schema={schema}"
        );
    }
    for instance in [
        serde_json::json!({ "daemonUpdateStrategy": { "rollingUpdate": { "partition": 1 } } }),
        serde_json::json!({
            "executor": "LocalExecutor",
            "persistence": { "enabled": true },
            "updateStrategy": { "rollingUpdate": { "maxSurge": 1 } },
        }),
    ] {
        assert!(
            !schema_accepts_instance(&schema, &instance),
            "a member from the OTHER kind's slot schema is rejected: \
             instance={instance}; schema={schema}"
        );
    }
}

/// nfs-subdir-external-provisioner: `maxUnavailable` flows through
/// `default 1` into a `PodDisruptionBudget`'s int-or-string slot, so the
/// declared integer default documents intent without narrowing away the
/// provider-accepted percentage string.
#[test]
fn pdb_int_or_string_survives_declared_integer_default() {
    let helpers = indoc! {r#"
        {{- define "pdb.apiVersion" -}}
        {{- if semverCompare ">=1.21-0" .Capabilities.KubeVersion.GitVersion -}}
        {{- print "policy/v1" -}}
        {{- else -}}
        {{- print "policy/v1beta1" -}}
        {{- end -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        {{- if .Values.podDisruptionBudget.enabled }}
        apiVersion: {{ template "pdb.apiVersion" . }}
        kind: PodDisruptionBudget
        metadata:
          name: test
        spec:
          maxUnavailable: {{ .Values.podDisruptionBudget.maxUnavailable | default 1 }}
        {{- end }}
    "#};
    let values_yaml = indoc! {"
        podDisruptionBudget:
          enabled: false
          maxUnavailable: 1
    "};
    let signals = schema_signals_for(parse_ir_with_helpers(src, helpers));
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&signals, &strict_provider())
            .with_values_documents(&prepared_values_documents(Some(values_yaml))),
    );

    for instance in [
        serde_json::json!({ "podDisruptionBudget": { "enabled": true, "maxUnavailable": "50%" } }),
        serde_json::json!({ "podDisruptionBudget": { "enabled": true, "maxUnavailable": 1 } }),
        serde_json::json!({ "podDisruptionBudget": { "enabled": true } }),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance),
            "the provider slot accepts int-or-string and the default covers absence: \
             instance={instance}; schema={schema}"
        );
    }
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "podDisruptionBudget": { "enabled": true, "maxUnavailable": { "a": 1 } }
            })
        ),
        "Go's plain formatting turns a safe mapping into a string accepted by IntOrString: {schema}"
    );
}

/// loki gateways: `hostUsers` renders ONLY where `kindIs "bool"` says so —
/// every other kind is silently omitted and the chart still renders — so
/// the declared default's string intent must not close the path against
/// maps: the self dispatch proves the complement never reaches the sink.
#[test]
fn self_kind_dispatch_keeps_complement_kinds_open() {
    let helpers = indoc! {r#"
        {{- define "test.kubeVersion" -}}
        {{- .Capabilities.KubeVersion.Version -}}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
        spec:
          {{- if and (semverCompare ">=1.33-0" (include "test.kubeVersion" .)) (kindIs "bool" .Values.hostUsers) }}
          hostUsers: {{ .Values.hostUsers }}
          {{- end }}
          containers:
            - name: main
    "#};
    let signals = schema_signals_for(parse_ir_with_helpers(src, helpers));
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&signals, &strict_provider())
            .with_values_documents(&prepared_values_documents(Some("hostUsers: nil\n"))),
    );
    assert!(
        schema
            .get("properties")
            .and_then(|properties| properties.get("hostUsers"))
            .is_some(),
        "the dispatched path stays a referenced property: {schema}"
    );
    for instance in [
        serde_json::json!({ "hostUsers": { "a": 1 } }),
        serde_json::json!({ "hostUsers": true }),
        serde_json::json!({ "hostUsers": "nil" }),
        serde_json::json!({ "hostUsers": 7 }),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance),
            "a kind outside the dispatch is omitted, not rejected: \
             instance={instance}; schema={schema}"
        );
    }
}

/// vault's affinity helper: `typeOf` dispatch selects `tpl` for strings
/// and `toYaml` for everything else, so structured affinity values are
/// chart-handled and must validate against the provider slot instead of
/// being rejected as non-strings.
#[test]
fn type_of_dispatch_keeps_serialized_arm_structured() {
    let helpers = indoc! {r#"
        {{- define "test.affinity" -}}
          {{- if .Values.affinity }}
      affinity:
        {{ $tp := typeOf .Values.affinity }}
        {{- if eq $tp "string" }}
          {{- tpl .Values.affinity . | nindent 8 | trim }}
        {{- else }}
          {{- toYaml .Values.affinity | nindent 8 }}
        {{- end }}
          {{- end }}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: apps/v1
        kind: Deployment
        metadata:
          name: test
        spec:
          template:
            spec:
              {{ template "test.affinity" . }}
              containers:
                - name: main
    "#};
    let signals = schema_signals_for(parse_ir_with_helpers(src, helpers));
    assert!(
        signals
            .evidence_for("affinity")
            .is_some_and(
                |evidence| evidence.conditional_overlays.iter().any(|overlay| {
                    overlay.guards.iter().any(|guard| {
                        matches!(
                            guard,
                            helm_schema_core::ConditionalGuard::Not(inner)
                                if matches!(
                                    inner.as_ref(),
                                    helm_schema_core::ConditionalGuard::TypeIs {
                                        path,
                                        schema_type,
                                    } if path == "affinity" && schema_type == "string"
                                )
                        )
                    }) && !overlay.evidence.facts.used_as_serialized
                })
            ),
        "the structure-preserving complement must keep provider evidence ahead of the scalar declared default"
    );
    let schema = generate_values_schema(
        ValuesSchemaInput::new(&signals, &strict_provider()).with_values_documents(
            &prepared_values_documents(Some(indoc! {"
                affinity: |
                  nodeAffinity: {}
            "})),
        ),
    );
    for (instance, want) in [
        (
            serde_json::json!({ "affinity": { "nodeAffinity": {
                "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [] }
            } } }),
            true,
        ),
        (serde_json::json!({ "affinity": "nodeAffinity: {}" }), true),
        (
            serde_json::json!({ "affinity": { "nodeAffinity": 7 } }),
            false,
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "the toYaml arm keeps provider typing for structured values: \
             instance={instance}; schema={schema}"
        );
    }
}