helm-schema-gen 0.0.4

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
use test_util::prelude::sim_assert_eq;

use super::*;

#[test]
fn guard_only_scalar_path_keeps_values_yaml_scalar_type() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Secret
        metadata:
          name: example
        {{- if .Values.existingSecret }}
        stringData:
          password: ignored
        {{- end }}
    "};
    let values_yaml = indoc! {"
        existingSecret: \"\"
    "};

    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));
    let existing_secret = schema
        .pointer("/properties/existingSecret")
        .expect("existingSecret present");

    assert!(
        !permits_null(existing_secret),
        "plain guard-only scalar values should not be widened without a null-tolerant render use, got {existing_secret}"
    );
    assert!(
        schema_contains_type(existing_secret, "string"),
        "values.yaml string evidence should still be preserved, got {existing_secret}"
    );
}

#[test]
fn helper_yaml_rendered_inside_block_scalar_does_not_project_payload_shape() {
    let helpers = indoc! {r#"
        {{- define "collector.config" -}}
        receivers:
          k8s_cluster:
            collection_interval: {{ .Values.presets.clusterMetrics.collectionInterval }}
            allocatable_types_to_report:
              {{- toYaml .Values.presets.clusterMetrics.allocatableTypesToReport | nindent 10 }}
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: collector
        data:
          collector.yaml: |-
            {{- include "collector.config" . | nindent 4 }}
    "#};
    let values_yaml = indoc! {"
        presets:
          clusterMetrics:
            collectionInterval: 30s
            allocatableTypesToReport:
              - cpu
              - memory
    "};

    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    let expected = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "additionalProperties": false,
        // The navigated hosts' presence claims; the object typing itself
        // folded into the base below.
        "allOf": [
            navigated_host_clause(&["presets"]),
            navigated_host_clause(&["presets", "clusterMetrics"]),
        ],
        "properties": {
            "presets": {
                "type": "object",
                "additionalProperties": {},
                "properties": {
                    "clusterMetrics": {
                        "type": "object",
                        "additionalProperties": {},
                        "properties": {
                            "allocatableTypesToReport": {
                                "anyOf": [
                                    {
                                        "type": "array",
                                        "items": {
                                            "type": "string"
                                        }
                                    },
                                    {
                                        "type": "null"
                                    }
                                ]
                            },
                            "collectionInterval": {
                                "type": "string"
                            }
                        }
                    }
                }
            }
        }
    });
    sim_assert_eq!(have: schema, want: expected);
}

