lightshuttle-export 0.5.0

Manifest to deployment artifact transpilation for LightShuttle
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
//! Tests for the Helm emitter.

use lightshuttle_export::{Emitter, ExportArtifacts, HelmEmitter, KubernetesEmitter, lower};
use lightshuttle_manifest::Manifest;

mod common;

const STACK: &str = r"
project:
  name: shop
  version: 1.4.0
export:
  helm:
    chart_name: shop-chart
resources:
  db:
    postgres:
      version: '16'
      password: devsecret
      volume: dbdata
  cache:
    redis:
      version: '7'
  api:
    container:
      image: alpine:3.20
      ports:
        - 8080:80
      env:
        LOG_LEVEL: info
        API_TOKEN: t0ken
      depends_on: [db]
";

fn artifacts(yaml: &str) -> ExportArtifacts {
    let manifest = Manifest::parse(yaml).expect("manifest parses");
    let model = lower(&manifest).expect("lowering succeeds");
    HelmEmitter.emit(&model).expect("emit succeeds")
}

fn file<'a>(artifacts: &'a ExportArtifacts, name: &str) -> &'a str {
    let found = artifacts
        .files
        .iter()
        .find(|f| f.path.to_str() == Some(name))
        .unwrap_or_else(|| panic!("missing file {name}"));
    found.contents.as_str()
}

#[test]
fn matches_golden_files() {
    let a = artifacts(STACK);
    assert_eq!(
        file(&a, "Chart.yaml"),
        include_str!("golden/helm/Chart.yaml"),
        "Chart.yaml drifted"
    );
    assert_eq!(
        file(&a, "values.yaml"),
        include_str!("golden/helm/values.yaml"),
        "values.yaml drifted"
    );
    assert_eq!(
        file(&a, "templates/db.yaml"),
        include_str!("golden/helm/db.yaml"),
        "templates/db.yaml drifted"
    );
    assert_eq!(
        file(&a, "templates/cache.yaml"),
        include_str!("golden/helm/cache.yaml"),
        "cache.yaml drifted from the golden file"
    );
}

#[test]
fn values_carry_resource_knobs() {
    let values = {
        let a = artifacts(STACK);
        file(&a, "values.yaml").to_owned()
    };
    assert!(values.contains("replicas: 1"));
    assert!(values.contains("repository: postgres"));
    assert!(values.contains("LOG_LEVEL: info"), "env in values");
    assert!(
        values.contains("API_TOKEN: '***'"),
        "secret placeholder in values"
    );
}

#[test]
fn templates_reference_values() {
    let a = artifacts(STACK);
    let db = file(&a, "templates/db.yaml");
    assert!(db.contains(r#"index .Values.services "db""#), "got:\n{db}");
    assert!(db.contains("replicas: {{ $svc.replicas }}"), "got:\n{db}");
    assert!(db.contains("range $k, $v := $svc.env"), "got:\n{db}");
}

// --- portless + split_env characterisation tests ---

const PORTLESS_STACK: &str = r"
project:
  name: shop
resources:
  worker:
    container:
      image: alpine:3.20
      env:
        DB_URL: postgres://db:5432/app
        DB_PASSWORD: s3cret
";

#[test]
fn portless_service_emits_no_helm_service() {
    let a = artifacts(PORTLESS_STACK);
    let worker_template = file(&a, "templates/worker.yaml");
    assert!(
        !worker_template.contains("kind: Service"),
        "worker has no ports so no Service block should be emitted, got:\n{worker_template}"
    );
}

#[test]
fn mixed_env_routes_to_values() {
    let a = artifacts(PORTLESS_STACK);
    let values = file(&a, "values.yaml");
    let worker_template = file(&a, "templates/worker.yaml");
    // DB_URL is plain config: appears in values.yaml env section.
    assert!(
        values.contains("DB_URL"),
        "DB_URL missing from values.yaml, got:\n{values}"
    );
    // DB_PASSWORD matches SECRET_MARKERS: appears as placeholder in secrets section.
    assert!(
        values.contains("DB_PASSWORD: '***'"),
        "DB_PASSWORD placeholder missing from values.yaml, got:\n{values}"
    );
    // Real credential must never appear anywhere.
    assert!(
        !values.contains("s3cret"),
        "real secret value leaked into values.yaml, got:\n{values}"
    );
    // Template wires env and secrets from values.
    assert!(
        worker_template.contains("range $k, $v := $svc.env"),
        "env range missing from worker template, got:\n{worker_template}"
    );
    assert!(
        worker_template.contains("range $k, $v := $svc.secrets"),
        "secrets range missing from worker template, got:\n{worker_template}"
    );
}

#[test]
fn portless_worker_matches_golden() {
    let a = artifacts(PORTLESS_STACK);
    assert_eq!(
        file(&a, "templates/worker.yaml"),
        include_str!("golden/helm/worker.yaml"),
        "templates/worker.yaml drifted from the golden file"
    );
}

/// The resolved `command` is Docker's `Cmd`, which Kubernetes calls
/// `args`. The redis resource resolves to `["redis-server"]`; before this
/// test existed, the Helm emitter dropped it entirely.
#[test]
fn emits_resolved_command_as_args() {
    let a = artifacts(STACK);
    let cache = file(&a, "templates/cache.yaml");
    assert!(
        cache.contains("        args:\n        - redis-server\n"),
        "cache args missing, got:\n{cache}"
    );
    assert!(
        !cache.contains("        command:\n        - redis-server\n"),
        "redis-server must be args, not command: command is the entrypoint in Kubernetes, got:\n{cache}"
    );
}

/// Extracts the `- item` lines directly following the `header` line
/// (e.g. `"        command:\n"`), stopping at the first line that is not
/// a list item at the same indentation. Used to compare the argv block
/// written by the Helm emitter (hand-written text) against the same
/// block written by the Kubernetes emitter (typed struct through
/// serde), independently of the rest of the surrounding document.
fn argv_block<'a>(text: &'a str, header: &str) -> Vec<&'a str> {
    let after = text.split(header).nth(1).unwrap_or_else(|| {
        panic!("header {header:?} not found in:\n{text}");
    });
    after
        .lines()
        .take_while(|line| line.starts_with("        - "))
        .collect()
}

