forjar 1.33.0

Rust-native Infrastructure as Code — bare-metal first, BLAKE3 state, provenance tracing
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
use super::file::*;
use crate::core::shell_escape::decode_written_file;
use crate::core::types::{MachineTarget, Resource, ResourceType};
use base64::Engine;

fn make_file_resource(path: &str, content: Option<&str>) -> Resource {
    Resource {
        phony: false,
        resource_type: ResourceType::File,
        machine: MachineTarget::Single("m1".to_string()),
        state: None,
        depends_on: vec![],
        provider: None,
        packages: vec![],
        version: None,
        path: Some(path.to_string()),
        content: content.map(|s| s.to_string()),
        source: None,
        target: None,
        owner: Some("root".to_string()),
        group: Some("root".to_string()),
        mode: Some("0644".to_string()),
        name: None,
        enabled: None,
        restart_on: vec![],
        triggers: vec![],
        fs_type: None,
        options: None,
        uid: None,
        shell: None,
        home: None,
        groups: vec![],
        ssh_authorized_keys: vec![],
        system_user: false,
        schedule: None,
        command: None,
        image: None,
        ports: vec![],
        environment: vec![],
        volumes: vec![],
        restart: None,
        protocol: None,
        port: None,
        action: None,
        from_addr: None,
        recipe: None,
        inputs: std::collections::HashMap::new(),
        arch: vec![],
        tags: vec![],
        resource_group: None,
        when: None,
        count: None,
        for_each: None,
        chroot_dir: None,
        namespace_uid: None,
        namespace_gid: None,
        seccomp: false,
        netns: false,
        cpuset: None,
        memory_limit: None,
        overlay_lower: None,
        overlay_upper: None,
        overlay_work: None,
        overlay_merged: None,
        format: None,
        quantization: None,
        checksum: None,
        cache_dir: None,
        gpu_backend: None,
        driver_version: None,
        cuda_version: None,
        rocm_version: None,
        devices: vec![],
        persistence_mode: None,
        compute_mode: None,
        gpu_memory_limit_mb: None,
        output_artifacts: vec![],
        completion_check: None,
        timeout: None,
        working_dir: None,
        task_mode: None,
        task_inputs: vec![],
        stages: vec![],
        cache: false,
        gpu_device: None,
        restart_delay: None,
        quality_gate: None,
        health_check: None,
        restart_policy: None,
        pre_apply: None,
        post_apply: None,
        lifecycle: None,
        store: false,
        sudo: false,
        script: None,
        gather: vec![],
        scatter: vec![],
        build_machine: None,
        repo: None,
        tag: None,
        asset_pattern: None,
        binary: None,
        install_dir: None,
        overlay_ip: None,
        overlay_iface: None,
        overlay_hosts: None,
        overlay_firewall: None,
        ..Default::default()
    }
}

#[test]
fn test_fj007_check_file() {
    let r = make_file_resource("/etc/test.conf", None);
    let script = check_script(&r);
    assert!(script.contains("test -f '/etc/test.conf'"));
}

#[test]
fn test_fj007_apply_file_with_content() {
    let r = make_file_resource("/etc/exports", Some("/data 192.168.1.0/24(ro)"));
    let script = apply_script(&r);
    // C8 (GH #296): the content is deployed delimiter-free and byte-exact. Assert on
    // the payload the script actually writes, not on the script text.
    assert_eq!(
        decode_written_file(&script, "/etc/exports"),
        Some(b"/data 192.168.1.0/24(ro)".to_vec())
    );
    assert!(script.contains("chown 'root:root'"));
    assert!(script.contains("chmod '0644'"));
}

#[test]
fn test_fj007_apply_directory() {
    let mut r = make_file_resource("/data/transcripts", None);
    r.state = Some("directory".to_string());
    r.owner = Some("noah".to_string());
    r.group = None;
    r.mode = Some("0755".to_string());
    let script = apply_script(&r);
    assert!(script.contains("mkdir -p '/data/transcripts'"));
    assert!(script.contains("chown 'noah'"));
    assert!(script.contains("chmod '0755'"));
}

#[test]
fn test_fj007_apply_absent() {
    let mut r = make_file_resource("/tmp/garbage", None);
    r.state = Some("absent".to_string());
    let script = apply_script(&r);
    assert!(script.contains("rm -rf '/tmp/garbage'"));
}

