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
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
//! Lock management.

use super::apply_helpers::*;
use super::helpers::*;
use super::workspace::*;
use crate::core::{resolver, state, types};
use std::path::Path;

/// Compare a newly generated lock against an existing lock, collecting mismatches.
pub(super) fn collect_verify_mismatches(
    machine_name: &str,
    lock: &types::StateLock,
    existing_lock: &types::StateLock,
    mismatches: &mut Vec<String>,
) {
    for (res_id, new_res_lock) in &lock.resources {
        match existing_lock.resources.get(res_id) {
            None => {
                mismatches.push(format!("{machine_name}:{res_id}: not in lock file"));
            }
            Some(existing_res) => {
                if existing_res.hash != new_res_lock.hash {
                    mismatches.push(format!(
                        "{}:{}: hash mismatch (lock={}, config={})",
                        machine_name,
                        res_id,
                        &existing_res.hash[..15.min(existing_res.hash.len())],
                        &new_res_lock.hash[..15.min(new_res_lock.hash.len())],
                    ));
                }
            }
        }
    }
    // Check for resources in lock that are no longer in config
    for res_id in existing_lock.resources.keys() {
        if !lock.resources.contains_key(res_id) {
            mismatches.push(format!(
                "{machine_name}:{res_id}: in lock but not in config"
            ));
        }
    }
}

