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
//! FJ-016: Drift detection — compare live state to lock hashes.

use crate::core::types::{Machine, Resource, ResourceStatus, ResourceType, StateLock};
use crate::tripwire::hasher;
use std::path::Path;

/// A single drift finding.
#[derive(Debug, Clone)]
pub struct DriftFinding {
    /// Resource identifier.
    pub resource_id: String,
    /// Type of resource that drifted.
    pub resource_type: ResourceType,
    /// Expected hash from the lock file.
    pub expected_hash: String,
    /// Actual hash from live state.
    pub actual_hash: String,
    /// Human-readable drift description.
    pub detail: String,
}

/// Check a single file resource for drift.
pub fn check_file_drift(
    resource_id: &str,
    path: &str,
    expected_hash: &str,
) -> Option<DriftFinding> {
    let file_path = Path::new(path);
    if !file_path.exists() {
        return Some(DriftFinding {
            resource_id: resource_id.to_string(),
            resource_type: ResourceType::File,
            expected_hash: expected_hash.to_string(),
            actual_hash: "MISSING".to_string(),
            detail: format!("{path} does not exist"),
        });
    }

    let actual = if file_path.is_dir() {
        hasher::hash_directory(file_path).unwrap_or_else(|e| format!("ERROR:{e}"))
    } else {
        hasher::hash_file(file_path).unwrap_or_else(|e| format!("ERROR:{e}"))
    };

    if actual != expected_hash {
        Some(DriftFinding {
            resource_id: resource_id.to_string(),
            resource_type: ResourceType::File,
            expected_hash: expected_hash.to_string(),
            actual_hash: actual,
            detail: format!("{path} content changed"),
        })
    } else {
        None
    }
}

/// Compute the hash of a remote file or directory via transport.
fn hash_remote_content(
    out: &crate::transport::ExecOutput,
    path: &str,
    machine: &Machine,
) -> Option<String> {
    // STRONG contract: `hash_string` rejects empty input. Drift queries may
    // legitimately return empty stdout when the file is missing or empty —
    // use `hash_string_or_sentinel` to stay inside the contract.
    if out.stdout.trim() == "__DIR__" {
        let ls_script = format!("ls -la '{path}'");
        match crate::transport::exec_script(machine, &ls_script) {
            Ok(ls_out) if ls_out.success() => Some(hasher::hash_string_or_sentinel(&ls_out.stdout)),
            _ => None,
        }
    } else {
        Some(hasher::hash_string_or_sentinel(&out.stdout))
    }
}

/// Build a DriftFinding for a changed file.
fn file_drift_finding(
    resource_id: &str,
    expected_hash: &str,
    actual_hash: String,
    detail: String,
) -> DriftFinding {
    DriftFinding {
        resource_id: resource_id.to_string(),
        resource_type: ResourceType::File,
        expected_hash: expected_hash.to_string(),
        actual_hash,
        detail,
    }
}

/// Check a file resource for drift via transport (for container/remote machines).
/// Runs `cat <path>` on the target and hashes the output.
pub fn check_file_drift_via_transport(
    resource_id: &str,
    path: &str,
    expected_hash: &str,
    machine: &Machine,
) -> Option<DriftFinding> {
    let script = format!(
        "set -euo pipefail\nif [ -d '{path}' ]; then echo '__DIR__'; else cat '{path}'; fi"
    );
    match crate::transport::exec_script(machine, &script) {
        Ok(out) if out.success() => {
            let actual = hash_remote_content(&out, path, machine)?;
            if actual != expected_hash {
                Some(file_drift_finding(
                    resource_id,
                    expected_hash,
                    actual,
                    format!("{path} content changed"),
                ))
            } else {
                None
            }
        }
        Ok(out) => Some(file_drift_finding(
            resource_id,
            expected_hash,
            "MISSING".to_string(),
            format!("{} not accessible: {}", path, out.stderr.trim()),
        )),
        Err(e) => Some(file_drift_finding(
            resource_id,
            expected_hash,
            "ERROR".to_string(),
            format!("transport error: {e}"),
        )),
    }
}

/// Check all file-type resources in a lock for drift.
/// Uses local filesystem hashing (for local machines without transport context).
pub fn detect_drift(lock: &StateLock) -> Vec<DriftFinding> {
    detect_drift_impl(lock, None)
}

/// Check all file-type resources in a lock for drift, using transport for remote/container machines.
pub fn detect_drift_with_machine(lock: &StateLock, machine: &Machine) -> Vec<DriftFinding> {
    detect_drift_impl(lock, Some(machine))
}

