forjar 1.25.1

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
//! Apply dry-run variants.

use super::apply::*;
use super::apply_helpers::*;
use super::helpers::*;
use super::helpers_state::*;
use super::workspace::*;
use crate::core::{codegen, planner, resolver, state, types};
use crate::transport;
use crate::tripwire::hasher;
use std::path::Path;

/// FJ-583: Show execution graph without applying.
pub(crate) fn cmd_apply_dry_run_graph(file: &Path) -> Result<(), String> {
    let config = parse_and_validate(file)?;

    // Build and display the execution DAG
    let mut graph: Vec<(String, Vec<String>)> = Vec::new();
    for (name, res) in &config.resources {
        graph.push((name.clone(), res.depends_on.clone()));
    }
    graph.sort_by(|a, b| a.0.cmp(&b.0));

    println!("Execution graph (dry run):");
    println!("  {} resources", graph.len());
    println!();
    for (name, deps) in &graph {
        if deps.is_empty() {
            println!("  {name} (no dependencies — runs first)");
        } else {
            println!("  {} → depends on: {}", name, deps.join(", "));
        }
    }
    Ok(())
}

/// FJ-510: Canary machine — apply to single machine first, then remaining.
///
/// # `yes` is the operator's, not ours (forjar#374)
///
/// Both legs used to pass a hard-coded `true` for `--yes`. A flag whose whole
/// promise is "one machine first, so you can look" therefore converged the
/// canary AND every remaining machine in the config without the confirmation
/// prompt every other apply asks for — for authorized operators too, needing no
/// misconfiguration to reach. The confirmation is the operator's decision, so
/// it is threaded from the command line and each leg asks in turn.
pub(crate) fn cmd_apply_canary_machine(
    file: &Path,
    state_dir: &Path,
    canary: &str,
    params: &[String],
    timeout: Option<u64>,
    yes: bool,
) -> Result<(), String> {
    let config = parse_and_validate(file)?;
    if !config.machines.contains_key(canary) {
        return Err(format!(
            "canary machine '{}' not found (available: {})",
            canary,
            config
                .machines
                .keys()
                .cloned()
                .collect::<Vec<_>>()
                .join(", ")
        ));
    }

    println!("=== Canary: applying to '{canary}' first ===\n");
    cmd_apply(
        file,
        state_dir,
        Some(canary),
        None,
        None,
        None,
        false,
        false,
        false,
        params,
        false,
        timeout,
        false,
        false,
        None,
        None,
        false,
        false,
        None,
        false,
        false,
        0,
        yes,
        false,
        None,
        false,
        None,
        None,
        None,
        false,
        None,
        false,
        None,  // telemetry_endpoint
        false, // refresh
        None,  // force_tag
        &[],
    )?;

    println!("\n{} Canary '{}' succeeded.", green(""), canary);

    let remaining: Vec<String> = config
        .machines
        .keys()
        .filter(|k| *k != canary)
        .cloned()
        .collect();

    if remaining.is_empty() {
        println!("No remaining machines. Canary deploy complete.");
        return Ok(());
    }

    println!(
        "\n=== Fleet: applying to {} remaining machines ===\n",
        remaining.len()
    );
    // forjar#374 (quorum review): one confirmation for the fleet, not one per
    // machine. `cmd_apply` prompts per machine when `yes` is false, so an
    // operator with N remaining machines was asked N times; the first EOF
    // aborted the rest silently. Ask once here, then hand each leg `yes`.
    if !yes {
        confirm_fleet_rollout(remaining.len())?;
    }
    for machine_name in &remaining {
        cmd_apply(
            file,
            state_dir,
            Some(machine_name),
            None,
            None,
            None,
            false,
            false,
            false,
            params,
            false,
            timeout,
            false,
            false,
            None,
            None,
            false,
            false,
            None,
            false,
            false,
            0,
            true, // confirmed once above, or --yes was typed
            false,
            None,
            false,
            None,
            None,
            None,
            false,
            None,
            false,
            None,  // telemetry_endpoint
            false, // refresh
            None,  // force_tag
            &[],
        )?;
    }

    println!(
        "\n{} Fleet deploy complete ({} machines).",
        green(""),
        remaining.len() + 1
    );
    Ok(())
}