/// Group resources by the machine(s) they target, in execution order.
///
/// A `Multiple` target lands the same resource under every machine it names.
fn group_resources_by_machine<'a>(
    config: &'a types::ForjarConfig,
    execution_order: &[String],
) -> indexmap::IndexMap<String, Vec<(String, &'a types::Resource)>> {
    let mut machine_resources: indexmap::IndexMap<String, Vec<(String, &types::Resource)>> =
        indexmap::IndexMap::new();
    for res_id in execution_order {
        if let Some(resource) = config.resources.get(res_id) {
            let machines = match &resource.machine {
                types::MachineTarget::Single(m) => vec![m.clone()],
                types::MachineTarget::Multiple(ms) => ms.clone(),
            };
            for m in machines {
                machine_resources
                    .entry(m)
                    .or_default()
                    .push((res_id.clone(), resource));
            }
        }
    }
    machine_resources
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn cmd_lock(
    file: &Path,
    state_dir: &Path,
    env_file: Option<&Path>,
    workspace: Option<&str>,
    verify: bool,
    dry_run: bool,
    json: bool,
) -> Result<(), String> {
    use crate::core::planner::hash_desired_state;

    let mut config = parse_and_validate(file)?;
    if let Some(path) = env_file {
        load_env_params(&mut config, path)?;
    }
    inject_workspace_param(&mut config, workspace);
    resolver::resolve_data_sources(&mut config)?;

    // FJ-2733: write apply's hash universe. `executor::record_success` hashes
    // the RESOLVED resource; hashing the raw one here made `lock --verify`,
    // `lock-diff` and `lock-integrity` compare unlike with unlike. Pinned by
    // cli::tests_prove_resolved::lock_and_apply_hash_the_same_resource_identically.
    config.resources = resolver::resolve_all(
        &config.resources,
        &config.params,
        &config.machines,
        &config.secrets,
    );

    let execution_order = resolver::build_execution_order(&config)?;

    let machine_resources = group_resources_by_machine(&config, &execution_order);

    let mut mismatches: Vec<String> = Vec::new();
    let mut total_resources = 0usize;
    let mut total_machines = 0usize;

    for (machine_name, resources) in &machine_resources {
        let hostname = config
            .machines
            .get(machine_name)
            .map(|m| m.hostname.as_str())
            .unwrap_or(machine_name);

        let mut lock = state::new_lock(machine_name, hostname);

        for (res_id, resource) in resources {
            let hash = hash_desired_state(resource);
            lock.resources.insert(
                res_id.clone(),
                types::ResourceLock {
                    resource_type: resource.resource_type.clone(),
                    status: types::ResourceStatus::Unknown,
                    applied_at: None,
                    duration_seconds: None,
                    hash: hash.clone(),
                    observed: None,
                    details: std::collections::HashMap::new(),
                },
            );
            total_resources += 1;
        }

        if verify {
            let existing = state::load_lock(state_dir, machine_name)?;
            match existing {
                None => {
                    mismatches.push(format!("{machine_name}: no existing lock file"));
                }
                Some(existing_lock) => {
                    collect_verify_mismatches(machine_name, &lock, &existing_lock, &mut mismatches);
                }
            }
        } else if !dry_run {
            state::save_lock(state_dir, &lock)?;
        }

        total_machines += 1;
    }

    if verify {
        super::lock_output::output_verify_results(
            &mismatches,
            total_machines,
            total_resources,
            json,
        )?;
    } else if dry_run {
        super::lock_output::output_dry_run_results(total_machines, total_resources, json)?;
    } else {
        super::lock_output::output_lock_results(
            state_dir,
            &config.name,
            &machine_resources,
            total_machines,
            total_resources,
            json,
        )?;
    }

    Ok(())
}

// FJ-384: Lock file metadata
pub(crate) fn cmd_lock_info(state_dir: &Path, json: bool) -> Result<(), String> {
    let entries =
        std::fs::read_dir(state_dir).map_err(|e| format!("cannot read state dir: {e}"))?;

    let mut machines = Vec::new();
    let mut total_resources = 0usize;

    for entry in entries.flatten() {
        if !entry.path().is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        if let Some(lock) = state::load_lock(state_dir, &name)? {
            total_resources += lock.resources.len();
            machines.push(serde_json::json!({
                "machine": lock.machine,
                "hostname": lock.hostname,
                "schema": lock.schema,
                "generator": lock.generator,
                "generated_at": lock.generated_at,
                "resources": lock.resources.len(),
            }));
        }
    }

    if json {
        let result = serde_json::json!({
            "machines": machines,
            "total_resources": total_resources,
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&result).unwrap_or_else(|_| "{}".to_string())
        );
    } else {
        println!("Lock Info:\n");
        println!("  Total machines: {}", machines.len());
        println!("  Total resources: {total_resources}");
        for m in &machines {
            println!(
                "\n  {} ({}): {} resources, schema {}, generated {}",
                bold(m["machine"].as_str().unwrap_or("?")),
                m["hostname"].as_str().unwrap_or("?"),
                m["resources"],
                m["schema"].as_str().unwrap_or("?"),
                m["generated_at"].as_str().unwrap_or("?"),
            );
        }
    }

    Ok(())
}

/// Lock entries that no longer name a resource in the config.
fn stale_lock_entries(
    lock: &types::StateLock,
    config_resources: &std::collections::HashSet<&String>,
) -> Vec<String> {
    lock.resources
        .keys()
        .filter(|k| !config_resources.contains(k))
        .cloned()
        .collect()
}

/// Drops the stale entries from the lock, naming each one as it goes.
///
/// ACTUALLY REMOVE IT.
///
/// This used to be the `println!` alone. `stale` was computed, printed and
/// counted; the lock was never mutated and never saved. So `lock-prune --yes`
/// announced "Pruned 'b' from local", exited 0, and left the lock file
/// BYTE-IDENTICAL — the message was the only thing that happened. Ledger id
/// lock-prune-yes-claims-pruned-but-changes-nothing, confirmed at 1.12.3 and
/// still live at 1.16.0.
fn remove_stale_entries(lock: &mut types::StateLock, stale: &[String], machine_name: &str) {
    for s in stale {
        lock.resources.shift_remove(s);
        println!("  {} Pruned '{}' from {}", red("-"), s, machine_name);
    }
}

/// Names the stale entries a `--yes` run would drop, touching nothing.
fn preview_stale_entries(stale: &[String], machine_name: &str) {
    for s in stale {
        println!(
            "  {} Would prune '{}' from {} (use --yes to apply)",
            yellow("~"),
            s,
            machine_name
        );
    }
}

/// Prunes one machine's lock, returning how many stale entries it held.
/// Without `--yes` this only previews. With it, the lock is saved, and a failed
/// write is an error: saving also rewrites the `.b3` sidecar, so a pruned lock
/// must never be reported as pruned unless it reached disk.
fn prune_machine_lock(
    state_dir: &Path,
    machine_name: &str,
    lock: &mut types::StateLock,
    config_resources: &std::collections::HashSet<&String>,
    yes: bool,
) -> Result<usize, String> {
    let stale = stale_lock_entries(lock, config_resources);
    if stale.is_empty() {
        return Ok(0);
    }

    if yes {
        remove_stale_entries(lock, &stale, machine_name);
        state::save_lock(state_dir, lock).map_err(|e| {
            format!(
                "pruned {} entr(ies) from {machine_name} but could not save the lock: {e}",
                stale.len()
            )
        })?;
    } else {
        preview_stale_entries(&stale, machine_name);
    }

    Ok(stale.len())
}

/// Closing line for a prune run: nothing found, a preview total, or a count of
/// what was removed.
fn print_prune_summary(pruned: usize, yes: bool) {
    if pruned == 0 {
        println!("{} No stale lock entries found.", green(""));
    } else if !yes {
        println!(
            "\n{} {} stale entries. Run with --yes to prune.",
            yellow("Total:"),
            pruned
        );
    } else {
        println!("\n{} Pruned {} stale entries.", green(""), pruned);
    }
}

// FJ-366: Lock prune — remove stale lock entries
pub(crate) fn cmd_lock_prune(file: &Path, state_dir: &Path, yes: bool) -> Result<(), String> {
    let config = parse_and_validate(file)?;
    let config_resources: std::collections::HashSet<&String> = config.resources.keys().collect();

    let entries =
        std::fs::read_dir(state_dir).map_err(|e| format!("cannot read state dir: {e}"))?;

    let mut pruned = 0usize;
    for entry in entries.flatten() {
        if !entry.path().is_dir() {
            continue;
        }
        let machine_name = entry.file_name().to_string_lossy().to_string();
        if let Some(mut lock) = state::load_lock(state_dir, &machine_name)? {
            pruned +=
                prune_machine_lock(state_dir, &machine_name, &mut lock, &config_resources, yes)?;
        }
    }

    print_prune_summary(pruned, yes);
    Ok(())
}

/// FJ-596: Validate lock file integrity (schema, hash consistency).
/// Validate a single lock file, returning issues found.
pub(super) fn validate_single_lock(
    m: &str,
    lock: &crate::core::types::StateLock,
) -> Vec<(String, String)> {
    let mut issues = Vec::new();
    if lock.schema != "1" && lock.schema != "1.0" {
        issues.push((
            m.to_string(),
            format!("unexpected schema version: {}", lock.schema),
        ));
    }
    for (rname, rlock) in &lock.resources {
        if rlock.hash.is_empty() {
            issues.push((m.to_string(), format!("empty hash for resource: {rname}")));
        }
    }
    issues
}

/// Tally (valid, invalid) machines from an issue list: a machine is valid only when
/// nothing at all was reported against it. Counting issues instead of machines
/// double-counts a lock that fails two independent checks.
fn tally_machines(machines: &[String], issues: &[(String, String)]) -> (u64, u64) {
    let flagged: std::collections::BTreeSet<&str> =
        issues.iter().map(|(m, _)| m.as_str()).collect();
    let valid = machines
        .iter()
        .filter(|m| !flagged.contains(m.as_str()))
        .count() as u64;
    (valid, flagged.len() as u64)
}

pub(crate) fn cmd_lock_validate(state_dir: &Path, json: bool) -> Result<(), String> {
    require_state_dir(state_dir)?;
    let machines = discover_machines(state_dir);

    // CB-2010: a lock is only "valid" if its body still hashes to the BLAKE3
    // sidecar `save_lock` wrote beside it. Structural validation alone passes a
    // tampered body, a deleted sidecar and a deleted lock file.
    let mut issues: Vec<(String, String)> = sidecar_failures(state_dir);

    for m in &machines {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        if !lock_path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&lock_path).unwrap_or_default();
        match serde_yaml_ng::from_str::<crate::core::types::StateLock>(&content) {
            Ok(lock) => issues.extend(validate_single_lock(m, &lock)),
            Err(e) => issues.push((m.clone(), format!("parse error: {e}"))),
        }
    }

    let (valid, invalid) = tally_machines(&machines, &issues);

    if json {
        let items: Vec<String> = issues
            .iter()
            .map(|(m, msg)| {
                format!(
                    r#"{{"machine":"{}","issue":"{}"}}"#,
                    m,
                    msg.replace('"', "\\\"")
                )
            })
            .collect();
        println!(
            r#"{{"valid":{},"invalid":{},"issues":[{}]}}"#,
            valid,
            invalid,
            items.join(",")
        );
    } else if issues.is_empty() {
        println!("All {valid} lock files are valid");
    } else {
        println!("Lock validation: {valid} valid, {invalid} invalid");
        for (m, msg) in &issues {
            println!("  {m}{msg}");
        }
    }
    if issues.is_empty() {
        Ok(())
    } else {
        Err(format!("{} lock validation issue(s)", issues.len()))
    }
}

