helm-schema-cli 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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Regression coverage for output-only `$ref` handling. External refs can be
//! re-homed into local `$defs`, fully inlined for export, or preserved
//! literally when requested.
//!
//! Tests exercise the lower-level `flatten_with_retriever` API with an
//! in-memory `Retrieve` keyed by URI — no temp dirs, no real filesystem
//! activity. The same retrieval abstraction handles production
//! filesystem-backed calls.

use std::collections::HashMap;

use color_eyre::eyre::{self, WrapErr};
use helm_schema_cli::flatten;
use helm_schema_cli::schema_override;
use jsonschema::{Retrieve, Uri};
use serde_json::Value;
use test_util::prelude::sim_assert_eq;

const BASE_URI: &str = "file:///chart/";

/// Map-backed `Retrieve` used in tests. Pre-populates URIs to JSON
/// content so the dereferencer can resolve refs without touching disk.
struct InlineRetriever(HashMap<String, Value>);

impl InlineRetriever {
    fn new<I: IntoIterator<Item = (&'static str, Value)>>(entries: I) -> Self {
        let mut m = HashMap::new();
        for (uri, value) in entries {
            m.insert(uri.to_string(), value);
        }
        Self(m)
    }
}

impl Retrieve for InlineRetriever {
    fn retrieve(
        &self,
        uri: &Uri<String>,
    ) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
        self.0
            .get(uri.as_str())
            .cloned()
            .ok_or_else(|| format!("InlineRetriever: no entry for {uri}").into())
    }
}

/// Base schema a real generation would have produced for a minimal
/// chart. Kept inline so the test is self-contained against generation
/// behaviour drift.
fn base_schema() -> Value {
    serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "additionalProperties": false,
        "properties": {},
        "type": "object"
    })
}

fn cloud_schema() -> Value {
    serde_json::json!({ "enum": [null, "azure", "minikube"] })
}

fn cloud_override() -> Value {
    serde_json::json!({
        "properties": { "cloud": { "$ref": "../schemas/cloud.json" } }
    })
}

#[test]
fn external_refs_can_be_bundled_into_defs() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = schema_override::apply_schema_override(base_schema(), cloud_override());

    // Relative ref `../schemas/cloud.json` from base `file:///chart/`
    // resolves to `file:///schemas/cloud.json`.
    let retriever = InlineRetriever::new([("file:///schemas/cloud.json", cloud_schema())]);
    let actual = flatten::bundle_with_retriever(merged, BASE_URI, retriever).wrap_err("bundle")?;

    let expected = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$defs": {
            "schema1": { "enum": [null, "azure", "minikube"] }
        },
        "additionalProperties": false,
        "properties": {
            "cloud": { "$ref": "#/$defs/schema1" }
        },
        "type": "object"
    });

    sim_assert_eq!(have: actual, want: expected);
    Ok(())
}

#[test]
fn repeated_external_refs_share_one_definition() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "cloud": { "$ref": "../schemas/cloud.json" },
            "provider": { "$ref": "../schemas/cloud.json" }
        }
    });
    let retriever = InlineRetriever::new([("file:///schemas/cloud.json", cloud_schema())]);

    let actual = flatten::bundle_with_retriever(merged, BASE_URI, retriever).wrap_err("bundle")?;

    sim_assert_eq!(
        have: actual.pointer("/properties/cloud/$ref"),
        want: Some(&Value::String("#/$defs/schema1".to_string()))
    );
    sim_assert_eq!(
        have: actual.pointer("/properties/provider/$ref"),
        want: Some(&Value::String("#/$defs/schema1".to_string()))
    );
    sim_assert_eq!(have: actual.pointer("/$defs/schema1"), want: Some(&cloud_schema()));

    Ok(())
}

#[test]
fn bundled_definition_names_do_not_overwrite_existing_defs() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$defs": {
            "schema1": { "type": "number" }
        },
        "type": "object",
        "properties": {
            "cloud": { "$ref": "../schemas/cloud.json" }
        }
    });
    let retriever = InlineRetriever::new([("file:///schemas/cloud.json", cloud_schema())]);

    let actual = flatten::bundle_with_retriever(merged, BASE_URI, retriever).wrap_err("bundle")?;

    sim_assert_eq!(
        have: actual.pointer("/$defs/schema1"),
        want: Some(&serde_json::json!({ "type": "number" }))
    );
    sim_assert_eq!(have: actual.pointer("/$defs/schema2"), want: Some(&cloud_schema()));
    sim_assert_eq!(
        have: actual.pointer("/properties/cloud/$ref"),
        want: Some(&Value::String("#/$defs/schema2".to_string()))
    );

    Ok(())
}

