forjar 1.29.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
//! Destroy, rollback, and undo.

use super::apply::*;
use super::helpers::*;
use crate::core::{codegen, executor, resolver, types};
use crate::transport;
use std::path::Path;

/// Destroy a single resource on its machine. Returns true on success.
fn destroy_single_resource(
    resource_id: &str,
    resource: &types::Resource,
    machine: &types::Machine,
) -> bool {
    let mut destroy_resource = resource.clone();
    destroy_resource.state = Some("absent".to_string());

    let script = match codegen::apply_script(&destroy_resource) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("  SKIP {resource_id}: codegen error: {e}");
            return false;
        }
    };

    if machine.is_container_transport() {
        let _ = crate::transport::container::ensure_container(machine);
    }

    match transport::exec_script(machine, &script) {
        Ok(out) if out.success() => {
            println!("  - {} ({})", resource_id, resource.resource_type);
            true
        }
        Ok(out) => {
            eprintln!(
                "  FAIL {}: exit {}: {}",
                resource_id,
                out.exit_code,
                out.stderr.trim()
            );
            false
        }
        Err(e) => {
            eprintln!("  FAIL {resource_id}: {e}");
            false
        }
    }
}

/// Clean up state lock files for the given machines.
fn cleanup_state_files(state_dir: &Path, machines: &[String], machine_filter: Option<&str>) {
    for machine_name in machines {
        if let Some(filter) = machine_filter {
            if machine_name != filter {
                continue;
            }
        }
        let lock_path = state_dir.join(machine_name).join("state.lock.yaml");
        if lock_path.exists() {
            let _ = std::fs::remove_file(&lock_path);
        }
        // forjar#449 (found by its falsifier): the BLAKE3 sidecar outlived the
        // lock, and the next `apply` refused — "lock file is missing but its
        // sidecar survives". A destroyed machine has no lock and no seal.
        let sidecar = state_dir.join(machine_name).join("state.lock.yaml.b3");
        if sidecar.exists() {
            let _ = std::fs::remove_file(&sidecar);
        }
    }
}

/// FJ-2005: Remove only succeeded resource entries from lock files on partial failure.
pub(crate) fn cleanup_succeeded_entries(
    state_dir: &Path,
    succeeded: &std::collections::HashMap<String, Vec<String>>,
) {
    for (machine_name, resource_ids) in succeeded {
        let lock_path = state_dir.join(machine_name).join("state.lock.yaml");
        let Ok(content) = std::fs::read_to_string(&lock_path) else {
            continue;
        };
        let Ok(mut lock) = serde_yaml_ng::from_str::<crate::core::types::StateLock>(&content)
        else {
            continue;
        };
        for rid in resource_ids {
            lock.resources.shift_remove(rid);
        }
        if lock.resources.is_empty() {
            let _ = std::fs::remove_file(&lock_path);
            let _ = std::fs::remove_file(state_dir.join(machine_name).join("state.lock.yaml.b3"));
        } else if let Ok(yaml) = serde_yaml_ng::to_string(&lock) {
            let _ = std::fs::write(&lock_path, yaml);
            // forjar#449: a rewritten lock needs a fresh seal, or the next
            // apply's integrity check refuses it as tampered.
            let _ = crate::core::state::integrity::write_b3_sidecar(&lock_path);
        }
    }
}

/// FJ-2005: Write a destroy log entry with pre-state for undo-destroy recovery.
pub(crate) fn write_destroy_log_entry(
    log_path: &Path,
    resource_id: &str,
    resource: &types::Resource,
    machine_name: &str,
    locks: &std::collections::HashMap<String, types::StateLock>,
) {
    let pre_hash = locks
        .get(machine_name)
        .and_then(|l| l.resources.get(resource_id))
        .map(|rl| rl.hash.clone())
        .unwrap_or_default();

    let entry = types::DestroyLogEntry {
        timestamp: crate::tripwire::eventlog::now_iso8601(),
        machine: machine_name.to_string(),
        resource_id: resource_id.to_string(),
        resource_type: resource.resource_type.to_string(),
        pre_hash,
        generation: 0, // filled by caller if known
        config_fragment: serde_yaml_ng::to_string(resource).ok(),
        reliable_recreate: resource.content.is_some(),
    };
    if let Ok(line) = entry.to_jsonl() {
        use std::io::Write;
        if let Ok(mut f) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(log_path)
        {
            let _ = writeln!(f, "{line}");
        }
    }
}

