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
//! FJ-3304: `forjar state encrypt/decrypt` CLI handler.
//!
//! Encrypts and decrypts state files using age passphrase encryption
//! with BLAKE3 integrity verification.

use crate::core::state_encryption::*;
use std::path::Path;

/// Encrypt state files with age passphrase encryption.
///
/// Each lock file is encrypted using the `age` crate with a user passphrase.
/// A BLAKE3-derived HMAC sidecar provides integrity verification.
pub fn cmd_state_encrypt(state_dir: &Path, passphrase: &str, json: bool) -> Result<(), String> {
    let lock_files = find_lock_files(state_dir)?;
    if lock_files.is_empty() {
        if json {
            println!("{{\"encrypted\": 0, \"skipped\": 0}}");
        } else {
            println!("No state files found in {}", state_dir.display());
        }
        return Ok(());
    }

    let mut encrypted = 0;
    let mut skipped = 0;

    for file in &lock_files {
        if is_encrypted(file) {
            skipped += 1;
            continue;
        }

        encrypt_state_file(file, passphrase)?;
        encrypted += 1;
    }

    if json {
        println!("{{\"encrypted\": {encrypted}, \"skipped\": {skipped}}}");
    } else {
        println!("Encrypted {encrypted} file(s), skipped {skipped} already-encrypted");
    }

    Ok(())
}

/// Decrypt state files encrypted with `forjar state encrypt`.
pub fn cmd_state_decrypt(state_dir: &Path, passphrase: &str, json: bool) -> Result<(), String> {
    let lock_files = find_lock_files(state_dir)?;

    // AN ABSENT CAPABILITY IS A NO-GO, NEVER A SILENT SUCCESS.
    //
    // Built without `--features encryption`, decrypt_state_file is a stub that
    // always errors. Every encrypted file would land in the error tally and —
    // before the fix below — exit 0 anyway. Worse, a file whose sidecar is
    // missing is not even attempted, so the run reported "skipped" and success
    // for state it could never have read. Say so plainly, once, up front.
    #[cfg(not(feature = "encryption"))]
    if !lock_files.is_empty() {
        return Err(
            "this build has no encryption support, so no state file can be \
                    decrypted — rebuild with `--features encryption`. Reporting a \
                    skip count here would claim a result that was never measured."
                .to_string(),
        );
    }
    let mut decrypted = 0;
    let mut skipped = 0;
    let mut errors = 0;

    for file in &lock_files {
        if !is_encrypted(file) {
            skipped += 1;
            continue;
        }

        match decrypt_state_file(file, passphrase) {
            Ok(_) => decrypted += 1,
            Err(e) => {
                errors += 1;
                if !json {
                    println!("  DECRYPT FAIL: {}: {e}", file.display());
                }
            }
        }
    }

    if json {
        println!("{{\"decrypted\": {decrypted}, \"skipped\": {skipped}, \"errors\": {errors}}}");
    } else {
        println!("Decrypted {decrypted} file(s), skipped {skipped}, errors {errors}");
    }

    // A FAILED DECRYPT IS A FAILURE.
    //
    // This counted `errors` and then returned Ok(()) regardless, so a WRONG
    // PASSPHRASE exited 0 with "Decrypted 0 file(s), skipped 2, errors 0" and
    // a caller could not distinguish a typo from success by exit code. Ledger
    // id state-decrypt-false-green-without-encryption-feature; confirmed at
    // 1.12.3 and still live at 1.16.0.
    //
    // Note the two answers this deliberately keeps apart: "there was nothing
    // to decrypt" (every file skipped) is NOT an error and still exits 0, but
    // "I could not decrypt what was there" is. Collapsing them by failing
    // whenever `decrypted == 0` would break every unencrypted state dir.
    if errors > 0 {
        return Err(format!(
            "{errors} file(s) failed to decrypt — wrong passphrase, or the state is not \
             recoverable with this key. Nothing was modified."
        ));
    }

    Ok(())
}

