forjar 1.4.2

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
//! Tests: Pre-condition checks.

#![allow(unused_imports)]
use super::check::*;
use super::commands::*;
use super::dispatch::*;
use super::helpers::*;
use super::helpers_state::*;
use super::helpers_time::*;
use super::observe::*;
use super::validate_core::*;
use crate::core::types::ProvenanceEvent;
use crate::core::{codegen, executor, migrate, parser, planner, resolver, secrets, state, types};
use crate::transport;
use crate::tripwire::{anomaly, drift, eventlog, tracer};
use std::path::{Path, PathBuf};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_anomaly_detects_drift() {
        let dir = tempfile::tempdir().unwrap();
        let state = dir.path().join("state");
        let machine_dir = state.join("web");
        std::fs::create_dir_all(&machine_dir).unwrap();

        let mut events = String::new();
        // 2 converges + 1 drift = 3 events (meets min_events=3)
        for _ in 0..2 {
            events.push_str(
                &serde_json::to_string(&types::TimestampedEvent {
                    ts: "2026-02-25T00:00:00Z".to_string(),
                    event: types::ProvenanceEvent::ResourceConverged {
                        machine: "web".to_string(),
                        resource: "config-file".to_string(),
                        duration_seconds: 0.5,
                        hash: "def".to_string(),
                    },
                })
                .unwrap(),
            );
            events.push('\n');
        }
        events.push_str(
            &serde_json::to_string(&types::TimestampedEvent {
                ts: "2026-02-25T01:00:00Z".to_string(),
                event: types::ProvenanceEvent::DriftDetected {
                    machine: "web".to_string(),
                    resource: "config-file".to_string(),
                    expected_hash: "aaa".to_string(),
                    actual_hash: "bbb".to_string(),
                },
            })
            .unwrap(),
        );
        events.push('\n');

        std::fs::write(machine_dir.join("events.jsonl"), &events).unwrap();

        let result = cmd_anomaly(&state, None, 3, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_anomaly_json_output() {
        let dir = tempfile::tempdir().unwrap();
        let state = dir.path().join("state");
        let machine_dir = state.join("srv");
        std::fs::create_dir_all(&machine_dir).unwrap();

        // Write 3 converge events for one resource (no anomaly, just normal)
        let mut events = String::new();
        for _ in 0..3 {
            events.push_str(
                &serde_json::to_string(&types::TimestampedEvent {
                    ts: "2026-02-25T00:00:00Z".to_string(),
                    event: types::ProvenanceEvent::ResourceConverged {
                        machine: "srv".to_string(),
                        resource: "pkg".to_string(),
                        duration_seconds: 1.0,
                        hash: "xyz".to_string(),
                    },
                })
                .unwrap(),
            );
            events.push('\n');
        }

        std::fs::write(machine_dir.join("events.jsonl"), &events).unwrap();

        let result = cmd_anomaly(&state, None, 3, true);
        assert!(result.is_ok());
    }

    #[test]
    fn test_anomaly_machine_filter() {
        let dir = tempfile::tempdir().unwrap();
        let state = dir.path().join("state");
        // Create two machines
        let m1 = state.join("m1");
        let m2 = state.join("m2");
        std::fs::create_dir_all(&m1).unwrap();
        std::fs::create_dir_all(&m2).unwrap();

        // Events only on m2
        let mut events = String::new();
        for _ in 0..5 {
            events.push_str(
                &serde_json::to_string(&types::TimestampedEvent {
                    ts: "2026-02-25T00:00:00Z".to_string(),
                    event: types::ProvenanceEvent::ResourceFailed {
                        machine: "m2".to_string(),
                        resource: "bad-svc".to_string(),
                        error: "timeout".to_string(),
                    },
                })
                .unwrap(),
            );
            events.push('\n');
        }
        std::fs::write(m2.join("events.jsonl"), &events).unwrap();

        // Filter to m1 (no events) → no anomalies
        let result = cmd_anomaly(&state, Some("m1"), 1, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_anomaly_dispatch() {
        let dir = tempfile::tempdir().unwrap();
        let state = dir.path().join("state");
        std::fs::create_dir_all(&state).unwrap();

        let result = dispatch(
            Commands::Anomaly(AnomalyArgs {
                state_dir: state,
                machine: None,
                min_events: 3,
                json: false,
            }),
            0,
            true,
        );
        assert!(result.is_ok());
    }

    // ── Import scan type tests ─────────────────────────────────

    #[test]
    fn test_fj017_check_machine_filter() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("forjar.yaml");
        std::fs::write(
            &config,
            r#"
version: "1.0"
name: check-test
machines:
  local:
    hostname: local
    addr: 127.0.0.1
resources:
  pkg:
    type: package
    machine: local
    provider: apt
    packages: [curl]
"#,
        )
        .unwrap();
        // Check with machine filter
        cmd_check(&config, Some("local"), None, None, false, false).unwrap();
    }

    #[test]
    fn test_fj017_check_resource_filter() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("forjar.yaml");
        std::fs::write(
            &config,
            r#"
version: "1.0"
name: check-test
machines:
  local:
    hostname: local
    addr: 127.0.0.1
resources:
  pkg1:
    type: package
    machine: local
    provider: apt
    packages: [curl]
  pkg2:
    type: package
    machine: local
    provider: apt
    packages: [wget]
"#,
        )
        .unwrap();
        // Check only specific resource
        cmd_check(&config, None, Some("pkg1"), None, false, false).unwrap();
    }

    #[test]
    fn test_fj017_check_json_output() {
        let dir = tempfile::tempdir().unwrap();
        let config = dir.path().join("forjar.yaml");
        std::fs::write(
            &config,
            r#"
version: "1.0"
name: check-test
machines:
  local:
    hostname: local
    addr: 127.0.0.1
resources:
  conf:
    type: file
    machine: local
    path: /tmp/forjar-check-test.txt
    content: hello
"#,
        )
        .unwrap();
        // JSON output
        cmd_check(&config, None, None, None, true, false).unwrap();
    }

    // ── Rollback error tests ───────────────────────────────────

    #[test]
    fn test_fj273_test_command_parse() {
        let cmd = Commands::Test(TestArgs {
            file: PathBuf::from("forjar.yaml"),
            machine: Some("web".to_string()),
            resource: None,
            tag: None,
            group: None,
            json: true,
            sandbox: "pepita".to_string(),
            parallel: 4,
            pairs: false,
            mutations: 50,
        });
        match cmd {
            Commands::Test(TestArgs { json, machine, .. }) => {
                assert!(json);
                assert_eq!(machine, Some("web".to_string()));
            }
            _ => panic!("expected Test"),
        }
    }

    #[test]
    fn test_fj273_test_dispatch_runs() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("forjar.yaml");
        std::fs::write(
            &config_path,
            "version: \"1.0\"\nname: test-proj\nmachines:\n  local:\n    hostname: localhost\n    addr: 127.0.0.1\nresources:\n  my-file:\n    type: file\n    machine: local\n    path: /tmp/fj273-test-dispatch.txt\n    content: hello\n",
        )
        .unwrap();
        let result = dispatch(
            Commands::Test(TestArgs {
                file: config_path,
                machine: None,
                resource: None,
                tag: None,
                group: None,
                json: false,
                sandbox: "pepita".to_string(),
                parallel: 4,
                pairs: false,
                mutations: 50,
            }),
            0,
            true,
        );
        // Will fail (file doesn't exist) or pass — either way it runs without panic
        let _ = result;
    }

    #[test]
    fn test_fj273_test_json_output() {
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("forjar.yaml");
        std::fs::write(
            &config_path,
            "version: \"1.0\"\nname: test-proj\nmachines:\n  local:\n    hostname: localhost\n    addr: 127.0.0.1\nresources:\n  my-file:\n    type: file\n    machine: local\n    path: /tmp/fj273-test-json.txt\n    content: hello\n",
        )
        .unwrap();
        let result = dispatch(
            Commands::Test(TestArgs {
                file: config_path,
                machine: None,
                resource: None,
                tag: None,
                group: None,
                json: true,
                sandbox: "pepita".to_string(),
                parallel: 4,
                pairs: false,
                mutations: 50,
            }),
            0,
            true,
        );
        let _ = result;
    }

    #[test]
    fn test_fj273_test_nonexistent_config() {
        let result = dispatch(
            Commands::Test(TestArgs {
                file: PathBuf::from("/tmp/fj273-nonexistent.yaml"),
                machine: None,
                resource: None,
                tag: None,
                group: None,
                json: false,
                sandbox: "pepita".to_string(),
                parallel: 4,
                pairs: false,
                mutations: 50,
            }),
            0,
            true,
        );
        assert!(result.is_err());
    }

    // ========================================================================
    // FJ-281: Resource groups
    // ========================================================================

    #[test]
    fn test_fj281_test_group_flag() {
        let cmd = Commands::Test(TestArgs {
            file: PathBuf::from("forjar.yaml"),
            machine: None,
            resource: None,
            tag: None,
            group: Some("database".to_string()),
            json: false,
            sandbox: "pepita".to_string(),
            parallel: 4,
            pairs: false,
            mutations: 50,
        });
        match cmd {
            Commands::Test(TestArgs { group, .. }) => {
                assert_eq!(group, Some("database".to_string()));
            }
            _ => panic!("expected Test"),
        }
    }

    // ── FJ-282: forjar validate --strict ──────────────────────────

    #[test]
    fn test_fj282_strict_off_skips_checks() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("forjar.yaml");
        // bad machine ref, but strict=false so it should pass
        let yaml = r#"
version: "1.0"
name: test
machines:
  local:
    hostname: local
    addr: 127.0.0.1
resources:
  cfg:
    type: file
    machine: nonexistent
    path: /tmp/test.txt
    content: "hello"
"#;
        std::fs::write(&file, yaml).unwrap();
        // strict=false should skip deep checks — but parse_and_validate
        // may still reject unknown machine refs. If so, we just verify
        // that the error is NOT about "strict validation".
        let result = cmd_validate(&file, false, false, false);
        match result {
            Ok(()) => {} // parser didn't catch it — fine
            Err(msg) => assert!(!msg.contains("strict validation")),
        }
    }

    // ── FJ-283: Apply retry with backoff ──────────────────────────

    #[test]
    fn test_fj305_check_json_ci_fields() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("fj305.txt");
        std::fs::write(&target, "ci-check").unwrap();

        let config_path = dir.path().join("forjar.yaml");
        std::fs::write(
            &config_path,
            format!(
                r#"
version: "1.0"
name: ci-gate
machines:
  local:
    hostname: localhost
    addr: 127.0.0.1
resources:
  cfg:
    type: file
    machine: local
    path: {}
    content: ci-check
"#,
                target.display()
            ),
        )
        .unwrap();
        // The function prints JSON to stdout — just verify it succeeds
        let result = cmd_check(&config_path, None, None, None, true, false);
        assert!(result.is_ok());
    }

    // ── FJ-306: env --json enhanced ──
}