#[test]
fn test_fj007_apply_symlink() {
    let mut r = make_file_resource("/usr/local/bin/tool", None);
    r.state = Some("symlink".to_string());
    r.target = Some("/opt/tool/bin/tool".to_string());
    let script = apply_script(&r);
    assert!(script.contains("ln -sfn '/opt/tool/bin/tool' '/usr/local/bin/tool'"));
}

#[test]
fn test_fj007_content_transport_is_safe() {
    // Content with quotes and special chars must reach the target as data.
    // C8 (GH #296): this used to assert the heredoc delimiter was present, which said
    // nothing about whether the content could close it. The delimiter is gone —
    // content is base64 and cannot reach the shell parser at all.
    let content = "key=\"value\"\n$HOME/path";
    let r = make_file_resource("/etc/test", Some(content));
    let script = apply_script(&r);
    assert!(!script.contains("FORJAR_EOF"));
    // No expansion is possible: the raw metacharacters are not in the script.
    assert!(!script.contains("$HOME"));
    assert_eq!(
        decode_written_file(&script, "/etc/test"),
        Some(content.as_bytes().to_vec())
    );
}

#[test]
fn test_fj007_check_script_directory() {
    let mut r = make_file_resource("/data/dir", None);
    r.state = Some("directory".to_string());
    let script = check_script(&r);
    assert!(script.contains("test -d '/data/dir'"));
    assert!(script.contains("exists:directory"));
}

#[test]
fn test_fj007_check_script_absent() {
    let mut r = make_file_resource("/tmp/gone", None);
    r.state = Some("absent".to_string());
    let script = check_script(&r);
    assert!(script.contains("test -e '/tmp/gone'"));
    assert!(script.contains("exists:present"));
}

#[test]
fn test_fj007_check_script_symlink() {
    let mut r = make_file_resource("/usr/bin/tool", None);
    r.state = Some("symlink".to_string());
    let script = check_script(&r);
    assert!(script.contains("test -L '/usr/bin/tool'"));
    assert!(script.contains("exists:symlink"));
}

#[test]
fn test_fj007_state_query_script() {
    let r = make_file_resource("/etc/config", None);
    let script = state_query_script(&r);
    assert!(script.contains("/etc/config"));
    assert!(script.contains("stat"));
    assert!(script.contains("MISSING"));
}

#[test]
fn test_fj007_apply_file_owner_no_group() {
    let mut r = make_file_resource("/etc/test.conf", Some("data"));
    r.group = None;
    let script = apply_script(&r);
    assert!(script.contains("chown 'root' '/etc/test.conf.forjar-new'"));
    assert!(!script.contains("chown 'root:"));
}

#[test]
fn test_fj007_apply_directory_owner_and_group() {
    let mut r = make_file_resource("/data/exports", None);
    r.state = Some("directory".to_string());
    r.owner = Some("nfs".to_string());
    r.group = Some("nfs".to_string());
    r.mode = None;
    let script = apply_script(&r);
    assert!(script.contains("mkdir -p '/data/exports'"));
    assert!(script.contains("chown 'nfs:nfs' '/data/exports'"));
}

#[test]
fn test_fj007_check_script_unknown_state() {
    let mut r = make_file_resource("/tmp/test", None);
    r.state = Some("custom-state".to_string());
    let script = check_script(&r);
    assert!(script.contains("unsupported file state: custom-state"));
}

#[test]
fn test_fj007_apply_script_unknown_state() {
    let mut r = make_file_resource("/tmp/test", None);
    r.state = Some("custom-state".to_string());
    let script = apply_script(&r);
    assert!(script.contains("unsupported file state: custom-state"));
}

#[test]
fn test_fj007_check_script_explicit_file_state() {
    // Verify explicit "file" state works the same as default
    let mut r = make_file_resource("/etc/conf", None);
    r.state = Some("file".to_string());
    let script = check_script(&r);
    assert!(script.contains("test -f '/etc/conf'"));
    assert!(script.contains("exists:file"));
}

#[test]
fn test_fj007_apply_file_at_root_no_mkdir() {
    // File at root path (/) should NOT have `mkdir -p '/'`
    let mut r = make_file_resource("/init", Some("boot script"));
    r.owner = None;
    let script = apply_script(&r);
    assert!(script.contains("| base64 -d > '/init.forjar-new'"));
    assert!(!script.contains("mkdir -p '/'"));
}

