forjar 1.24.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
//! FJ-3203: Compliance pack pre-apply gate.
//!
//! Loads compliance packs from a directory and evaluates them against
//! config resources. Blocks apply if any error-severity rule fails.

use crate::core::compliance_pack::{evaluate_pack, list_packs, parse_pack, PackEvalResult};
use crate::core::types::ForjarConfig;
use std::collections::HashMap;
use std::path::Path;

/// Result of the compliance gate check.
#[derive(Debug, Clone)]
pub struct ComplianceGateResult {
    /// Total packs evaluated.
    pub packs_evaluated: usize,
    /// Pack evaluation results.
    pub results: Vec<PackEvalResult>,
    /// Total error-severity failures.
    pub error_count: usize,
    /// Total warning-severity issues.
    pub warning_count: usize,
}

impl ComplianceGateResult {
    /// Whether the gate passed (no error-severity failures).
    pub fn passed(&self) -> bool {
        self.error_count == 0
    }
}

/// Convert forjar config resources to the flat map format expected by compliance pack evaluation.
pub fn config_to_resource_map(config: &ForjarConfig) -> HashMap<String, HashMap<String, String>> {
    let mut resources = HashMap::new();
    for (id, resource) in &config.resources {
        let mut fields = HashMap::new();
        fields.insert(
            "type".into(),
            format!("{:?}", resource.resource_type).to_lowercase(),
        );
        if let Some(ref owner) = resource.owner {
            fields.insert("owner".into(), owner.clone());
        }
        if let Some(ref group) = resource.group {
            fields.insert("group".into(), group.clone());
        }
        if let Some(ref mode) = resource.mode {
            fields.insert("mode".into(), mode.clone());
        }
        if let Some(ref content) = resource.content {
            fields.insert("content".into(), content.clone());
        }
        if let Some(ref name) = resource.name {
            fields.insert("name".into(), name.clone());
        }
        if let Some(ref enabled) = resource.enabled {
            fields.insert("enabled".into(), enabled.to_string());
        }
        if !resource.tags.is_empty() {
            fields.insert("tags".into(), resource.tags.join(","));
        }
        resources.insert(id.clone(), fields);
    }
    resources
}

/// Run the compliance gate: load all packs from a directory and evaluate.
///
/// `Err` means the gate WAS BLIND — the directory would not list, or a pack
/// file in it would not read. It does NOT mean a rule failed: a failing rule is
/// `error_count` on an `Ok`, which is what `passed()` reads. (The doc here used
/// to say "Returns `Err` if any error-severity rule fails", which was never
/// true of the code and which no caller behaved as if it were.)
///
/// A caller that could not see its packs must not report compliant, so
/// `quality_gate::checks::check_compliance` turns this `Err` into the blocking
/// `FJQ-CMP-000` finding.
pub fn check_compliance_gate(
    policy_dir: &Path,
    config: &ForjarConfig,
    verbose: bool,
) -> Result<ComplianceGateResult, String> {
    let pack_names = list_packs(policy_dir)?;
    if pack_names.is_empty() {
        return Ok(ComplianceGateResult {
            packs_evaluated: 0,
            results: Vec::new(),
            error_count: 0,
            warning_count: 0,
        });
    }

    let resources = config_to_resource_map(config);
    let mut results = Vec::new();
    let mut total_errors = 0;
    let mut total_warnings = 0;

    for name in &pack_names {
        let path = policy_dir.join(format!("{name}.yaml"));
        let alt_path = policy_dir.join(format!("{name}.yml"));
        let pack_path = if path.exists() { &path } else { &alt_path };

        // A pack file that will not READ is the directory failure one level
        // down — `chmod 000 policies/cis.yaml` hides a pack exactly as
        // `chmod 000 policies/` hid all of them — so it is refused, not skipped.
        let text = std::fs::read_to_string(pack_path)
            .map_err(|e| format!("read pack `{name}` in {}: {e}", policy_dir.display()))?;

        // A file that reads fine and does not PARSE as a pack is a different
        // fact, and it is deliberately still skipped. `list_packs` guesses that
        // every `*.yaml` under the directory is a pack; that guess is forjar's,
        // not the operator's declaration, and blocking an apply because forjar
        // mis-guessed about a stray YAML punishes the wrong party. (It is not a
        // hypothetical: this module's own tests point `--policy-dir` at the
        // directory holding `forjar.yaml`.) The skip stays verbose-only, which
        // is a known gap of a different shape from #356 — a pack that is THERE
        // and unenforced — and is not fixed here.
        let pack = match parse_pack(&text) {
            Ok(p) => p,
            Err(e) => {
                if verbose {
                    eprintln!("  [WARN] skip {name}: not a compliance pack: {e}");
                }
                continue;
            }
        };

        let eval = evaluate_pack(&pack, &resources);
        let errors = count_severity_failures(&eval, "error");
        let warnings = count_severity_failures(&eval, "warning");

        if verbose {
            eprintln!(
                "  pack {}: {}/{} rules passed ({} error, {} warning)",
                pack.name,
                eval.passed_count(),
                eval.results.len(),
                errors,
                warnings
            );
        }

        total_errors += errors;
        total_warnings += warnings;
        results.push(eval);
    }

    Ok(ComplianceGateResult {
        packs_evaluated: results.len(),
        results,
        error_count: total_errors,
        warning_count: total_warnings,
    })
}