/// Extracts the raw, pre-render YAML text of the single list item
/// directly following `header` (e.g. `"        args:\n"`): the first
/// line's scalar plus, for a block scalar, its indented body lines.
/// Unlike `argv_block`, this keeps a multi-line scalar intact, as a
/// standalone reparseable YAML document, since a block scalar's body
/// lines do not themselves start with `"        - "`.
fn raw_arg_scalar(text: &str, header: &str) -> String {
    let after = text.split(header).nth(1).unwrap_or_else(|| {
        panic!("header {header:?} not found in:\n{text}");
    });
    let mut lines = after.lines();
    let first = lines
        .next()
        .unwrap_or_else(|| panic!("at least one line after header {header:?} in:\n{text}"));
    let first = first
        .strip_prefix("        - ")
        .unwrap_or_else(|| panic!("list item prefix missing in {first:?}"));
    let mut out = first.to_owned();
    for line in lines {
        // A block scalar's body lines are indented but are not
        // themselves list items; stop at the next list item, an
        // unindented line, or a document separator.
        if line.starts_with("        - ")
            || line == "---"
            || (!line.is_empty() && !line.starts_with(' '))
        {
            break;
        }
        out.push('\n');
        out.push_str(line);
    }
    out
}

/// The motivating case of #261: a redis `--requirepass s3cr:t` argument
/// contains a colon followed by a space, which YAML would otherwise
/// parse as a mapping key rather than part of the scalar. Both emitters
/// must agree on how this argument is quoted, since `up` and
/// `export kubernetes`/`export helm` describe the same container.
///
/// An argument containing `{{` is deliberately NOT exercised here: as
/// of fix wave 2, the two emitters diverge on that input on purpose
/// (see `helm_escapes_template_braces_to_close_the_injection` below and
/// `kubernetes_does_not_escape_template_braces` in
/// `kubernetes_emitter.rs`), so it would make this cross-emitter
/// equality check fail for the wrong reason.
#[test]
fn helm_quotes_scalars_like_the_kubernetes_emitter() {
    let yaml = r"
project:
  name: shop
resources:
  svc:
    container:
      image: alpine:3.20
      entrypoint: ['sh', '-c']
      command: ['echo a: b']
";
    let manifest = Manifest::parse(yaml).expect("manifest parses");
    let model = lower(&manifest).expect("lowering succeeds");

    let helm = HelmEmitter.emit(&model).expect("helm emit succeeds");
    let kubernetes = KubernetesEmitter
        .emit(&model)
        .expect("kubernetes emit succeeds");

    let helm_svc = helm
        .files
        .iter()
        .find(|f| f.path.to_str() == Some("templates/svc.yaml"))
        .expect("helm template emitted")
        .contents
        .as_str();
    let kubernetes_svc = kubernetes
        .files
        .iter()
        .find(|f| f.path.to_str() == Some("svc.yaml"))
        .expect("kubernetes manifest emitted")
        .contents
        .as_str();

    assert_eq!(
        argv_block(helm_svc, "        command:\n"),
        argv_block(kubernetes_svc, "        command:\n"),
        "Helm command: block quoted differently from Kubernetes, got helm:\n{helm_svc}\nkubernetes:\n{kubernetes_svc}"
    );
    assert_eq!(
        argv_block(helm_svc, "        args:\n"),
        argv_block(kubernetes_svc, "        args:\n"),
        "Helm args: block quoted differently from Kubernetes, got helm:\n{helm_svc}\nkubernetes:\n{kubernetes_svc}"
    );

    // The colon-space argument is the ambiguous one: unquoted, YAML
    // would parse it as a mapping key rather than as a scalar.
    let args = argv_block(helm_svc, "        args:\n");
    assert!(
        args.contains(&"        - 'echo a: b'"),
        "the colon-space argument must be quoted, got:\n{helm_svc}"
    );
}

