nornir 0.4.28

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
436
437
438
439
440
441
442
443
//! AI-agent guard rails.
//!
//! Enforces the `[guard].forbidden` list from `nornir.toml` at the
//! filesystem level via `chmod -w`. A misbehaving agent (or a tired
//! human) trying to edit a protected file gets `EACCES` rather than
//! silently corrupting append-only history or generated docs.
//!
//! Operations:
//! - [`apply`]   — chmod -w on every forbidden path that exists
//! - [`release`] — chmod +w on every forbidden path (for intentional edits)
//! - [`status`]  — report current writable bit for each path
//!
//! Tamper-evidence (lock-down integrity):
//! - [`manifest`]      — snapshot {exists, mode, sha256} per forbidden path
//! - [`write_manifest`]/[`read_manifest`] — persist/load the snapshot
//! - [`verify`]        — recompute and diff against a recorded manifest
//! - [`intact`]        — gate form: `Err` if any drift (perm or content)
//! - [`policy_json`]   — host-consumable forbidden-list export
//!
//! `chmod -w` is advisory: the same agent that holds the bit can flip it
//! back. The manifest makes such tampering **non-deniable** — a release
//! gate (`Gates.guard_intact`) recomputes the hashes and fails if a
//! protected file's permissions or contents drifted out of band.
//!
//! All paths in the `forbidden` list are interpreted relative to the
//! supplied `workspace_root` (typically the dir containing
//! `workspace_holger/`, `holger/`, `znippy/`, ...).

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use sha2::{Digest, Sha256};

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PathStatus {
    pub path: PathBuf,
    pub exists: bool,
    pub writable: bool,
    pub changed: bool,
}

pub fn status(workspace_root: &Path, forbidden: &[String]) -> Vec<PathStatus> {
    forbidden
        .iter()
        .map(|rel| {
            let p = workspace_root.join(rel);
            let (exists, writable) = inspect(&p);
            PathStatus { path: p, exists, writable, changed: false }
        })
        .collect()
}

pub fn apply(workspace_root: &Path, forbidden: &[String]) -> Result<Vec<PathStatus>> {
    chmod_each(workspace_root, forbidden, false)
}

pub fn release(workspace_root: &Path, forbidden: &[String]) -> Result<Vec<PathStatus>> {
    chmod_each(workspace_root, forbidden, true)
}

fn inspect(p: &Path) -> (bool, bool) {
    match std::fs::metadata(p) {
        Ok(m) => (true, !m.permissions().readonly()),
        Err(_) => (false, false),
    }
}

#[cfg(unix)]
fn chmod_each(
    workspace_root: &Path,
    forbidden: &[String],
    writable: bool,
) -> Result<Vec<PathStatus>> {
    use std::os::unix::fs::PermissionsExt;
    let mut out = Vec::new();
    for rel in forbidden {
        let p = workspace_root.join(rel);
        if !p.exists() {
            out.push(PathStatus { path: p, exists: false, writable: false, changed: false });
            continue;
        }
        let meta = std::fs::metadata(&p)
            .with_context(|| format!("stat {}", p.display()))?;
        let before = !meta.permissions().readonly();
        let mut perms = meta.permissions();
        let mode = perms.mode();
        let new_mode = if writable {
            mode | 0o200 // u+w
        } else {
            mode & !0o222 // strip write everywhere
        };
        perms.set_mode(new_mode);
        std::fs::set_permissions(&p, perms)
            .with_context(|| format!("chmod {}", p.display()))?;
        let (_, after) = inspect(&p);
        out.push(PathStatus {
            path: p,
            exists: true,
            writable: after,
            changed: before != after,
        });
    }
    Ok(out)
}

