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
432
//! FJ-013: Lock file management — load, save (atomic), path derivation.

pub mod ephemeral;
pub mod integrity;
pub mod reconstruct;
pub mod rulebook_log;

use super::types::{ApplyResult, GlobalLock, MachineSummary, StateLock};
use provable_contracts_macros::contract;
use std::path::{Path, PathBuf};

/// Derive the lock file path for a machine within the state directory.
pub fn lock_file_path(state_dir: &Path, machine: &str) -> PathBuf {
    state_dir.join(machine).join("state.lock.yaml")
}

/// Load a lock file for a machine. Returns None if the file doesn't exist.
pub fn load_lock(state_dir: &Path, machine: &str) -> Result<Option<StateLock>, String> {
    let path = lock_file_path(state_dir, machine);
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("cannot read {}: {}", path.display(), e))?;
    let lock: StateLock = serde_yaml_ng::from_str(&content)
        .map_err(|e| format!("invalid lock file {}: {}", path.display(), e))?;
    Ok(Some(lock))
}

/// Save a lock file atomically (write to temp, then rename).
#[contract("execution-safety-v1", equation = "atomic_write")]
pub fn save_lock(state_dir: &Path, lock: &StateLock) -> Result<(), String> {
    // Contract: execution-safety-v1.yaml precondition (pv codegen)
    contract_pre_atomic_write!(state_dir);
    let path = lock_file_path(state_dir, &lock.machine);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("cannot create dir {}: {}", parent.display(), e))?;
    }

    let yaml = serde_yaml_ng::to_string(lock).map_err(|e| format!("serialize error: {e}"))?;

    // Write to temp file, then rename for crash-safe persistence
    let tmp_path = path.with_extension("lock.yaml.tmp");
    std::fs::write(&tmp_path, &yaml)
        .map_err(|e| format!("cannot write {}: {}", tmp_path.display(), e))?;
    std::fs::rename(&tmp_path, &path).map_err(|e| {
        format!(
            "cannot rename {}{}: {}",
            tmp_path.display(),
            path.display(),
            e
        )
    })?;

    // FJ-1270: Write BLAKE3 integrity sidecar.
    // FJ-118 (2026-04-24 fix): was `let _ = …` which silently discarded
    // sidecar-write errors, leaving `state.lock.yaml` updated on disk
    // but `.b3` stale or missing — guaranteeing a hard-fail on the
    // NEXT apply with "integrity check failed, expected X, got Y" and
    // no signal at the moment of corruption. Propagating the error
    // means sidecar-write failures now fail the apply at the source.
    integrity::write_b3_sidecar(&path).map_err(|e| {
        format!(
            "sidecar write failed for {}: {} (lock.yaml was saved; \
             recover with `forjar reseal --file {}` or re-run apply)",
            path.display(),
            e,
            path.display(),
        )
    })?;

    // FJ-2200: Atomicity postcondition — file exists and temp is gone
    debug_assert!(path.exists(), "save_lock: file does not exist after write");
    debug_assert!(
        !tmp_path.exists(),
        "save_lock: temp file still exists after rename"
    );

    Ok(())
}

/// Path to the global lock file.
pub fn global_lock_path(state_dir: &Path) -> PathBuf {
    state_dir.join("forjar.lock.yaml")
}

/// Load the global lock file. Returns None if it doesn't exist.
pub fn load_global_lock(state_dir: &Path) -> Result<Option<GlobalLock>, String> {
    let path = global_lock_path(state_dir);
    if !path.exists() {
        return Ok(None);
    }
    let content = std::fs::read_to_string(&path)
        .map_err(|e| format!("cannot read {}: {}", path.display(), e))?;
    let lock: GlobalLock = serde_yaml_ng::from_str(&content)
        .map_err(|e| format!("invalid global lock {}: {}", path.display(), e))?;
    Ok(Some(lock))
}