/// Count failures by severity in a pack evaluation.
///
/// Reads the severity off the RESULT. It used to be recovered by searching
/// `pack.rules` for a rule with a matching id, which answered "warning" for
/// any result whose rule id was not found — a pack whose ids drifted counted
/// zero errors and passed the gate.
fn count_severity_failures(eval: &PackEvalResult, severity: &str) -> usize {
    eval.results
        .iter()
        .filter(|r| !r.passed && r.severity == severity)
        .count()
}

/// Format compliance gate result for display.
pub fn format_gate_result(result: &ComplianceGateResult) -> String {
    let status = if result.passed() { "PASS" } else { "FAIL" };
    format!(
        "Compliance gate: {} ({} packs, {} errors, {} warnings)",
        status, result.packs_evaluated, result.error_count, result.warning_count
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::types::{ForjarConfig, Resource, ResourceType};

    fn make_config(resources: &[(&str, &str, Option<&str>)]) -> ForjarConfig {
        let mut config = ForjarConfig::default();
        for (name, rtype, owner) in resources {
            let resource = Resource {
                resource_type: match *rtype {
                    "file" => ResourceType::File,
                    "package" => ResourceType::Package,
                    "service" => ResourceType::Service,
                    _ => ResourceType::File,
                },
                owner: owner.map(|o| o.to_string()),
                ..Default::default()
            };
            config.resources.insert(name.to_string(), resource);
        }
        config
    }

    #[test]
    fn config_to_map_includes_fields() {
        let config = make_config(&[("nginx", "file", Some("root"))]);
        let map = config_to_resource_map(&config);
        assert_eq!(map.len(), 1);
        let nginx = map.get("nginx").unwrap();
        assert_eq!(nginx.get("type").unwrap(), "file");
        assert_eq!(nginx.get("owner").unwrap(), "root");
    }

    #[test]
    fn config_to_map_optional_fields() {
        let config = make_config(&[("pkg", "package", None)]);
        let map = config_to_resource_map(&config);
        let pkg = map.get("pkg").unwrap();
        assert_eq!(pkg.get("type").unwrap(), "package");
        assert!(pkg.get("owner").is_none());
    }

    #[test]
    fn gate_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let config = make_config(&[("f1", "file", None)]);
        let result = check_compliance_gate(dir.path(), &config, false).unwrap();
        assert!(result.passed());
        assert_eq!(result.packs_evaluated, 0);
    }

    #[test]
    fn gate_with_passing_pack() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("test.yaml"),
            r#"
name: test-gate
version: "1.0"
framework: TEST
rules:
  - id: T1
    title: Files have owner
    type: require
    resource_type: file
    field: owner
"#,
        )
        .unwrap();

        let config = make_config(&[("f1", "file", Some("root"))]);
        let result = check_compliance_gate(dir.path(), &config, false).unwrap();
        assert!(result.passed());
    }

    #[test]
    fn gate_with_failing_pack() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("strict.yaml"),
            r#"
name: strict
version: "1.0"
framework: TEST
rules:
  - id: S1
    title: Must have owner
    severity: error
    type: require
    resource_type: file
    field: owner