/// Re-query ONE converged resource's live state and hash it the same way the
/// executor did when it recorded the stored `live_hash`.
///
/// FJ-154 / #22: resolve with the SAME SecretsConfig the executor used to
/// produce the stored live_hash (record_success →
/// resolve_resource_templates_with_secrets(.., &cfg.config.secrets)), so the
/// refresh-query script matches and we don't report spurious drift / rewrite
/// state on every refresh.
///
/// `None` means "no answer" — the resource has no refresh-query script, or the
/// query did not succeed — and the caller then leaves the stored hash untouched.
fn refreshed_live_hash(
    machine: &types::Machine,
    resource: &types::Resource,
    config: &types::ForjarConfig,
    timeout: Option<u64>,
) -> Option<String> {
    let resolved = resolver::resolve_resource_templates_with_secrets(
        resource,
        &config.params,
        &config.machines,
        &config.secrets,
    )
    .unwrap_or_else(|_| resource.clone());

    // STRONG contract: refresh-query stdout may legitimately be empty when
    // state is absent — use the sentinel wrapper to uphold `!input.is_empty()`.
    // forjar#360: THE THIRD WRITER of the observed digest. `record_success` and
    // `drift::check_nonfile_drift` are the obvious two; this one re-baselines
    // the same value under `apply --refresh` / `--refresh-only`. Masking the
    // other two and not this one means one `--refresh` stores an UNMASKED
    // digest and the next `drift` reports false drift on the ignored field —
    // and `observed_state_drifted` below mis-counts refresh's own `drift:`
    // lines while it does so.
    let query = codegen::state_query_script(&resolved).ok()?;
    match transport::exec_script_timeout(machine, &query, timeout) {
        Ok(out) if out.success() => Some(hasher::hash_string_or_sentinel(
            &crate::core::observation_mask::masked_for(&out.stdout, &resolved),
        )),
        _ => None,
    }
}

/// Live hash for a lock entry that is still eligible for refresh: it must be
/// recorded as converged and still be present in the config. `None` means the
/// entry is skipped — either it is not converged, the resource was removed from
/// the config, or the live query did not answer.
fn refreshable_live_hash(
    config: &types::ForjarConfig,
    machine: &types::Machine,
    id: &str,
    rl: &types::ResourceLock,
    timeout: Option<u64>,
) -> Option<String> {
    if rl.status != types::ResourceStatus::Converged {
        return None;
    }
    let resource = config.resources.get(id)?;
    refreshed_live_hash(machine, resource, config, timeout)
}

/// True when a freshly queried hash differs from the OBSERVED state already
/// recorded on the lock entry (an absent recording counts as a difference
/// unless the new hash is empty, matching the pre-refactor comparison).
///
/// Reads through `observed_state()` rather than `details["live_hash"]`: #338
/// split SPEC from STATUS and the accessor prefers the typed `observed` field,
/// so a raw `details` read here would disagree with the drift path.
fn observed_state_drifted(rl: &types::ResourceLock, hash: &str) -> bool {
    // Compare against the OBSERVED state through the accessor, so this path and
    // the drift path agree on where that value lives.
    let old_hash = rl.observed_state().unwrap_or("");
    hash != old_hash
}

/// Re-queries every refreshable resource of one machine, returning the lock with
/// updated observed state plus (queried, drifted) counts.
fn refresh_machine_lock(
    config: &types::ForjarConfig,
    machine: &types::Machine,
    machine_name: &str,
    lock: &types::StateLock,
    timeout: Option<u64>,
    verbose: bool,
) -> (types::StateLock, usize, usize) {
    let mut updated_lock = lock.clone();
    let mut refreshed = 0usize;
    let mut drift_count = 0usize;

    for (id, rl) in &lock.resources {
        let Some(hash) = refreshable_live_hash(config, machine, id, rl, timeout) else {
            continue;
        };
        if observed_state_drifted(rl, &hash) {
            drift_count += 1;
            if verbose {
                eprintln!("  drift: {id} on {machine_name} (hash changed)");
            }
        }
        if let Some(entry) = updated_lock.resources.get_mut(id) {
            // MUST go through the setter. Writing only `details` here would
            // leave the typed `observed` field holding the PREVIOUS digest, and
            // `observed_state()` prefers the typed field — so `--refresh` would
            // update one of two copies and every later reader would see the
            // stale one. That is forjar#305's exact shape (two stores, readers
            // split between them), which this refactor exists to remove.
            entry.set_observed_state(hash);
            // The mask travels with the digest it was taken under, exactly as
            // in `record_success`. Without this a `--refresh` under a newly
            // added `ignore_drift` writes a masked digest beside a stale mask
            // record, and drift declines to compare (forjar#360).
            if let Some(r) = config.resources.get(id) {
                let key = crate::core::observation_mask::mask_key(r);
                crate::core::observation_mask::record_mask(&mut entry.details, &key);
            }
        }
        refreshed += 1;
    }

    (updated_lock, refreshed, drift_count)
}