#[test]
fn bundled_external_document_id_updates_relative_ref_base() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "external": { "$ref": "shared.json" }
        }
    });
    let shared = serde_json::json!({
        "$id": "schemas/shared.json",
        "type": "object",
        "properties": {
            "name": { "$ref": "defs.json#/$defs/name" }
        }
    });
    let definitions = serde_json::json!({
        "$defs": {
            "name": { "type": "string" }
        }
    });
    let retriever = InlineRetriever::new([
        ("file:///chart/shared.json", shared),
        ("file:///chart/schemas/defs.json", definitions),
    ]);

    let actual = flatten::bundle_with_retriever(merged, BASE_URI, retriever).wrap_err("bundle")?;

    sim_assert_eq!(
        have: actual.pointer("/properties/external/$ref"),
        want: Some(&Value::String("#/$defs/schema1".to_string()))
    );
    sim_assert_eq!(
        have: actual.pointer("/$defs/schema1/properties/name/$ref"),
        want: Some(&Value::String("#/$defs/schema2".to_string()))
    );
    sim_assert_eq!(
        have: actual.pointer("/$defs/schema2"),
        want: Some(&serde_json::json!({ "type": "string" }))
    );

    Ok(())
}

#[test]
fn root_document_id_does_not_turn_local_refs_into_external_fetches() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$id": "https://example.test/root.schema.json",
        "$defs": {
            "name": { "type": "string" }
        },
        "type": "object",
        "properties": {
            "name": { "$ref": "#/$defs/name" },
            "cloud": { "$ref": "../schemas/cloud.json" }
        }
    });
    let retriever =
        InlineRetriever::new([("https://example.test/schemas/cloud.json", cloud_schema())]);

    let actual = flatten::bundle_with_retriever(merged, BASE_URI, retriever).wrap_err("bundle")?;

    sim_assert_eq!(
        have: actual.pointer("/properties/name/$ref"),
        want: Some(&Value::String("#/$defs/name".to_string()))
    );
    sim_assert_eq!(
        have: actual.pointer("/properties/cloud/$ref"),
        want: Some(&Value::String("#/$defs/schema1".to_string()))
    );

    Ok(())
}

#[test]
fn bundling_does_not_rewrite_ref_keys_inside_enum_data() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "literal": {
                "enum": [
                    { "$ref": "this is data, not a schema reference" }
                ]
            },
            "cloud": { "$ref": "../schemas/cloud.json" }
        }
    });
    let retriever = InlineRetriever::new([("file:///schemas/cloud.json", cloud_schema())]);

    let actual = flatten::bundle_with_retriever(merged, BASE_URI, retriever).wrap_err("bundle")?;

    sim_assert_eq!(
        have: actual.pointer("/properties/literal/enum/0/$ref"),
        want: Some(&Value::String(
            "this is data, not a schema reference".to_string()
        ))
    );
    sim_assert_eq!(
        have: actual.pointer("/properties/cloud/$ref"),
        want: Some(&Value::String("#/$defs/schema1".to_string()))
    );

    Ok(())
}

#[test]
fn bundling_rejects_non_object_root_defs_before_writing_dangling_refs() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "$defs": false,
        "type": "object",
        "properties": {
            "cloud": { "$ref": "../schemas/cloud.json" }
        }
    });
    let retriever = InlineRetriever::new([("file:///schemas/cloud.json", cloud_schema())]);

    let err = flatten::bundle_with_retriever(merged, BASE_URI, retriever)
        .expect_err("non-object $defs should be rejected");

    assert!(
        err.to_string().contains("root $defs is not an object"),
        "unexpected error: {err}"
    );
    Ok(())
}

#[test]
fn external_refs_can_be_fully_inlined_for_export() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = schema_override::apply_schema_override(base_schema(), cloud_override());
    let retriever = InlineRetriever::new([("file:///schemas/cloud.json", cloud_schema())]);
    let actual =
        flatten::flatten_with_retriever(&merged, BASE_URI, retriever).wrap_err("flatten")?;

    let expected = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "additionalProperties": false,
        "properties": {
            "cloud": { "enum": [null, "azure", "minikube"] }
        },
        "type": "object"
    });

    sim_assert_eq!(have: actual, want: expected);
    Ok(())
}

/// `--keep-refs` preserves references through the output pipeline. Verify the
/// override-merged document keeps its literal `$ref` string.
#[test]
fn keep_refs_path_preserves_literal_ref_strings() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = schema_override::apply_schema_override(base_schema(), cloud_override());

    let expected = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "additionalProperties": false,
        "properties": {
            "cloud": { "$ref": "../schemas/cloud.json" }
        },
        "type": "object"
    });

    sim_assert_eq!(have: merged, want: expected);
    Ok(())
}