/// Check a non-file resource for drift by running its state_query_script.
fn check_nonfile_drift(
    id: &str,
    rl: &crate::core::types::ResourceLock,
    resource: &Resource,
    machine: &Machine,
    stored_live_hash: &str,
) -> Option<DriftFinding> {
    let query = match crate::core::codegen::state_query_script(resource) {
        Ok(q) => q,
        Err(_) => return None,
    };

    match crate::transport::exec_script(machine, &query) {
        Ok(out) if out.success() => {
            // STRONG contract: query stdout may be empty when state absent.
            let actual_hash = hasher::hash_string_or_sentinel(&out.stdout);
            if actual_hash != stored_live_hash {
                Some(DriftFinding {
                    resource_id: id.to_string(),
                    resource_type: rl.resource_type.clone(),
                    expected_hash: stored_live_hash.to_string(),
                    actual_hash,
                    detail: format!("{} state changed", rl.resource_type),
                })
            } else {
                None
            }
        }
        Ok(out) => Some(DriftFinding {
            resource_id: id.to_string(),
            resource_type: rl.resource_type.clone(),
            expected_hash: stored_live_hash.to_string(),
            actual_hash: "ERROR".to_string(),
            detail: format!("state query failed: {}", out.stderr.trim()),
        }),
        Err(e) => Some(DriftFinding {
            resource_id: id.to_string(),
            resource_type: rl.resource_type.clone(),
            expected_hash: stored_live_hash.to_string(),
            actual_hash: "ERROR".to_string(),
            detail: format!("transport error: {e}"),
        }),
    }
}

/// Full drift detection: files via hash comparison, non-file resources via state_query_script.
/// Requires the config resources to reconstruct state query scripts.
/// FJ-1220: Resources with lifecycle.ignore_drift are skipped.
pub fn detect_drift_full(
    lock: &StateLock,
    machine: &Machine,
    resources: &indexmap::IndexMap<String, Resource>,
) -> Vec<DriftFinding> {
    let mut findings = detect_drift_with_lifecycle(lock, Some(machine), resources);
    findings.extend(detect_nonfile_drift(lock, machine, resources));
    findings.extend(detect_image_drift(lock, machine, resources));
    findings
}

/// Check all non-file converged resources for drift via state_query_script.
fn detect_nonfile_drift(
    lock: &StateLock,
    machine: &Machine,
    resources: &indexmap::IndexMap<String, Resource>,
) -> Vec<DriftFinding> {
    let mut findings = Vec::new();
    for (id, rl) in &lock.resources {
        if rl.status != ResourceStatus::Converged || rl.resource_type == ResourceType::File {
            continue;
        }
        if should_ignore_drift(id, resources) {
            continue;
        }
        let stored_live_hash = match rl.details.get("live_hash") {
            Some(serde_yaml_ng::Value::String(s)) => s.as_str(),
            _ => continue,
        };
        let resource = match resources.get(id) {
            Some(r) => r,
            None => continue,
        };
        if let Some(f) = check_nonfile_drift(id, rl, resource, machine, stored_live_hash) {
            findings.push(f);
        }
    }
    findings
}

/// FJ-2106/E15: Check all image-type resources for drift.
///
/// For each converged image resource, compares the manifest digest stored
/// in the lock file against the running container's image digest
/// (via `docker inspect`).
fn detect_image_drift(
    lock: &StateLock,
    machine: &Machine,
    resources: &indexmap::IndexMap<String, Resource>,
) -> Vec<DriftFinding> {
    let mut findings = Vec::new();
    for (id, rl) in &lock.resources {
        if rl.status != ResourceStatus::Converged || rl.resource_type != ResourceType::Image {
            continue;
        }
        if should_ignore_drift(id, resources) {
            continue;
        }
        let expected_digest = match rl.details.get("manifest_digest") {
            Some(serde_yaml_ng::Value::String(s)) => s.as_str(),
            _ => continue,
        };
        let container_name = match rl.details.get("container_name") {
            Some(serde_yaml_ng::Value::String(s)) => s.as_str(),
            _ => continue,
        };
        if let Some(f) = check_image_drift(id, container_name, expected_digest, machine) {
            findings.push(f);
        }
    }
    findings
}