#[test]
fn helper_local_yaml_merge_inside_block_scalar_does_not_project_payload_shape() {
    let helpers = indoc! {r#"
        {{- define "collector.config" -}}
        {{- $config := include "collector.baseConfig" . | fromYaml }}
        {{- if .Values.presets.clusterMetrics.enabled }}
        {{- $config = (include "collector.applyClusterMetricsConfig" (dict "Values" . "config" $config) | fromYaml) }}
        {{- end }}
        {{- tpl (toYaml $config) . }}
        {{- end -}}

        {{- define "collector.baseConfig" -}}
        service:
          pipelines:
            metrics:
              receivers: []
              exporters: []
        {{- end -}}

        {{- define "collector.applyClusterMetricsConfig" -}}
        {{- $config := mustMergeOverwrite (include "collector.clusterMetricsConfig" .Values | fromYaml) .config }}
        {{- $config | toYaml }}
        {{- end -}}

        {{- define "collector.clusterMetricsConfig" -}}
        receivers:
          k8s_cluster:
            collection_interval: {{ .Values.presets.clusterMetrics.collectionInterval }}
            allocatable_types_to_report:
              {{- toYaml .Values.presets.clusterMetrics.allocatableTypesToReport | nindent 10 }}
        service:
          pipelines:
            metrics:
              receivers:
                - k8s_cluster
        {{- end -}}
    "#};
    let src = indoc! {r#"
        apiVersion: v1
        kind: ConfigMap
        metadata:
          name: collector
        data:
          collector.yaml: |-
            {{- include "collector.config" . | nindent 4 }}
    "#};
    let values_yaml = indoc! {"
        presets:
          clusterMetrics:
            enabled: true
            collectionInterval: 30s
            allocatableTypesToReport:
              - cpu
              - memory
    "};

    let schema = schema_for_values_yaml(parse_ir_with_helpers(src, helpers), Some(values_yaml));

    let expected = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "additionalProperties": false,
        "allOf": [
            navigated_host_clause(&["presets"]),
            navigated_host_clause(&["presets", "clusterMetrics"]),
        ],
        "properties": {
            "presets": {
                "type": "object",
                "additionalProperties": {},
                "properties": {
                    "clusterMetrics": {
                        "type": "object",
                        "additionalProperties": {},
                        "properties": {
                            "allocatableTypesToReport": {
                                "type": "array",
                                "items": {
                                    "type": "string"
                                }
                            },
                            "collectionInterval": {
                                "type": "string"
                            },
                            "enabled": {
                                "type": "boolean"
                            }
                        }
                    }
                }
            }
        }
    });
    sim_assert_eq!(have: schema, want: expected);
}

#[test]
fn local_default_alias_render_applies_provider_schema_to_fallback_path() {
    let src = indoc! {r#"
        apiVersion: example.com/v1
        kind: Widget
        spec:
          {{- $storageClass := default .Values.persistence.storageClass .Values.global.storageClass -}}
          {{- if $storageClass }}
          {{- if (eq "-" $storageClass) }}
          storageClassName: ""
          {{- else }}
          storageClassName: {{ $storageClass }}
          {{- end }}
          {{- end }}
    "#};
    let values_yaml = indoc! {"
        global:
          storageClass:
        persistence:
          storageClass:
    "};

    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    for (instance, want, label) in [
        (
            serde_json::json!({
                "global": { "storageClass": null },
                "persistence": { "storageClass": "fast" }
            }),
            true,
            "string fallback",
        ),
        (
            serde_json::json!({
                "global": { "storageClass": null },
                "persistence": { "storageClass": 7 }
            }),
            false,
            "invalid selected fallback",
        ),
        (
            serde_json::json!({
                "global": { "storageClass": "fast" },
                "persistence": { "storageClass": 7 }
            }),
            true,
            "shadowed invalid fallback",
        ),
        (
            serde_json::json!({
                "global": { "storageClass": 7 },
                "persistence": { "storageClass": "fast" }
            }),
            false,
            "invalid selected primary",
        ),
        (
            serde_json::json!({
                "global": { "storageClass": "-" },
                "persistence": { "storageClass": null }
            }),
            true,
            "special unset marker",
        ),
        (
            serde_json::json!({
                "global": { "storageClass": null },
                "persistence": { "storageClass": null }
            }),
            true,
            "empty effective value",
        ),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance) == want,
            "{label}: instance={instance}; schema={schema}"
        );
    }
}

#[test]
fn unconstrained_object_fragment_keeps_nested_maps_open() {
    let src = indoc! {r"
        apiVersion: example.com/v1
        kind: Widget
        spec:
          resources: {{ toYaml .Values.resources | nindent 4 }}
    "};
    let values_yaml = indoc! {"
        resources:
          requests:
            cpu: 100m
            memory: 200Mi
    "};

    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    // Undeclared members of a spliced fragment are passthrough: typing them
    // as the merge of declared property schemas rejected legitimate keys
    // whose shape differs from the declared ones (`requests: {cpu: "1",
    // "nvidia.com/gpu": 2}` renders fine).
    let expected = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "additionalProperties": false,
        "properties": {
            "resources": {
                "type": "object",
                "additionalProperties": {},
                "properties": {
                    "requests": {
                        "type": "object",
                        "additionalProperties": {},
                        "properties": {
                            "cpu": {
                                "type": "string"
                            },
                            "memory": {
                                "type": "string"
                            }
                        }
                    }
                }
            }
        }
    });
    sim_assert_eq!(have: schema, want: expected);
}

/// A destructured `range $k, $v := .` inside an outer `with .Values.X` should
/// still attribute the rendered map field back to `X`, so provider schemas can
/// type it as an open string map.
#[test]
fn with_bound_range_dot_annotations_stay_string_map() {
    let src = indoc! {r"
        apiVersion: v1
        kind: Pod
        metadata:
          name: test
          {{- with .Values.annotations }}
          annotations:
            {{- range $key, $value := . }}
            {{ $key }}: {{ $value | quote }}
            {{- end }}
          {{- end }}
    "};
    let values_yaml = indoc! {"
        annotations:
          foo: bar
    "};
    let ir = parse_ir(src);
    let schema = schema_for_values_yaml(&ir, Some(values_yaml));

    let annotations = schema
        .pointer("/properties/annotations")
        .expect("annotations present");
    let map_arm = ranged_arm_of_type(annotations, "object")
        .unwrap_or_else(|| panic!("annotations object arm missing, got {annotations}"));
    sim_assert_eq!(
        have: map_arm
            .pointer("/additionalProperties/type")
            .and_then(Value::as_str),
        want: Some("string"),
        "annotations should stay an open string map, got {annotations}"
    );
}

#[test]
fn with_defaulted_object_body_rebinds_dot_to_fallback_path() {
    let src = indoc! {r#"
        {{- range $db, $cfg := .Values.jobs }}
        apiVersion: v1
        kind: Pod
        spec:
          containers:
            - name: runner
              {{- with (.image | default $.Values.globalImage) }}
              image: "{{ .repository }}:{{ .tag }}"
              {{- end }}
        {{- end }}
    "#};
    let values_yaml = indoc! {"
        globalImage:
          repository: repo/app
        jobs:
          first: {}
    "};

    let schema = schema_for_values_yaml(parse_ir(src), Some(values_yaml));

    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "globalImage": {
                    "repository": "repo/app",
                    "tag": 1.25
                },
                "jobs": { "first": {} }
            })
        ),
        "the fallback image accepts scalar tag interpolation: {schema}"
    );
    assert!(
        schema_accepts_instance(
            &schema,
            &serde_json::json!({
                "globalImage": {
                    "repository": "repo/app",
                    "tag": { "bad": true }
                },
                "jobs": { "first": {} }
            })
        ),
        "the range-member-dependent fallback cannot be lowered safely, so its tag contract must abstain: {schema}"
    );
}

#[test]
fn ranged_with_defaulted_object_body_abstains_on_cross_range_fallback() {
    let src = indoc! {r#"
        {{- $tag := .Values.image.tag | default .Chart.AppVersion -}}
        {{- range $db, $cfg := .Values.migrations.databases }}
        apiVersion: batch/v1
        kind: Job
        spec:
          template:
            spec:
              containers:
                - name: runner
                  {{- with (.image | default $.Values.migrations.image) }}
                  image: "{{ .repository }}:{{ .tag | default $tag }}"
                  imagePullPolicy: {{ .pullPolicy | default "Always" }}
                  {{- end }}
        {{- end }}
    "#};
    let values_yaml = indoc! {"
        image:
          tag: app-version
        migrations:
          image:
            repository: repo/app
            pullPolicy: Always
          databases:
            first: {}
    "};

    let ir = parse_ir(src);
    let schema = schema_for_values_yaml(&ir, Some(values_yaml));

    // The `with` subject chooses between a ranged member and a root
    // fallback. Draft 7 cannot express that cross-collection relation, and
    // the quoted partial scalar stringifies every selected tag shape. Keep
    // the fallback open instead of attributing the member arm's shape to it.
    for instance in [
        serde_json::json!({
            "image": { "tag": "app-version" },
            "migrations": {
                "databases": { "first": {} },
                "image": {
                    "repository": "repo/app",
                    "pullPolicy": "Always",
                    "tag": 7
                }
            }
        }),
        serde_json::json!({
            "image": { "tag": "app-version" },
            "migrations": {
                "databases": { "first": { "image": {
                    "repository": "member/app",
                    "tag": "member",
                    "pullPolicy": "Always"
                } } },
                "image": { "tag": 7 }
            }
        }),
    ] {
        assert!(
            schema_accepts_instance(&schema, &instance),
            "an unlowerable member/fallback choice must abstain: instance={instance}; schema={schema}; ir={ir:?}"
        );
    }
}