#[cfg(not(unix))]
fn chmod_each(
    workspace_root: &Path,
    forbidden: &[String],
    writable: bool,
) -> Result<Vec<PathStatus>> {
    let mut out = Vec::new();
    for rel in forbidden {
        let p = workspace_root.join(rel);
        if !p.exists() {
            out.push(PathStatus { path: p, exists: false, writable: false, changed: false });
            continue;
        }
        let meta = std::fs::metadata(&p)?;
        let before = !meta.permissions().readonly();
        let mut perms = meta.permissions();
        perms.set_readonly(!writable);
        std::fs::set_permissions(&p, perms)?;
        let (_, after) = inspect(&p);
        out.push(PathStatus {
            path: p,
            exists: true,
            writable: after,
            changed: before != after,
        });
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// Tamper-evidence: manifest, verify, policy export.
// ---------------------------------------------------------------------------

/// Recorded state of one forbidden path at `guard_apply` time.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ManifestEntry {
    /// Workspace-root-relative path, exactly as listed in `[guard].forbidden`.
    pub rel: String,
    pub exists: bool,
    /// True if the path is a directory (content is not hashed).
    pub is_dir: bool,
    /// Unix permission bits (`st_mode & 0o7777`). `0` on non-unix.
    pub mode: u32,
    /// Lowercase hex sha256 of file contents; `None` for dirs/missing.
    pub sha256: Option<String>,
}

/// A snapshot of every forbidden path, persisted so later drift is
/// non-deniable. Append-only by convention: each `guard_apply` rewrites
/// it, but the warehouse/git history retains prior versions.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Manifest {
    pub recorded_at: chrono::DateTime<chrono::Utc>,
    pub entries: Vec<ManifestEntry>,
}

/// What changed for one path between the recorded manifest and now.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum Drift {
    /// Recorded as existing, now gone.
    Vanished,
    /// Recorded as absent, now present.
    Appeared,
    /// Permission bits changed (e.g. someone re-granted write).
    Mode { recorded: u32, current: u32 },
    /// File contents changed (sha256 mismatch).
    Content { recorded: Option<String>, current: Option<String> },
}

/// Per-path verification result.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct VerifyStatus {
    pub rel: String,
    pub drift: Vec<Drift>,
}

impl VerifyStatus {
    pub fn ok(&self) -> bool {
        self.drift.is_empty()
    }
}

/// Canonical on-disk location of the persisted manifest.
pub fn manifest_path(workspace_root: &Path) -> PathBuf {
    workspace_root.join(".nornir").join("guard-manifest.json")
}

/// Canonical on-disk location of the host-consumable policy export.
pub fn policy_path(workspace_root: &Path) -> PathBuf {
    workspace_root.join(".nornir").join("guard-policy.json")
}

/// Compute a fresh manifest for the forbidden set (does not write it).
pub fn manifest(workspace_root: &Path, forbidden: &[String]) -> Manifest {
    let entries = forbidden
        .iter()
        .map(|rel| entry_for(&workspace_root.join(rel), rel))
        .collect();
    Manifest { recorded_at: chrono::Utc::now(), entries }
}

fn entry_for(abs: &Path, rel: &str) -> ManifestEntry {
    match std::fs::symlink_metadata(abs) {
        Err(_) => ManifestEntry { rel: rel.to_string(), exists: false, is_dir: false, mode: 0, sha256: None },
        Ok(meta) => {
            let is_dir = meta.is_dir();
            let mode = mode_of(&meta);
            let sha256 = if is_dir || meta.file_type().is_symlink() {
                None
            } else {
                sha256_file(abs).ok()
            };
            ManifestEntry { rel: rel.to_string(), exists: true, is_dir, mode, sha256 }
        }
    }
}

#[cfg(unix)]
fn mode_of(meta: &std::fs::Metadata) -> u32 {
    use std::os::unix::fs::PermissionsExt;
    meta.permissions().mode() & 0o7777
}

#[cfg(not(unix))]
fn mode_of(meta: &std::fs::Metadata) -> u32 {
    if meta.permissions().readonly() { 0o444 } else { 0o644 }
}