/// FJ-675: Check lock file structural integrity
pub(crate) fn cmd_lock_integrity(state_dir: &Path, json: bool) -> Result<(), String> {
    let machines = discover_machines(state_dir);

    // CB-2010: the command is literally named `lock-integrity` and never measured
    // any. It read the schema string and nothing else — never the `.b3` sidecar
    // sitting next to the lock — so it printed "All N lock files pass integrity
    // check" for a rewritten body and for a deleted sidecar alike.
    let mut issues: Vec<(String, String)> = sidecar_failures(state_dir);

    for m in &machines {
        let lock_path = state_dir.join(m).join("state.lock.yaml");
        if !lock_path.exists() {
            continue;
        }
        let content = std::fs::read_to_string(&lock_path).unwrap_or_default();
        match serde_yaml_ng::from_str::<crate::core::types::StateLock>(&content) {
            Ok(lock) => {
                if lock.schema != "1" && lock.schema != "1.0" {
                    issues.push((
                        m.clone(),
                        format!("unexpected schema version '{}'", lock.schema),
                    ));
                }
            }
            Err(e) => issues.push((m.clone(), format!("parse error — {e}"))),
        }
    }

    let (valid, invalid) = tally_machines(&machines, &issues);

    if json {
        println!(
            r#"{{"valid":{},"invalid":{},"issues_count":{}}}"#,
            valid,
            invalid,
            issues.len()
        );
    } else if issues.is_empty() {
        println!("All {valid} lock files pass integrity check");
    } else {
        println!("Integrity check: {valid} valid, {invalid} invalid");
        for (m, issue) in &issues {
            println!("  - {m}: {issue}");
        }
    }
    if issues.is_empty() {
        Ok(())
    } else {
        Err(format!("{} lock integrity issue(s)", issues.len()))
    }
}