/// Decides which machine a resource is destroyed on, and whether `-m` selects it
/// at all. A `Multiple` target is destroyed on its first machine; `None` means
/// skip this resource entirely — either it names no machine, or the machine
/// filter excludes it. Lifted out of the destroy loop so the loop body reads as
/// "pick a machine, then destroy on it".
fn destroy_target_machine<'a>(
    resource: &'a types::Resource,
    machine_filter: Option<&str>,
) -> Option<&'a str> {
    let machine_name = match &resource.machine {
        types::MachineTarget::Single(m) => m.as_str(),
        types::MachineTarget::Multiple(ms) => ms.first()?.as_str(),
    };

    if let Some(filter) = machine_filter {
        if machine_name != filter {
            return None;
        }
    }

    Some(machine_name)
}

pub(crate) fn cmd_destroy(
    file: &Path,
    state_dir: &Path,
    machine_filter: Option<&str>,
    yes: bool,
    verbose: bool,
) -> Result<(), String> {
    if !yes {
        return Err(
            "destroy requires --yes flag to confirm removal of all managed resources".to_string(),
        );
    }

    let config = parse_and_validate(file)?;
    // `build_execution_order` on the RAW config is sound: `depends_on` is
    // deliberately never templated (see resolver::tests_completeness).
    let execution_order = resolver::build_execution_order(&config)?;
    let reverse_order: Vec<String> = execution_order.into_iter().rev().collect();

    // FJ-2722 (PMAT-199): destroy MUST operate on resolved resources.
    //
    // It previously took resources straight from `config.resources` and handed
    // them to `codegen::apply_script` with `state: absent`. For a file resource
    // that generates `rm -rf '{{params.x}}/...'` — a destructive command against
    // a literal path, reported as a success, while the real resource survives
    // and its lock entry is removed. This is the third code path to make the
    // same mistake (drift in v1.11.0, the staleness probe in v1.11.1), which is
    // why `resolve_all` exists as the single entry point.
    let resolved = resolver::resolve_all(
        &config.resources,
        &config.params,
        &config.machines,
        &config.secrets,
    );

    if verbose {
        eprintln!(
            "Destroying {} resources in reverse order",
            reverse_order.len()
        );
    }

    let all_machines = executor::collect_machines(&config);
    // FJ-2005: Load locks to capture pre-hash for destroy log
    let locks = super::helpers_state::load_machine_locks(&config, state_dir, machine_filter)
        .unwrap_or_default();
    let destroy_log_path = state_dir.join("destroy-log.jsonl");
    let mut destroyed = 0u32;
    let mut failed = 0u32;
    let mut succeeded_resources: std::collections::HashMap<String, Vec<String>> =
        std::collections::HashMap::new();

    for resource_id in &reverse_order {
        let resource = match resolved.get(resource_id) {
            Some(r) => r,
            None => continue,
        };

        let Some(machine_name) = destroy_target_machine(resource, machine_filter) else {
            continue;
        };

        let machine = match config.machines.get(machine_name) {
            Some(m) => m,
            None => {
                eprintln!("  SKIP {resource_id}: machine '{machine_name}' not found");
                failed += 1;
                continue;
            }
        };

        if destroy_single_resource(resource_id, resource, machine) {
            destroyed += 1;
            succeeded_resources
                .entry(machine_name.to_string())
                .or_default()
                .push(resource_id.clone());
            // FJ-2005: Write pre-state to destroy-log.jsonl
            write_destroy_log_entry(
                &destroy_log_path,
                resource_id,
                resource,
                machine_name,
                &locks,
            );
        } else {
            failed += 1;
        }
    }

    if failed == 0 {
        // All succeeded — remove entire lock files
        cleanup_state_files(state_dir, &all_machines, machine_filter);
    } else {
        // FJ-2005: Partial failure — only remove lock entries for succeeded resources
        cleanup_succeeded_entries(state_dir, &succeeded_resources);
    }

    // forjar#449: record the generation this destroy produced, exactly as
    // apply does (GH-376: failures included — a generation is a record of what
    // happened). Without it `undo` had nothing earlier than "current" to
    // rewind to, and the destroy/undo roundtrip the contract
    // destroy-undo-roundtrip-v1 names could not happen.
    //
    // A generation pairs a state with the config that PRODUCED it, and `undo`
    // re-converges a generation by re-applying that config. The config that
    // produced a destroyed state is one that no longer declares what was
    // destroyed — recording the file's config unchanged would pair empty locks
    // with resources still declared, and a later `undo` landing here would
    // re-create everything the destroy removed (the quorum review's poisoned
    // rollback). So the recorded config drops exactly the resources this run
    // destroyed; a resource that failed to destroy, or was outside -m, stays.
    let mut produced = config.clone();
    for ids in succeeded_resources.values() {
        for id in ids {
            produced.resources.shift_remove(id);
        }
    }
    super::apply_snapshot::maybe_record_generation(&produced, state_dir, false, verbose);

    println!();
    if failed > 0 {
        println!("Destroy completed with errors: {destroyed} destroyed, {failed} failed");
        return Err(format!("{failed} resource(s) failed to destroy"));
    }

    println!("Destroy complete: {destroyed} resources removed.");
    Ok(())
}