/// Save the global lock file atomically.
pub fn save_global_lock(state_dir: &Path, lock: &GlobalLock) -> Result<(), String> {
    std::fs::create_dir_all(state_dir)
        .map_err(|e| format!("cannot create dir {}: {}", state_dir.display(), e))?;

    let path = global_lock_path(state_dir);
    let yaml = serde_yaml_ng::to_string(lock).map_err(|e| format!("serialize error: {e}"))?;

    let tmp_path = path.with_extension("lock.yaml.tmp");
    std::fs::write(&tmp_path, &yaml)
        .map_err(|e| format!("cannot write {}: {}", tmp_path.display(), e))?;
    std::fs::rename(&tmp_path, &path).map_err(|e| {
        format!(
            "cannot rename {}{}: {}",
            tmp_path.display(),
            path.display(),
            e
        )
    })?;

    // FJ-1270: Write BLAKE3 integrity sidecar.
    // FJ-118 (2026-04-24 fix): was `let _ = …` which silently discarded
    // sidecar-write errors, leaving `state.lock.yaml` updated on disk
    // but `.b3` stale or missing — guaranteeing a hard-fail on the
    // NEXT apply with "integrity check failed, expected X, got Y" and
    // no signal at the moment of corruption. Propagating the error
    // means sidecar-write failures now fail the apply at the source.
    integrity::write_b3_sidecar(&path).map_err(|e| {
        format!(
            "sidecar write failed for {}: {} (lock.yaml was saved; \
             recover with `forjar reseal --file {}` or re-run apply)",
            path.display(),
            e,
            path.display(),
        )
    })?;

    Ok(())
}

/// Create a new GlobalLock with machine summaries.
pub fn new_global_lock(name: &str) -> GlobalLock {
    use crate::tripwire::eventlog::now_iso8601;
    GlobalLock {
        schema: "1.0".to_string(),
        name: name.to_string(),
        last_apply: now_iso8601(),
        generator: format!("forjar {}", env!("CARGO_PKG_VERSION")),
        machines: indexmap::IndexMap::new(),
        outputs: indexmap::IndexMap::new(),
    }
}

/// Update global lock with results from an apply.
pub fn update_global_lock(
    state_dir: &Path,
    config_name: &str,
    machine_results: &[(String, usize, usize, usize)], // (name, total, converged, failed)
) -> Result<(), String> {
    use crate::tripwire::eventlog::now_iso8601;
    let mut lock = load_global_lock(state_dir)?.unwrap_or_else(|| new_global_lock(config_name));
    lock.name = config_name.to_string();
    lock.last_apply = now_iso8601();
    lock.generator = format!("forjar {}", env!("CARGO_PKG_VERSION"));

    for (name, total, converged, failed) in machine_results {
        lock.machines.insert(
            name.clone(),
            MachineSummary {
                resources: *total,
                converged: *converged,
                failed: *failed,
                last_apply: now_iso8601(),
            },
        );
    }

    save_global_lock(state_dir, &lock)
}

/// FJ-1260: Resolve all output values from a config into a flat map.
pub fn resolve_outputs(config: &super::types::ForjarConfig) -> indexmap::IndexMap<String, String> {
    let mut resolved = indexmap::IndexMap::new();
    for (k, output) in &config.outputs {
        let value = super::resolver::resolve_template_with_secrets(
            &output.value,
            &config.params,
            &config.machines,
            &config.secrets,
        )
        .unwrap_or_else(|_| output.value.clone());
        resolved.insert(k.clone(), value);
    }
    resolved
}

/// FJ-1260 + FJ-3300: Persist resolved outputs into the global lock file.
///
/// When `ephemeral` is true, secret values are replaced with BLAKE3 hashes
/// before writing to state. This prevents cleartext secrets at rest while
/// preserving drift detection capability.
pub fn persist_outputs(
    state_dir: &Path,
    config_name: &str,
    outputs: &indexmap::IndexMap<String, String>,
    ephemeral: bool,
) -> Result<(), String> {
    let mut lock = load_global_lock(state_dir)?.unwrap_or_else(|| new_global_lock(config_name));
    lock.outputs = if ephemeral {
        ephemeral::redact_outputs(outputs, true)
    } else {
        outputs.clone()
    };
    save_global_lock(state_dir, &lock)
}