/// Validates the generated chart with the real `helm` CLI.
/// Ignored by default: it needs Helm on the host.
#[test]
#[ignore = "requires helm on the host"]
fn output_passes_helm_lint() {
    use std::io::Write;

    if !common::tool_available("helm") {
        eprintln!("skipping: helm not found on PATH");
        return;
    }

    let dir = tempfile::tempdir().expect("temp dir");
    let chart = dir.path().join("chart");
    for f in &artifacts(STACK).files {
        let path = chart.join(&f.path);
        std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        std::fs::File::create(&path)
            .and_then(|mut file| file.write_all(f.contents.as_bytes()))
            .expect("write chart file");
    }

    let output = std::process::Command::new("helm")
        .arg("lint")
        .arg(&chart)
        .output()
        .expect("helm runs");
    assert!(
        output.status.success(),
        "helm lint rejected the chart:\n{}\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

/// Same translation as the Kubernetes emitter: a chart is Kubernetes.
#[test]
fn entrypoint_becomes_helm_command_and_command_becomes_args() {
    let yaml = r"
project:
  name: shop
  version: 1.4.0
export:
  helm:
    chart_name: shop-chart
resources:
  svc:
    container:
      image: alpine:3.20
      entrypoint: ['sh', '-c']
      command: ['echo hi']
";
    let a = artifacts(yaml);
    let svc = file(&a, "templates/svc.yaml");
    assert!(
        svc.contains("        command:\n        - sh\n        - -c\n"),
        "the manifest entrypoint must become the chart command, got:\n{svc}"
    );
    assert!(
        svc.contains("        args:\n        - echo hi\n"),
        "the manifest command must become args, got:\n{svc}"
    );
}

/// Fix wave 2, Critical A, generalised in fix wave 3 to a small table of
/// brace-run shapes: multiple consecutive openers, a bare closer with
/// no opener, an opener embedded after other text, a colon-space
/// argument combined with an opener, and a block-scalar body
/// containing an opener. Helm renders every file under `templates/`
/// through Go `text/template` BEFORE any YAML parser sees it, so a
/// resolved argv element containing `{{` is a template injection path,
/// not a formatting nit: quoting it as a YAML string does nothing to
/// Go's templater, which reads past the quotes. The oracle here is
/// independent of the Kubernetes emitter (that cross-check is what let
/// this hole through last wave): for each input, it applies the
/// inverse of Helm's literal escape, the same substitution Go's
/// templater performs on `{{ "{{" }}` at `helm install` time, and
/// reparses the result as YAML to check the argument comes back
/// exactly as it went in.
#[test]
fn helm_escapes_template_braces_to_close_the_injection() {
    for original in [
        "redis {{ .Values.x }} arg",
        "{{{",
        "{{{{",
        "a}}b",
        "echo a: b {{ .V }}",
        "line1 {{ .V }}\nline2",
    ] {
        let yaml = format!(
            r"
project:
  name: shop
resources:
  svc:
    container:
      image: alpine:3.20
      command: [{original:?}]
"
        );
        let a = artifacts(&yaml);
        let svc = file(&a, "templates/svc.yaml");

        let scalar = raw_arg_scalar(svc, "        args:\n");

        // Every escaped occurrence in the arg accounted for, nothing
        // bare should remain (the rest of the file legitimately has
        // other, unrelated `{{ ... }}` Go template directives, so this
        // check is scoped to the arg's own scalar, not the whole
        // file).
        let without_escapes = scalar.replace(r#"{{ "{{" }}"#, "");
        assert!(
            !without_escapes.contains("{{"),
            "a raw, unescaped `{{{{` opener survived in the arg for {original:?}, got:\n{scalar}"
        );
        if original.contains("{{") {
            assert!(
                scalar.contains(r#"{{ "{{" }}"#),
                "the `{{{{` opener must be escaped to the Helm literal for {original:?}, got:\n{scalar}"
            );
        }

        // Simulate Go's templater: it renders `{{ "{{" }}` back to a
        // literal `{{` before the YAML parser ever runs.
        let rendered = scalar.replace(r#"{{ "{{" }}"#, "{{");
        let round_tripped: String = serde_norway::from_str(&rendered).unwrap_or_else(|e| {
            panic!("the rendered scalar reparses as YAML for {original:?}: {e}\ngot:\n{rendered}")
        });
        assert_eq!(
            round_tripped, original,
            "the arg must round-trip through the escape/render/parse chain to the exact original value for {original:?}"
        );
    }
}

/// Reparse the first document of an emitted Helm template as YAML,
/// preserving every byte after the leading Go template directive line,
/// including all trailing newlines. Go's templater consumes the
/// `{{- $svc := ... -}}` directive line before the YAML parser ever
/// sees it, so that one line is dropped here; nothing else is touched.
/// A lenient reconstruction built from `str::lines()` drops the final
/// line terminator and never yields a trailing empty line, silently
/// masking a trailing-newline bug in the emitter this oracle exists to
/// catch, so this helper preserves trailing bytes exactly instead.
fn reparse_first_document(svc: &str) -> serde_norway::Value {
    let first_doc = svc.split("---").next().expect("at least one document");
    let without_directive = first_doc
        .split_once('\n')
        .expect("template has a leading directive line")
        .1;
    serde_norway::from_str(without_directive).expect("the emitted chart must reparse as YAML")
}

/// Fix wave 2, Critical B. `serde_norway` indents a block scalar's body
/// two columns from the document root, but this emitter splices the
/// result after a `        - ` list marker (column 10): an unindented
/// body dedents out of the list item and the chart fails to parse.
/// Reparsing the emitted template as YAML is the oracle: it must
/// reproduce the exact multi-line value, not merely look plausible.
#[test]
fn multiline_arg_round_trips_through_the_emitted_template() {
    let original = "set -e\necho one\nexec app";
    let yaml = format!(
        r"
project:
  name: shop
resources:
  svc:
    container:
      image: alpine:3.20
      entrypoint: ['sh', '-c']
      command: [{original:?}]
"
    );
    let a = artifacts(&yaml);
    let svc = file(&a, "templates/svc.yaml");

    let parsed = reparse_first_document(svc);
    let args = parsed["spec"]["template"]["spec"]["containers"][0]["args"]
        .as_sequence()
        .expect("args is a sequence");
    assert_eq!(args.len(), 1, "expected exactly one arg, got: {args:?}");
    assert_eq!(
        args[0].as_str(),
        Some(original),
        "the multi-line arg must round-trip exactly, got: {:?}",
        args[0]
    );
}

/// Fix wave 3, adversarial re-review of `cce9046`. `serde_norway`
/// appends exactly one document-terminating newline to every scalar it
/// serialises; `yaml_scalar` used to remove it with `.trim_end()`,
/// which also strips the trailing blank lines that a `|+` (keep)
/// chomping block scalar deliberately preserves as part of the value.
/// An argument ending in two or more newlines therefore lost its
/// trailing newlines silently: the same `up`-vs-`export` argv
/// divergence class of bug as #262, masked until fix wave 2 made
/// multi-line args parse at all. Reparsing the emitted template as
/// YAML is the oracle: it must reproduce the exact trailing newlines,
/// not merely look plausible.
#[test]
fn trailing_newline_arg_round_trips_through_the_emitted_template() {
    let original = "set -e\necho one\n\n";
    let yaml = format!(
        r"
project:
  name: shop
resources:
  svc:
    container:
      image: alpine:3.20
      entrypoint: ['sh', '-c']
      command: [{original:?}]
"
    );
    let a = artifacts(&yaml);
    let svc = file(&a, "templates/svc.yaml");

    let parsed = reparse_first_document(svc);
    let args = parsed["spec"]["template"]["spec"]["containers"][0]["args"]
        .as_sequence()
        .expect("args is a sequence");
    assert_eq!(args.len(), 1, "expected exactly one arg, got: {args:?}");
    assert_eq!(
        args[0].as_str(),
        Some(original),
        "the trailing newlines in the arg must round-trip exactly, got: {:?}",
        args[0]
    );
}