/// URL ref with a JSON Pointer fragment descends into the loaded
/// document instead of inlining the whole thing. This is the headline
/// behaviour the `referencing`-backed dereferencer gives us for free —
/// our old hand-rolled flatten would have inlined the whole document.
#[test]
fn url_with_fragment_descends_pointer() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let podspec_like = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "securityContext": {
                "type": "object",
                "properties": {
                    "runAsNonRoot": { "type": "boolean" }
                }
            },
            "tolerations": {
                "type": "array",
                "items": { "type": "object" }
            }
        }
    });

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "securityContext": {
                "$ref": "https://example.test/podspec.json#/properties/securityContext"
            }
        }
    });

    let retriever = InlineRetriever::new([("https://example.test/podspec.json", podspec_like)]);

    let actual =
        flatten::flatten_with_retriever(&merged, BASE_URI, retriever).wrap_err("flatten")?;

    let security_context = actual
        .pointer("/properties/securityContext")
        .expect("securityContext present");
    let expected_security_context = serde_json::json!({
        "type": "object",
        "properties": {
            "runAsNonRoot": { "type": "boolean" }
        }
    });
    sim_assert_eq!(have: security_context.clone(), want: expected_security_context);

    // The tolerations array from the fetched podspec must NOT have
    // leaked into our schema. If it does, the dereferencer is inlining
    // the whole document rather than descending the pointer.
    assert!(
        actual.pointer("/properties/tolerations").is_none(),
        "pointer descent failed — siblings of the targeted node leaked in: {actual}",
    );

    Ok(())
}

/// File ref with a JSON Pointer fragment: same as the URL case but
/// with a file URI. `referencing` handles both uniformly.
#[test]
fn file_with_fragment_descends_pointer() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let bundle = serde_json::json!({
        "$defs": {
            "Port": { "type": "integer", "format": "int32" },
            "Host": { "type": "string", "format": "hostname" }
        }
    });

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "port": { "$ref": "../schemas/net.json#/$defs/Port" }
        }
    });

    let retriever = InlineRetriever::new([("file:///schemas/net.json", bundle)]);

    let actual =
        flatten::flatten_with_retriever(&merged, BASE_URI, retriever).wrap_err("flatten")?;

    let port = actual.pointer("/properties/port").expect("port present");
    sim_assert_eq!(
        have: port.clone(),
        want: serde_json::json!({ "type": "integer", "format": "int32" })
    );

    Ok(())
}

/// Bare fragment refs (`#/$defs/...`) resolve against the current
/// document. helm-schema's own output doesn't emit these, but overrides
/// could, and the `referencing`-backed pass handles them out of the
/// box.
#[test]
fn bare_fragment_refs_resolve_within_document() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "primary": { "$ref": "#/$defs/Address" },
            "billing": { "$ref": "#/$defs/Address" }
        },
        "$defs": {
            "Address": {
                "type": "object",
                "properties": {
                    "street": { "type": "string" },
                    "city": { "type": "string" }
                }
            }
        }
    });

    let retriever = InlineRetriever::new([]);
    let actual =
        flatten::flatten_with_retriever(&merged, BASE_URI, retriever).wrap_err("flatten")?;

    let expected_address = serde_json::json!({
        "type": "object",
        "properties": {
            "street": { "type": "string" },
            "city": { "type": "string" }
        }
    });
    sim_assert_eq!(
        have: actual.pointer("/properties/primary").unwrap().clone(),
        want: expected_address
    );
    sim_assert_eq!(
        have: actual.pointer("/properties/billing").unwrap().clone(),
        want: expected_address
    );

    Ok(())
}

/// RFC 6901 escapes in JSON Pointer fragments (`~0` → `~`, `~1` → `/`)
/// resolve correctly. The `referencing` crate handles the escape rules
/// per the spec; we just verify the round-trip end-to-end.
#[test]
fn rfc6901_pointer_escapes_resolve() -> eyre::Result<()> {
    let _guard = test_util::builder().with_tracing(false).build()?;

    let merged = serde_json::json!({
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "media": { "$ref": "#/$defs/application~1json" }
        },
        "$defs": {
            "application/json": { "type": "string", "format": "media-range" }
        }
    });

    let retriever = InlineRetriever::new([]);
    let actual =
        flatten::flatten_with_retriever(&merged, BASE_URI, retriever).wrap_err("flatten")?;

    sim_assert_eq!(
        have: actual.pointer("/properties/media").unwrap().clone(),
        want: serde_json::json!({ "type": "string", "format": "media-range" })
    );
    Ok(())
}