fn sha256_file(path: &Path) -> Result<String> {
    let bytes = std::fs::read(path).with_context(|| format!("read {}", path.display()))?;
    let mut h = Sha256::new();
    h.update(&bytes);
    Ok(hex_encode(&h.finalize()))
}

fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut s = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        s.push(HEX[(b >> 4) as usize] as char);
        s.push(HEX[(b & 0x0f) as usize] as char);
    }
    s
}

/// Persist a manifest to `manifest_path(workspace_root)` (creates `.nornir/`).
pub fn write_manifest(workspace_root: &Path, m: &Manifest) -> Result<PathBuf> {
    let path = manifest_path(workspace_root);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("mkdir {}", parent.display()))?;
    }
    let json = serde_json::to_string_pretty(m).context("serialize guard manifest")?;
    std::fs::write(&path, json).with_context(|| format!("write {}", path.display()))?;
    Ok(path)
}

/// Load a previously written manifest.
pub fn read_manifest(workspace_root: &Path) -> Result<Manifest> {
    let path = manifest_path(workspace_root);
    let text = std::fs::read_to_string(&path)
        .with_context(|| format!("read guard manifest {} (run guard_apply first)", path.display()))?;
    serde_json::from_str(&text).with_context(|| format!("parse {}", path.display()))
}

/// Recompute current state and diff it against `recorded`. Returns one
/// [`VerifyStatus`] per recorded entry (drift empty == intact).
pub fn verify(workspace_root: &Path, recorded: &Manifest) -> Vec<VerifyStatus> {
    recorded
        .entries
        .iter()
        .map(|rec| {
            let cur = entry_for(&workspace_root.join(&rec.rel), &rec.rel);
            let mut drift = Vec::new();
            match (rec.exists, cur.exists) {
                (true, false) => drift.push(Drift::Vanished),
                (false, true) => drift.push(Drift::Appeared),
                (false, false) => {}
                (true, true) => {
                    if rec.mode != cur.mode {
                        drift.push(Drift::Mode { recorded: rec.mode, current: cur.mode });
                    }
                    if !rec.is_dir && !cur.is_dir && rec.sha256 != cur.sha256 {
                        drift.push(Drift::Content {
                            recorded: rec.sha256.clone(),
                            current: cur.sha256.clone(),
                        });
                    }
                }
            }
            VerifyStatus { rel: rec.rel.clone(), drift }
        })
        .collect()
}

/// Gate form of [`verify`]: `Ok(())` if every path is intact, else an
/// `Err` naming the drifted paths. Suitable for a release gate.
pub fn intact(workspace_root: &Path, recorded: &Manifest) -> Result<()> {
    let report = verify(workspace_root, recorded);
    let drifted: Vec<&VerifyStatus> = report.iter().filter(|v| !v.ok()).collect();
    if drifted.is_empty() {
        return Ok(());
    }
    let detail = drifted
        .iter()
        .map(|v| format!("{} ({} drift)", v.rel, v.drift.len()))
        .collect::<Vec<_>>()
        .join(", ");
    anyhow::bail!("guard manifest drift on {} path(s): {detail}", drifted.len())
}

/// Host-consumable policy: the forbidden list + the manifest path, so an
/// agent runtime or sibling MCP can be configured to deny writes.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Policy {
    pub forbidden: Vec<String>,
    pub manifest: PathBuf,
    pub note: String,
}

/// Build and write `guard-policy.json` next to the manifest.
pub fn write_policy(workspace_root: &Path, forbidden: &[String]) -> Result<PathBuf> {
    let policy = Policy {
        forbidden: forbidden.to_vec(),
        manifest: manifest_path(workspace_root),
        note: "Paths are workspace-root-relative and chmod -w by nornir guard. \
               Deny writes from agent runtimes; nornir's guard_intact gate verifies \
               sha256+mode at release time."
            .to_string(),
    };
    let path = policy_path(workspace_root);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("mkdir {}", parent.display()))?;
    }
    let json = serde_json::to_string_pretty(&policy).context("serialize guard policy")?;
    std::fs::write(&path, json).with_context(|| format!("write {}", path.display()))?;
    Ok(path)
}