/// Rollback to a previous config revision from git history.
pub(crate) fn cmd_rollback(
    file: &Path,
    state_dir: &Path,
    revision: u32,
    machine_filter: Option<&str>,
    dry_run: bool,
    verbose: bool,
) -> Result<(), String> {
    let file_str = file.to_string_lossy();
    let git_ref = format!("HEAD~{revision}:{file_str}");
    let output = crate::core::gitenv::git()
        .args(["show", &git_ref])
        .output()
        .map_err(|e| format!("git show failed: {e}"))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!(
            "cannot read {} from git history (HEAD~{}): {}",
            file_str,
            revision,
            stderr.trim()
        ));
    }

    let previous_yaml = String::from_utf8_lossy(&output.stdout);
    let previous_config: types::ForjarConfig = serde_yaml_ng::from_str(&previous_yaml)
        .map_err(|e| format!("cannot parse previous config (HEAD~{revision}): {e}"))?;
    let current_config = parse_and_validate(file)?;

    let changes = compute_rollback_changes(&previous_config, &current_config, revision);

    if changes.is_empty() {
        println!("No config changes between HEAD and HEAD~{revision}. Nothing to rollback.");
        return Ok(());
    }

    println!("Rollback to HEAD~{} ({}):", revision, previous_config.name);
    for c in &changes {
        println!("{c}");
    }
    println!();

    if dry_run {
        println!("Dry run: {} change(s) would be applied.", changes.len());
        return Ok(());
    }

    let temp_config = std::env::temp_dir().join("forjar-rollback.yaml");
    std::fs::write(&temp_config, previous_yaml.as_bytes())
        .map_err(|e| format!("cannot write temp config: {e}"))?;

    println!("Applying previous config with --force...");
    cmd_apply(
        &temp_config,
        state_dir,
        machine_filter,
        None,
        None,
        None,
        true,
        false,
        false,
        &[],
        false,
        None,
        false,
        verbose,
        None,
        None,
        false,
        false,
        None,
        false,
        false,
        0,
        true,
        false,
        None,
        false,
        None,
        None,
        None,
        false,
        None,
        false,
        None,  // telemetry_endpoint
        false, // refresh
        None,  // force_tag
        &[],
    )
}

/// Compare previous and current configs to find rollback changes.
pub(crate) fn compute_rollback_changes(
    previous: &types::ForjarConfig,
    current: &types::ForjarConfig,
    revision: u32,
) -> Vec<String> {
    let mut changes = Vec::new();
    for (id, prev_resource) in &previous.resources {
        if let Some(cur_resource) = current.resources.get(id) {
            let prev_yaml = serde_yaml_ng::to_string(prev_resource).unwrap_or_default();
            let cur_yaml = serde_yaml_ng::to_string(cur_resource).unwrap_or_default();
            if prev_yaml != cur_yaml {
                changes.push(format!("  ~ {id} (modified)"));
            }
        } else {
            changes.push(format!("  + {id} (will be re-added from HEAD~{revision})"));
        }
    }
    for id in current.resources.keys() {
        if !previous.resources.contains_key(id) {
            changes.push(format!(
                "  - {id} (exists now but not in HEAD~{revision}, will remain)"
            ));
        }
    }
    changes
}