/// FJ-3309: Re-encrypt state files with a new passphrase.
///
/// Decrypts each encrypted file with the old passphrase, then re-encrypts
/// with the new one. Non-encrypted files are encrypted with the new passphrase directly.
pub fn cmd_state_rekey(
    state_dir: &Path,
    old_passphrase: &str,
    new_passphrase: &str,
    json: bool,
) -> Result<(), String> {
    let lock_files = find_lock_files(state_dir)?;
    if lock_files.is_empty() {
        if json {
            println!("{{\"rekeyed\": 0, \"errors\": 0}}");
        } else {
            println!("No state files found in {}", state_dir.display());
        }
        return Ok(());
    }

    let mut rekeyed = 0;
    let mut errors = 0;

    for file in &lock_files {
        let plaintext = if is_encrypted(file) {
            match rekey_decrypt(file, old_passphrase) {
                Ok(p) => p,
                Err(e) => {
                    errors += 1;
                    if !json {
                        println!("  REKEY FAIL: {}: {e}", file.display());
                    }
                    continue;
                }
            }
        } else {
            std::fs::read(file).map_err(|e| format!("read {}: {e}", file.display()))?
        };

        // Re-encrypt with new passphrase
        let ciphertext = encrypt_data(&plaintext, new_passphrase)?;
        std::fs::write(file, &ciphertext).map_err(|e| format!("write {}: {e}", file.display()))?;

        let new_key = derive_key(new_passphrase);
        let meta = create_metadata(&plaintext, &ciphertext, &new_key);
        write_metadata(file, &meta)?;

        rekeyed += 1;
    }

    if json {
        println!("{{\"rekeyed\": {rekeyed}, \"errors\": {errors}}}");
    } else {
        println!("Rekeyed {rekeyed} file(s), errors {errors}");
    }

    Ok(())
}

/// Decrypt a file during rekey (returns plaintext without writing to disk).
fn rekey_decrypt(file: &Path, passphrase: &str) -> Result<Vec<u8>, String> {
    let ciphertext = std::fs::read(file).map_err(|e| format!("read {}: {e}", file.display()))?;
    let key = derive_key(passphrase);
    let meta = read_metadata(file)?;

    if !verify_metadata(&meta, &ciphertext, &key) {
        return Err("integrity check failed".into());
    }

    let plaintext = decrypt_data(&ciphertext, passphrase)?;

    if hash_data(&plaintext) != meta.plaintext_hash {
        return Err("plaintext hash mismatch".into());
    }

    Ok(plaintext)
}

/// Appends every lock file sitting directly in `dir`. An unreadable directory
/// contributes nothing: a state tree the caller cannot list is not an error
/// here, it simply holds no locks to encrypt.
fn push_lock_files_in(dir: &Path, files: &mut Vec<std::path::PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if is_lock_file(&path) {
            files.push(path);
        }
    }
}

/// Find lock files in a state directory: those at the top level, plus those one
/// level down in each machine subdirectory.
fn find_lock_files(state_dir: &Path) -> Result<Vec<std::path::PathBuf>, String> {
    let mut files = Vec::new();

    if !state_dir.exists() {
        return Ok(files);
    }

    if let Ok(entries) = std::fs::read_dir(state_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                push_lock_files_in(&path, &mut files);
            } else if is_lock_file(&path) {
                files.push(path);
            }
        }
    }

    files.sort();
    Ok(files)
}

fn is_lock_file(path: &Path) -> bool {
    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
    (name.ends_with(".lock.yaml") || name.ends_with(".lock.json"))
        && !name.ends_with(".enc.meta.json")
}

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

    #[test]
    fn find_lock_files_empty() {
        let dir = tempfile::tempdir().unwrap();
        let files = find_lock_files(dir.path()).unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn find_lock_files_with_locks() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("m1.lock.yaml"), "data").unwrap();
        std::fs::write(dir.path().join("m2.lock.yaml"), "data").unwrap();
        std::fs::write(dir.path().join("other.txt"), "data").unwrap();
        let files = find_lock_files(dir.path()).unwrap();
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn find_lock_files_subdirs() {
        let dir = tempfile::tempdir().unwrap();
        let sub = dir.path().join("machine1");
        std::fs::create_dir_all(&sub).unwrap();
        std::fs::write(sub.join("state.lock.yaml"), "data").unwrap();
        let files = find_lock_files(dir.path()).unwrap();
        assert_eq!(files.len(), 1);
    }

    #[test]
    fn find_lock_files_nonexistent() {
        let files = find_lock_files(Path::new("/nonexistent/dir")).unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn is_lock_file_check() {
        assert!(is_lock_file(Path::new("m1.lock.yaml")));
        assert!(is_lock_file(Path::new("state.lock.json")));
        assert!(!is_lock_file(Path::new("state.yaml")));
        assert!(!is_lock_file(Path::new("x.enc.meta.json")));
    }

    #[test]
    fn encrypt_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let result = cmd_state_encrypt(dir.path(), "pass", false);
        assert!(result.is_ok());
    }

    #[test]
    fn encrypt_json_output() {
        let dir = tempfile::tempdir().unwrap();
        let result = cmd_state_encrypt(dir.path(), "pass", true);
        assert!(result.is_ok());
    }

    #[test]
    fn rekey_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let result = cmd_state_rekey(dir.path(), "old", "new", false);
        assert!(result.is_ok());
    }

    #[test]
    fn rekey_json_output() {
        let dir = tempfile::tempdir().unwrap();
        let result = cmd_state_rekey(dir.path(), "old", "new", true);
        assert!(result.is_ok());
    }
}