/// FJ-1230: Refresh state only — re-query live state for all converged resources
/// and update lock hashes without applying any changes.
///
/// # Refs #368: "without applying any changes" is not "without writing state"
///
/// This takes the same `apply_mode_exits` early return `--plan-file` does, so
/// it never reached `apply_pre_validate` either — and it rewrites
/// `state.lock.yaml` and re-seals its `.b3` in a loop. That made it a laundry
/// for the one gate whose refusal text says no flag overrides it. Measured on
/// 1.24.0 with the lock BODY tampered:
///
/// ```text
///   apply --yes           -> error: state integrity check failed … No apply
///                            flag overrides this check.
///   apply --refresh-only  -> Refresh complete: 1 resources queried, 0 drifted
///                            (.b3 rewritten: 7d869a9f… -> 9b96fcbd…)
///   apply --yes           -> Apply complete: 1 converged (1 repaired drift)
/// ```
///
/// So a fix confined to `cmd_apply_from_plan` would have left the same hole
/// open one flag over. `check_operator_auth` runs here too, for the reason
/// forjar#370 moved it into `cmd_apply_from_plan`: the gate belongs to the act
/// of writing state, not to the dispatcher that remembered.
///
/// `operator` is a PARAMETER and not a hard-coded `None`, and the difference is
/// not cosmetic. `OperatorIdentity::resolve(None)` falls back to
/// `$USER@$(hostname)`, so a gate that ignores the flag refuses the very person
/// it is meant to admit: on a machine declaring `allowed_operators: [alice]`,
/// `apply --refresh-only --operator alice` answered
/// `error: operator 'noah@box' not authorized for machine 'box'` while the
/// ordinary `apply --operator alice` converged. That is forjar#358's defect —
/// a mode that drops what the operator actually typed — reappearing one flag
/// over, which is precisely the shape this change exists to close.
#[allow(clippy::too_many_arguments)]
pub(crate) fn cmd_refresh_only(
    file: &Path,
    state_dir: &Path,
    machine_filter: Option<&str>,
    verbose: bool,
    timeout: Option<u64>,
    env_file: Option<&Path>,
    workspace: Option<&str>,
    operator: Option<&str>,
) -> Result<(), String> {
    super::dispatch_apply::check_operator_auth(file, operator, machine_filter)?;

    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)?;

    // Refuse BEFORE the first `save_lock`, not after: a refresh that re-seals a
    // tampered lock has destroyed the only evidence the tamper happened.
    super::apply_preflight::lock_write_gates(state_dir, verbose)?;

    let locks = load_machine_locks(&config, state_dir, machine_filter)?;
    let mut refreshed = 0usize;
    let mut drift_count = 0usize;

    for (machine_name, lock) in &locks {
        let Some(machine) = config.machines.get(machine_name) else {
            continue;
        };
        let (updated_lock, machine_refreshed, machine_drift) =
            refresh_machine_lock(&config, machine, machine_name, lock, timeout, verbose);
        refreshed += machine_refreshed;
        drift_count += machine_drift;
        state::save_lock(state_dir, &updated_lock)?;
    }

    println!("Refresh complete: {refreshed} resources queried, {drift_count} drifted");
    Ok(())
}

/// FJ-536: Dry run cost — show estimated change count without applying.
pub(crate) fn cmd_apply_dry_run_cost(
    file: &Path,
    state_dir: &Path,
    machine: Option<&str>,
) -> Result<(), String> {
    let config = parse_and_validate(file)?;
    let order = resolver::build_execution_order(&config)?;
    let locks = load_machine_locks(&config, state_dir, machine)?;
    let plan = planner::plan(&config, &order, &locks, None);

    let creates = plan
        .changes
        .iter()
        .filter(|c| c.action == types::PlanAction::Create)
        .count();
    let updates = plan
        .changes
        .iter()
        .filter(|c| c.action == types::PlanAction::Update)
        .count();
    let deletes = plan
        .changes
        .iter()
        .filter(|c| c.action == types::PlanAction::Destroy)
        .count();
    let noops = plan
        .changes
        .iter()
        .filter(|c| c.action == types::PlanAction::NoOp)
        .count();

    println!("Dry run cost estimate:\n");
    println!("  Create:  {creates}");
    println!("  Update:  {updates}");
    println!("  Destroy: {deletes}");
    println!("  No-op:   {noops}");
    println!("  ─────────────");
    println!("  Total changes: {}", creates + updates + deletes);
    Ok(())
}

/// forjar#374: the fleet leg's single confirmation. EOF (a closed stdin, as in
/// CI) reads as "no", the same rule `apply_preflight` uses per machine.
fn confirm_fleet_rollout(remaining: usize) -> Result<(), String> {
    eprint!("Apply to {remaining} remaining machine(s)? [y/N] ");
    let mut answer = String::new();
    std::io::stdin()
        .read_line(&mut answer)
        .map_err(|e| format!("stdin error: {e}"))?;
    if !answer.trim().eq_ignore_ascii_case("y") {
        return Err("aborted by user".to_string());
    }
    Ok(())
}