"#,
        )
        .unwrap();

        let config = make_config(&[("f1", "file", None)]);
        let result = check_compliance_gate(dir.path(), &config, false).unwrap();
        assert_eq!(result.error_count, 1);
        assert!(!result.passed());
    }

    /// B2: the gate must not report compliant over packs it could not see.
    ///
    /// The pack in the locked directory is error-severity and WOULD block; the
    /// same directory readable is asserted alongside so the fixture is proved
    /// to have teeth rather than merely producing nothing.
    #[test]
    #[cfg(unix)]
    fn an_unreadable_policy_dir_does_not_pass_the_gate() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let policies = dir.path().join("policies");
        std::fs::create_dir(&policies).unwrap();
        std::fs::write(
            policies.join("strict.yaml"),
            "name: strict\nversion: \"1.0\"\nframework: TEST\nrules:\n  - id: S1\n    \
             title: Must have owner\n    severity: error\n    type: require\n    \
             resource_type: file\n    field: owner\n",
        )
        .unwrap();
        let config = make_config(&[("f1", "file", None)]);

        // Readable: the pack blocks. If this ever stops holding, the assertion
        // below is passing for the wrong reason.
        let open = check_compliance_gate(&policies, &config, false).unwrap();
        assert_eq!(open.error_count, 1, "the fixture pack must block when seen");

        std::fs::set_permissions(&policies, std::fs::Permissions::from_mode(0o000)).unwrap();
        let blind = check_compliance_gate(&policies, &config, false);
        let restore = std::fs::set_permissions(&policies, std::fs::Permissions::from_mode(0o755));

        if blind.as_ref().is_ok_and(|r| r.error_count == 1) {
            restore.unwrap(); // running as root: the mode did not blind anything
            return;
        }
        assert!(
            blind.is_err(),
            "an unreadable policy directory answered {blind:?} — every pack inside it \
             vanished and the gate reported compliant"
        );
        restore.unwrap();
    }

    /// A pack file that is present and unreadable hides one pack the same way.
    #[test]
    #[cfg(unix)]
    fn an_unreadable_pack_file_does_not_pass_the_gate() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let pack = dir.path().join("strict.yaml");
        std::fs::write(
            &pack,
            "name: strict\nversion: \"1.0\"\nframework: TEST\nrules:\n  - id: S1\n    \
             title: Must have owner\n    severity: error\n    type: require\n    \
             resource_type: file\n    field: owner\n",
        )
        .unwrap();
        std::fs::set_permissions(&pack, std::fs::Permissions::from_mode(0o000)).unwrap();

        let blind = check_compliance_gate(dir.path(), &make_config(&[("f1", "file", None)]), false);
        let restore = std::fs::set_permissions(&pack, std::fs::Permissions::from_mode(0o644));

        if blind.as_ref().is_ok_and(|r| r.error_count == 1) {
            restore.unwrap(); // running as root
            return;
        }
        assert!(blind.is_err(), "an unreadable pack file read as compliant");
        restore.unwrap();
    }

    /// The counterweight: a YAML that reads fine and is not a pack is forjar's
    /// own `*.yaml` guess being wrong, so it is skipped and does NOT block.
    /// Without this, the two assertions above would be satisfied by a gate that
    /// simply refuses everything.
    #[test]
    fn a_readable_non_pack_yaml_is_skipped_not_blocking() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("forjar.yaml"),
            "version: \"1.0\"\nname: not-a-pack\nresources: {}\n",
        )
        .unwrap();
        let result =
            check_compliance_gate(dir.path(), &make_config(&[("f1", "file", None)]), false)
                .expect("a stray YAML is forjar's mis-guess, not blindness — it must not error");
        assert!(result.passed());
        assert_eq!(result.packs_evaluated, 0);
    }

    #[test]
    fn gate_result_format() {
        let result = ComplianceGateResult {
            packs_evaluated: 2,
            results: vec![],
            error_count: 0,
            warning_count: 1,
        };
        let text = format_gate_result(&result);
        assert!(text.contains("PASS"));
        assert!(text.contains("2 packs"));
    }

    #[test]
    fn gate_result_format_fail() {
        let result = ComplianceGateResult {
            packs_evaluated: 1,
            results: vec![],
            error_count: 2,
            warning_count: 0,
        };
        let text = format_gate_result(&result);
        assert!(text.contains("FAIL"));
        assert!(text.contains("2 errors"));
    }

    #[test]
    fn config_with_tags() {
        let mut config = ForjarConfig::default();
        let resource = Resource {
            resource_type: ResourceType::File,
            tags: vec!["web".into(), "config".into()],
            ..Default::default()
        };
        config.resources.insert("nginx".into(), resource);

        let map = config_to_resource_map(&config);
        let nginx = map.get("nginx").unwrap();
        assert_eq!(nginx.get("tags").unwrap(), "web,config");
    }

    #[test]
    fn config_with_mode() {
        let mut config = ForjarConfig::default();
        let resource = Resource {
            resource_type: ResourceType::File,
            mode: Some("0644".into()),
            ..Default::default()
        };
        config.resources.insert("f1".into(), resource);

        let map = config_to_resource_map(&config);
        assert_eq!(map.get("f1").unwrap().get("mode").unwrap(), "0644");
    }
}