/// FJ-2106/E15: Check a single image resource for drift.
///
/// Runs `docker inspect <container> --format '{{.Image}}'` on the target
/// machine and compares the actual image digest to the expected manifest
/// digest from the build.
pub fn check_image_drift(
    resource_id: &str,
    container_name: &str,
    expected_digest: &str,
    machine: &Machine,
) -> Option<DriftFinding> {
    let script = format!(
        "docker inspect {container_name} --format '{{{{.Image}}}}' 2>/dev/null || echo 'NOT_RUNNING'"
    );
    match crate::transport::exec_script(machine, &script) {
        Ok(out) if out.success() => {
            let actual = out.stdout.trim().to_string();
            if actual == "NOT_RUNNING" {
                Some(DriftFinding {
                    resource_id: resource_id.to_string(),
                    resource_type: ResourceType::Image,
                    expected_hash: expected_digest.to_string(),
                    actual_hash: "NOT_RUNNING".to_string(),
                    detail: format!("container {container_name} is not running"),
                })
            } else if actual != expected_digest {
                Some(DriftFinding {
                    resource_id: resource_id.to_string(),
                    resource_type: ResourceType::Image,
                    expected_hash: expected_digest.to_string(),
                    actual_hash: actual,
                    detail: "deployed image differs from built image".to_string(),
                })
            } else {
                None
            }
        }
        Ok(out) => Some(DriftFinding {
            resource_id: resource_id.to_string(),
            resource_type: ResourceType::Image,
            expected_hash: expected_digest.to_string(),
            actual_hash: "ERROR".to_string(),
            detail: format!("docker inspect failed: {}", out.stderr.trim()),
        }),
        Err(e) => Some(DriftFinding {
            resource_id: resource_id.to_string(),
            resource_type: ResourceType::Image,
            expected_hash: expected_digest.to_string(),
            actual_hash: "ERROR".to_string(),
            detail: format!("transport error: {e}"),
        }),
    }
}

/// FJ-1220: Check if a resource's lifecycle rules say to ignore drift.
fn should_ignore_drift(
    resource_id: &str,
    resources: &indexmap::IndexMap<String, Resource>,
) -> bool {
    if let Some(resource) = resources.get(resource_id) {
        if let Some(ref lifecycle) = resource.lifecycle {
            // ignore_drift: ["*"] means skip all drift
            // ignore_drift: ["content", "mode"] means skip specific fields (treated as skip-all for now)
            return !lifecycle.ignore_drift.is_empty();
        }
    }
    false
}

/// Drift detection for file resources, respecting lifecycle.ignore_drift.
fn detect_drift_with_lifecycle(
    lock: &StateLock,
    machine: Option<&Machine>,
    resources: &indexmap::IndexMap<String, Resource>,
) -> Vec<DriftFinding> {
    let mut findings = Vec::new();

    for (id, rl) in &lock.resources {
        if rl.status != ResourceStatus::Converged || rl.resource_type != ResourceType::File {
            continue;
        }
        // FJ-1220: skip resources with ignore_drift
        if should_ignore_drift(id, resources) {
            continue;
        }
        if let Some(f) = check_file_resource_drift(id, rl, machine) {
            findings.push(f);
        }
    }

    findings
}

/// Extract path and content_hash from a file resource lock entry and check for drift.
fn check_file_resource_drift(
    id: &str,
    rl: &crate::core::types::ResourceLock,
    machine: Option<&Machine>,
) -> Option<DriftFinding> {
    let path = match rl.details.get("path") {
        Some(serde_yaml_ng::Value::String(s)) => s.as_str(),
        _ => return None,
    };
    let expected = match rl.details.get("content_hash") {
        Some(serde_yaml_ng::Value::String(s)) => s.as_str(),
        _ => return None,
    };
    match machine {
        Some(m) if m.is_container_transport() => {
            check_file_drift_via_transport(id, path, expected, m)
        }
        _ => check_file_drift(id, path, expected),
    }
}

fn detect_drift_impl(lock: &StateLock, machine: Option<&Machine>) -> Vec<DriftFinding> {
    let mut findings = Vec::new();

    for (id, rl) in &lock.resources {
        if rl.status != ResourceStatus::Converged || rl.resource_type != ResourceType::File {
            continue;
        }
        if let Some(f) = check_file_resource_drift(id, rl, machine) {
            findings.push(f);
        }
    }

    findings
}

#[cfg(test)]
mod tests_basic;
#[cfg(test)]
mod tests_basic_b;
#[cfg(test)]
mod tests_edge_fj131;
#[cfg(test)]
mod tests_edge_fj132;
#[cfg(test)]
mod tests_edge_fj132_b;
#[cfg(test)]
mod tests_fj036;
#[cfg(test)]
mod tests_full;
#[cfg(test)]
mod tests_image_drift;
#[cfg(test)]
mod tests_lifecycle;
#[cfg(test)]
mod tests_transport;