/// Create a new empty StateLock for a machine.
pub fn new_lock(machine: &str, hostname: &str) -> StateLock {
    use crate::tripwire::eventlog::now_iso8601;
    StateLock {
        schema: "1.0".to_string(),
        machine: machine.to_string(),
        hostname: hostname.to_string(),
        generated_at: now_iso8601(),
        generator: format!("forjar {}", env!("CARGO_PKG_VERSION")),
        blake3_version: "1.8".to_string(),
        resources: indexmap::IndexMap::new(),
    }
}

/// FJ-262: Save per-machine apply report to `state/<machine>/last-apply.yaml`.
pub fn save_apply_report(state_dir: &Path, result: &ApplyResult) -> Result<(), String> {
    let dir = state_dir.join(&result.machine);
    std::fs::create_dir_all(&dir)
        .map_err(|e| format!("cannot create dir {}: {}", dir.display(), e))?;
    let path = dir.join("last-apply.yaml");
    let yaml =
        serde_yaml_ng::to_string(result).map_err(|e| format!("serialize report error: {e}"))?;
    std::fs::write(&path, &yaml).map_err(|e| format!("cannot write {}: {}", path.display(), e))?;
    Ok(())
}

/// FJ-262: Load last apply report for a machine.
pub fn load_apply_report(state_dir: &Path, machine: &str) -> Result<Option<String>, String> {
    let path = state_dir.join(machine).join("last-apply.yaml");
    if !path.exists() {
        return Ok(None);
    }
    std::fs::read_to_string(&path)
        .map(Some)
        .map_err(|e| format!("cannot read {}: {}", path.display(), e))
}

// ============================================================================
// FJ-266: State locking — prevent concurrent applies
// ============================================================================

/// Path to the process lock file.
pub(super) fn process_lock_path(state_dir: &Path) -> PathBuf {
    state_dir.join(".forjar.lock")
}

/// Acquire an exclusive process lock. Returns an error if another apply is running.
/// Stale locks (PID no longer running) are automatically removed.
pub fn acquire_process_lock(state_dir: &Path) -> Result<(), String> {
    std::fs::create_dir_all(state_dir).map_err(|e| format!("cannot create state dir: {e}"))?;

    let lock_path = process_lock_path(state_dir);

    // Check for existing lock
    if lock_path.exists() {
        let content = std::fs::read_to_string(&lock_path)
            .map_err(|e| format!("cannot read lock file: {e}"))?;
        if let Some(pid) = parse_lock_pid(&content) {
            if is_pid_running(pid) {
                return Err(format!(
                    "state directory is locked by PID {} ({}). \
                     If this is stale, run: forjar apply --force-unlock",
                    pid,
                    lock_path.display()
                ));
            }
            // Stale lock — PID no longer running, remove it
        }
        let _ = std::fs::remove_file(&lock_path);
    }

    // Write our PID
    let pid = std::process::id();
    let content = format!(
        "pid: {}\nstarted_at: {}\n",
        pid,
        crate::tripwire::eventlog::now_iso8601()
    );
    std::fs::write(&lock_path, content).map_err(|e| format!("cannot write lock file: {e}"))?;
    Ok(())
}

/// Release the process lock.
pub fn release_process_lock(state_dir: &Path) {
    let lock_path = process_lock_path(state_dir);
    let _ = std::fs::remove_file(&lock_path);
}

/// Force-remove the process lock (for --force-unlock).
pub fn force_unlock(state_dir: &Path) -> Result<(), String> {
    let lock_path = process_lock_path(state_dir);
    if !lock_path.exists() {
        return Ok(());
    }
    std::fs::remove_file(&lock_path).map_err(|e| format!("cannot remove lock file: {e}"))
}