#[cfg(all(test, feature = "encryption"))]
mod tests_encryption {
    use super::*;

    #[test]
    fn encrypt_decrypt_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("test.lock.yaml");
        let original = "resources:\n  pkg:\n    state: converged\n";
        std::fs::write(&lock, original).unwrap();

        let passphrase = "test-pass-123";

        // Encrypt
        cmd_state_encrypt(dir.path(), passphrase, false).unwrap();
        assert!(is_encrypted(&lock));
        let encrypted_content = std::fs::read(&lock).unwrap();
        assert_ne!(encrypted_content, original.as_bytes());

        // Decrypt
        cmd_state_decrypt(dir.path(), passphrase, false).unwrap();
        let decrypted_content = std::fs::read(&lock).unwrap();
        assert_eq!(decrypted_content, original.as_bytes());
    }

    #[test]
    fn decrypt_wrong_passphrase() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("test.lock.yaml");
        std::fs::write(&lock, "state data").unwrap();

        cmd_state_encrypt(dir.path(), "correct-pass", false).unwrap();

        // A WRONG PASSPHRASE MUST FAIL. This test previously asserted
        // `is_ok()` with the comment "doesn't error, reports errors count" —
        // its own first line already said "should fail integrity check", so
        // the test recorded the intent and then enshrined the opposite. That
        // is how state-decrypt-false-green-without-encryption-feature survived
        // four minor versions: the ledger called it a defect and the suite
        // called it correct.
        let result = cmd_state_decrypt(dir.path(), "wrong-pass", false);
        assert!(
            result.is_err(),
            "a wrong passphrase reported success — a caller cannot tell a typo \
             from a correct passphrase by exit code"
        );
        // And the file must be left ENCRYPTED, not half-written.
        assert!(
            is_encrypted(&lock),
            "the file was modified by a failed decrypt"
        );
    }

    #[test]
    fn decrypt_with_nothing_encrypted_is_not_a_failure() {
        // The control. "I could not decrypt what was there" and "there was
        // nothing to decrypt" are different answers, and only the first is an
        // error. Without this, the fix above could be satisfied by failing
        // whenever `decrypted == 0`, which would break every state dir that is
        // simply not encrypted.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("test.lock.yaml"), "plain").unwrap();
        assert!(cmd_state_decrypt(dir.path(), "any-pass", false).is_ok());
    }

    #[test]
    fn rekey_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("test.lock.yaml");
        let original = "resources:\n  pkg:\n    state: converged\n";
        std::fs::write(&lock, original).unwrap();

        // Encrypt with old passphrase
        cmd_state_encrypt(dir.path(), "old-pass", false).unwrap();
        assert!(is_encrypted(&lock));

        // Rekey to new passphrase
        cmd_state_rekey(dir.path(), "old-pass", "new-pass", false).unwrap();
        assert!(is_encrypted(&lock));

        // Decrypt with new passphrase
        cmd_state_decrypt(dir.path(), "new-pass", false).unwrap();
        let content = std::fs::read(&lock).unwrap();
        assert_eq!(content, original.as_bytes());
    }

    #[test]
    fn rekey_wrong_old_passphrase() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("test.lock.yaml");
        std::fs::write(&lock, "data").unwrap();

        cmd_state_encrypt(dir.path(), "correct", false).unwrap();

        // Rekey with wrong old passphrase — should report error
        let result = cmd_state_rekey(dir.path(), "wrong", "new", false);
        assert!(result.is_ok()); // reports errors, doesn't fail
    }

    #[test]
    fn rekey_unencrypted_file() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("state.lock.yaml");
        let original = "plain state data";
        std::fs::write(&lock, original).unwrap();

        // Rekey encrypts unencrypted files directly
        cmd_state_rekey(dir.path(), "ignored", "new-pass", false).unwrap();
        assert!(is_encrypted(&lock));

        // Decrypt with new passphrase
        cmd_state_decrypt(dir.path(), "new-pass", false).unwrap();
        let content = std::fs::read(&lock).unwrap();
        assert_eq!(content, original.as_bytes());
    }
}