#[test]
fn test_fj035_source_file_base64() {
    // Create a temp file to use as source
    let dir = tempfile::tempdir().unwrap();
    let source_path = dir.path().join("config.txt");
    std::fs::write(&source_path, "hello world\n").unwrap();

    let mut r = make_file_resource("/etc/app/config.txt", None);
    r.source = Some(source_path.to_str().unwrap().to_string());
    let script = apply_script(&r);

    // Should use base64 decode pipeline
    assert!(script.contains("base64 -d"));
    assert!(script.contains("/etc/app/config.txt"));
    // Should contain the base64 encoding of "hello world\n"
    let expected_b64 = base64::engine::general_purpose::STANDARD.encode(b"hello world\n");
    assert!(script.contains(&expected_b64));
}

#[test]
fn test_fj035_source_file_missing() {
    let mut r = make_file_resource("/etc/app/config.txt", None);
    r.source = Some("/nonexistent/path/file.txt".to_string());
    let script = apply_script(&r);
    assert!(script.contains("ERROR: cannot read source file"));
}

#[test]
fn test_fj035_source_takes_precedence_over_content() {
    // When both source and content are set, source wins (though validator rejects this)
    let dir = tempfile::tempdir().unwrap();
    let source_path = dir.path().join("from-source.txt");
    std::fs::write(&source_path, "from source").unwrap();

    let mut r = make_file_resource("/etc/test", Some("from content"));
    r.source = Some(source_path.to_str().unwrap().to_string());
    let script = apply_script(&r);

    // C8 (GH #296): both branches now share one transport, so "no FORJAR_EOF" is no
    // longer a discriminator. Decode what the script deploys and check WHICH of
    // the two candidate payloads it is.
    assert_eq!(
        decode_written_file(&script, "/etc/test"),
        Some(b"from source".to_vec())
    );
}

#[test]
fn test_fj035_source_binary_file() {
    // Verify binary content is safely transferred via base64
    let dir = tempfile::tempdir().unwrap();
    let source_path = dir.path().join("binary.bin");
    let binary_data: Vec<u8> = (0..=255).collect();
    std::fs::write(&source_path, &binary_data).unwrap();

    let mut r = make_file_resource("/opt/bin/data.bin", None);
    r.source = Some(source_path.to_str().unwrap().to_string());
    let script = apply_script(&r);

    assert!(script.contains("base64 -d"));
    assert!(script.contains("/opt/bin/data.bin"));
}

#[test]
fn test_fj007_apply_file_creates_parent_dir() {
    let r = make_file_resource("/etc/app/nested/config.yaml", Some("key: val"));
    let script = apply_script(&r);
    assert!(script.contains("mkdir -p '/etc/app/nested'"));
    let mkdir_idx = script.find("mkdir -p").unwrap();
    let write_idx = script.find("| base64 -d >").unwrap();
    assert!(
        mkdir_idx < write_idx,
        "mkdir must precede the content write in apply script"
    );
}

/// forjar#310: `group:` declared WITHOUT `owner:` emitted no ownership command
/// at all, and the lock recorded `group: <declared>` under `converged` anyway.
///
/// A declared attribute that is never applied and is still reported converged is
/// the worst shape available: the operator wrote down an intent the system
/// quietly agreed to ignore. 58 directory resources on the paiml fleet declare
/// ownership.
#[test]
fn group_without_owner_is_actually_applied() {
    let mut r = Resource {
        resource_type: ResourceType::File,
        machine: MachineTarget::Single("m1".to_string()),
        path: Some("/etc/thing.conf".to_string()),
        content: Some("x".to_string()),
        ..Default::default()
    };
    r.group = Some("staff".to_string());
    r.owner = None;
    let script = apply_script(&r);
    assert!(
        script.contains("chgrp 'staff' '/etc/thing.conf.forjar-new'"),
        "group declared without owner emitted NO ownership command:\n{script}"
    );

    // Controls — the three other combinations must be unchanged.
    r.owner = Some("noah".to_string());
    let both = apply_script(&r);
    assert!(
        both.contains("chown 'noah:staff' '/etc/thing.conf.forjar-new'"),
        "owner+group regressed:\n{both}"
    );
    assert!(
        !both.contains("chgrp"),
        "owner+group must use one chown, not chown plus chgrp:\n{both}"
    );

    r.group = None;
    let owner_only = apply_script(&r);
    assert!(
        owner_only.contains("chown 'noah' '/etc/thing.conf.forjar-new'"),
        "owner-only regressed:\n{owner_only}"
    );

    r.owner = None;
    let neither = apply_script(&r);
    assert!(
        !neither.contains("chown") && !neither.contains("chgrp"),
        "neither declared, but an ownership command was emitted:\n{neither}"
    );
}