/// Parse PID from lock file content.
pub(super) fn parse_lock_pid(content: &str) -> Option<u32> {
    for line in content.lines() {
        if let Some(rest) = line.strip_prefix("pid:") {
            return rest.trim().parse().ok();
        }
    }
    None
}

/// Check if a PID is still running (Linux-specific: /proc/<pid> exists).
fn is_pid_running(pid: u32) -> bool {
    Path::new(&format!("/proc/{pid}")).exists()
}

// ============================================================================
// FJ-1240: State encryption with age
// ============================================================================

/// Encrypt all YAML state files in the state directory using `age`.
/// Requires `FORJAR_AGE_KEY` env var (public key for encryption).
pub fn encrypt_state_files(state_dir: &Path) -> Result<(), String> {
    let pubkey = std::env::var("FORJAR_AGE_KEY")
        .map_err(|_| "FORJAR_AGE_KEY env var required for --encrypt-state".to_string())?;

    for entry in walk_yaml_files(state_dir) {
        let encrypted_path = entry.with_extension("yaml.age");
        let status = std::process::Command::new("age")
            .args(["-r", &pubkey, "-o"])
            .arg(&encrypted_path)
            .arg(&entry)
            .status()
            .map_err(|e| format!("age encrypt failed for {}: {}", entry.display(), e))?;
        if !status.success() {
            return Err(format!("age encrypt failed for {}", entry.display()));
        }
        std::fs::remove_file(&entry)
            .map_err(|e| format!("remove plaintext {}: {}", entry.display(), e))?;
    }
    Ok(())
}

/// Decrypt all `.age` state files in the state directory using `age`.
/// Requires `FORJAR_AGE_IDENTITY` env var (private key file path).
pub fn decrypt_state_files(state_dir: &Path) -> Result<(), String> {
    let identity = std::env::var("FORJAR_AGE_IDENTITY")
        .map_err(|_| "FORJAR_AGE_IDENTITY env var required to decrypt state".to_string())?;

    for entry in walk_age_files(state_dir) {
        let yaml_path = PathBuf::from(entry.to_string_lossy().replace(".yaml.age", ".yaml"));
        let status = std::process::Command::new("age")
            .args(["-d", "-i", &identity, "-o"])
            .arg(&yaml_path)
            .arg(&entry)
            .status()
            .map_err(|e| format!("age decrypt failed for {}: {}", entry.display(), e))?;
        if !status.success() {
            return Err(format!("age decrypt failed for {}", entry.display()));
        }
        std::fs::remove_file(&entry)
            .map_err(|e| format!("remove encrypted {}: {}", entry.display(), e))?;
    }
    Ok(())
}

/// Walk state directory for YAML files (lock files and reports).
fn walk_yaml_files(state_dir: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(state_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                files.extend(walk_yaml_files(&path));
            } else if path.extension().is_some_and(|e| e == "yaml") {
                files.push(path);
            }
        }
    }
    files
}

/// Walk state directory for .age encrypted files.
fn walk_age_files(state_dir: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    if let Ok(entries) = std::fs::read_dir(state_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                files.extend(walk_age_files(&path));
            } else if path.to_string_lossy().ends_with(".yaml.age") {
                files.push(path);
            }
        }
    }
    files
}

#[cfg(test)]
mod tests_basic;
#[cfg(test)]
mod tests_edge;
#[cfg(test)]
mod tests_encrypt;
#[cfg(test)]
mod tests_global_lock;
#[cfg(test)]
mod tests_helpers;
#[cfg(test)]
mod tests_integrity;
#[cfg(test)]
mod tests_integrity_cov;
#[cfg(test)]
mod tests_outputs;
#[cfg(test)]
mod tests_process_lock;
#[cfg(test)]
mod tests_reconstruct;
#[cfg(test)]
mod tests_state_cov;