/// Convenience for `guard_apply`: chmod -w, snapshot a manifest, export
/// the policy file. Returns the per-path chmod report.
pub fn apply_and_record(workspace_root: &Path, forbidden: &[String]) -> Result<Vec<PathStatus>> {
    let report = apply(workspace_root, forbidden)?;
    let m = manifest(workspace_root, forbidden);
    write_manifest(workspace_root, &m)?;
    write_policy(workspace_root, forbidden)?;
    Ok(report)
}

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

    fn write(p: &Path, s: &str) {
        std::fs::write(p, s).unwrap();
    }

    #[test]
    fn manifest_then_verify_clean() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write(&root.join("a.txt"), "hello");
        std::fs::create_dir(root.join("d")).unwrap();
        let forbidden = vec!["a.txt".to_string(), "d".to_string(), "missing.txt".to_string()];
        let m = manifest(root, &forbidden);
        let report = verify(root, &m);
        assert!(report.iter().all(|v| v.ok()), "freshly recorded tree must be intact");
        assert!(intact(root, &m).is_ok());
    }

    #[test]
    fn verify_detects_content_drift() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write(&root.join("a.txt"), "hello");
        let forbidden = vec!["a.txt".to_string()];
        let m = manifest(root, &forbidden);
        write(&root.join("a.txt"), "tampered");
        let report = verify(root, &m);
        let a = report.iter().find(|v| v.rel == "a.txt").unwrap();
        assert!(matches!(a.drift.as_slice(), [Drift::Content { .. }]));
        assert!(intact(root, &m).is_err());
    }

    #[test]
    fn verify_detects_vanish_and_appear() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write(&root.join("a.txt"), "hi");
        let forbidden = vec!["a.txt".to_string(), "later.txt".to_string()];
        let m = manifest(root, &forbidden);
        std::fs::remove_file(root.join("a.txt")).unwrap();
        write(&root.join("later.txt"), "now here");
        let report = verify(root, &m);
        let a = report.iter().find(|v| v.rel == "a.txt").unwrap();
        let l = report.iter().find(|v| v.rel == "later.txt").unwrap();
        assert!(matches!(a.drift.as_slice(), [Drift::Vanished]));
        assert!(matches!(l.drift.as_slice(), [Drift::Appeared]));
    }

    #[cfg(unix)]
    #[test]
    fn verify_detects_mode_drift() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let f = root.join("a.txt");
        write(&f, "x");
        let mut perms = std::fs::metadata(&f).unwrap().permissions();
        perms.set_mode(0o444);
        std::fs::set_permissions(&f, perms).unwrap();
        let forbidden = vec!["a.txt".to_string()];
        let m = manifest(root, &forbidden);
        // Re-grant write (the classic tamper).
        let mut perms = std::fs::metadata(&f).unwrap().permissions();
        perms.set_mode(0o644);
        std::fs::set_permissions(&f, perms).unwrap();
        let report = verify(root, &m);
        let a = report.iter().find(|v| v.rel == "a.txt").unwrap();
        assert!(a.drift.iter().any(|d| matches!(d, Drift::Mode { .. })));
    }

    #[test]
    fn write_and_read_manifest_roundtrips() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        write(&root.join("a.txt"), "hello");
        let forbidden = vec!["a.txt".to_string()];
        let report = apply_and_record(root, &forbidden).unwrap();
        assert_eq!(report.len(), 1);
        assert!(manifest_path(root).exists());
        assert!(policy_path(root).exists());
        let loaded = read_manifest(root).unwrap();
        assert!(intact(root, &loaded).is_ok());
    }
}