/// forjar#634: a script parked on a child must finish on the bytes it started
/// with. An in-place rewrite (`> path`) hands the parked shell the NEW bytes at
/// its OLD offset; the two scripts below are the same length, so under the old
/// emitter the parked shell resumes at `echo NEW`. Executes the artifact.
#[test]
fn fj634_a_parked_script_finishes_on_its_old_bytes() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("wrapper.sh");
    let out = dir.path().join("out");
    std::fs::write(&target, "sleep 1\necho OLD >\"$1\"\n").unwrap();
    let mut parked = std::process::Command::new("bash")
        .arg(&target)
        .arg(&out)
        .spawn()
        .unwrap();
    std::thread::sleep(std::time::Duration::from_millis(300));
    let mut r = make_file_resource(
        target.to_str().unwrap(),
        Some("sleep 1\necho NEW >\"$1\"\n"),
    );
    r.owner = None;
    r.group = None;
    let applied = std::process::Command::new("bash")
        .arg("-c")
        .arg(apply_script(&r))
        .status()
        .unwrap();
    assert!(applied.success(), "apply script failed");
    assert!(parked.wait().unwrap().success());
    assert_eq!(
        std::fs::read_to_string(&out).unwrap(),
        "OLD\n",
        "the parked script ran the NEW bytes"
    );
    assert_eq!(
        std::fs::read_to_string(&target).unwrap(),
        "sleep 1\necho NEW >\"$1\"\n"
    );
    assert!(
        !dir.path().join("wrapper.sh.forjar-new").exists(),
        "staged file left behind"
    );
}

/// forjar#634: the rename must not drop an attribute the resource does not
/// declare. An in-place write kept the old inode's mode; an executable with no
/// `mode:` must still be executable after the replace.
#[test]
fn fj634_an_undeclared_exec_bit_survives_the_replace() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("tool");
    std::fs::write(&target, "#!/bin/sh\necho old\n").unwrap();
    std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o755)).unwrap();
    let mut r = make_file_resource(target.to_str().unwrap(), Some("#!/bin/sh\necho new\n"));
    r.mode = None;
    r.owner = None;
    r.group = None;
    let applied = std::process::Command::new("bash")
        .arg("-c")
        .arg(apply_script(&r))
        .status()
        .unwrap();
    assert!(applied.success());
    let mode = std::fs::metadata(&target).unwrap().permissions().mode() & 0o777;
    assert_eq!(mode, 0o755, "undeclared exec bit lost: {mode:o}");
    assert_eq!(
        std::fs::read_to_string(&target).unwrap(),
        "#!/bin/sh\necho new\n"
    );
}

/// forjar#634 review: a directory at a `state: file` path is refused. `> dir`
/// failed with EISDIR; `mv -f staged dir` would move the file INTO it and exit 0.
#[test]
fn fj634_a_directory_at_the_path_is_refused_not_filled() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("conf");
    std::fs::create_dir(&target).unwrap();
    let mut r = make_file_resource(target.to_str().unwrap(), Some("x\n"));
    r.owner = None;
    r.group = None;
    let applied = std::process::Command::new("bash")
        .arg("-c")
        .arg(apply_script(&r))
        .status()
        .unwrap();
    assert!(
        !applied.success(),
        "apply reported success over a directory"
    );
    assert!(target.is_dir());
    assert_eq!(
        std::fs::read_dir(&target).unwrap().count(),
        0,
        "file moved into the directory"
    );
}

/// forjar#634 review: an unreadable source fails before anything is staged.
#[test]
fn fj634_an_unreadable_source_leaves_no_staged_file() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("conf");
    std::fs::write(&target, "old\n").unwrap();
    let mut r = make_file_resource(target.to_str().unwrap(), None);
    r.source = Some(dir.path().join("no-such-source").display().to_string());
    r.owner = None;
    r.group = None;
    let applied = std::process::Command::new("bash")
        .arg("-c")
        .arg(apply_script(&r))
        .status()
        .unwrap();
    assert!(!applied.success());
    assert!(
        !dir.path().join("conf.forjar-new").exists(),
        "staged file left behind"
    );
    assert_eq!(std::fs::read_to_string(&target).unwrap(), "old\n");
}