nap-core 0.3.11

Core library for the Narrative Addressing Protocol
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Application-layer ACL for directory and file paths in a Lore workspace.
//!
//! ## Why app-layer and not VCS-layer
//!
//! Lore's stock server has no native path-level access control.  Instead,
//! NAP enforces ACLs at the application layer by intercepting file read/
//! write calls after they pass through the Lore VCS.  This keeps the
//! loreserver simple and allows NAP to implement rich rules (prefix
//! patterns, deny-overrides, role expansion) without server changes.
//!
//! ## Design
//!
//! [`PermissionGate`] is constructed with a set of [`Permission`] rules.
//! Every request to read or write a path is checked against the ruleset:
//!
//! 1. If an explicit `Deny` matches the path, the request is **rejected**.
//! 2. If a `Write` (or `Read`) matches, the request is **allowed**.
//! 3. No match → **denied by default** (fail-closed).
//!
//! Rules are stored in `context/nap-gate.toml` inside the workspace and
//! loaded on [`PermissionGate::load`].
//!
//! ## Future
//!
//! In a future iteration this may read from `lore file metadata` or from
//! a dedicated ACL API, but for v0 the file-based approach gives us a
//! portable, inspectable ACL that works without server changes.

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

use serde::{Deserialize, Serialize};

use crate::error::NapError;
use crate::vcs::{AccessLevel, Permission};

// ---------------------------------------------------------------------------
// Gate configuration (serialised to context/nap-gate.toml)
// ---------------------------------------------------------------------------

/// On-disk format for the permission gate config.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct GateConfig {
    /// Default access level when no rules match.
    #[serde(default = "default_deny")]
    default: String,
    /// Ordered list of access rules.
    #[serde(default)]
    rules: Vec<GateRule>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct GateRule {
    /// Glob or prefix pattern (e.g. `agents/**` or `context/`).
    path: String,
    /// Principal (user or role) this rule applies to.
    principal: String,
    /// Access level: "read", "write", or "deny".
    access: String,
}

fn default_deny() -> String {
    "deny".to_string()
}

// ---------------------------------------------------------------------------
// PermissionGate
// ---------------------------------------------------------------------------

/// Application-layer access-control gate for Lore workspace paths.
///
/// ## Usage
///
/// ```ignore
/// let gate = PermissionGate::load(workspace_path).await?;
/// gate.check_read("/context/secret.md", "alice")?;     // Err if denied
/// gate.check_write("/entities/characters/bob.yaml", "alice")?; // Err if denied
/// ```
///
/// ## Thread safety
///
/// `PermissionGate` is immutable after construction and safe to share
/// across threads (immutable `&self` check methods).
#[derive(Debug)]
pub struct PermissionGate {
    /// Workspace root path (resolves relative rules).
    workspace_root: PathBuf,
    /// Parsed rules keyed by (canonicalised prefix, principal).
    /// The vec is searched in order; first match wins.
    rules: Vec<(PathBuf, String, AccessLevel)>,
    /// Cached access-level decisions for hot paths.
    /// Stores the granted `AccessLevel` for a (path, principal) pair.
    cache: std::sync::Mutex<HashMap<(PathBuf, String), AccessLevel>>,
    /// Default access when no rule matches.
    default: AccessLevel,
}

impl PermissionGate {
    /// Load the permission gate from `context/nap-gate.toml` inside the
    /// workspace.  If the file does not exist, returns a permissive gate
    /// (default: write access for all principals).  Use
    /// [`PermissionGate::strict`] to enforce a closed-by-default gate
    /// when no config is present.
    pub fn load(workspace_root: &Path) -> Result<Self, NapError> {
        let config_path = workspace_root.join("context").join("nap-gate.toml");
        if !config_path.exists() {
            // No gate config → permissive (backwards-compatible).
            return Ok(Self {
                workspace_root: workspace_root.to_path_buf(),
                rules: Vec::new(),
                cache: std::sync::Mutex::new(HashMap::new()),
                default: AccessLevel::Write,
            });
        }

        let contents = std::fs::read_to_string(&config_path).map_err(|e| {
            NapError::Other(format!(
                "failed to read gate config at {:?}: {}",
                config_path, e
            ))
        })?;

        let config: GateConfig = toml::from_str(&contents).map_err(|e| {
            NapError::Other(format!(
                "failed to parse gate config at {:?}: {}",
                config_path, e
            ))
        })?;

        let default = match config.default.as_str() {
            "read" => AccessLevel::Read,
            "write" => AccessLevel::Write,
            "deny" => AccessLevel::None,
            other => {
                return Err(NapError::Other(format!(
                    "unknown default access level '{}' in gate config at {:?}",
                    other, config_path
                )));
            }
        };

        let mut rules: Vec<(PathBuf, String, AccessLevel)> = Vec::new();
        for rule in &config.rules {
            let access = match rule.access.as_str() {
                "read" => AccessLevel::Read,
                "write" => AccessLevel::Write,
                "deny" | "none" => AccessLevel::None,
                other => {
                    return Err(NapError::Other(format!(
                        "unknown access level '{}' in rule for path '{}'",
                        other, rule.path
                    )));
                }
            };
            rules.push((PathBuf::from(&rule.path), rule.principal.clone(), access));
        }

        Ok(Self {
            workspace_root: workspace_root.to_path_buf(),
            rules,
            cache: std::sync::Mutex::new(HashMap::new()),
            default,
        })
    }

    /// Create a strict gate that denies everything by default, even
    /// when no config file is present.  Useful for agents or untrusted
    /// contexts.
    pub fn strict(workspace_root: &Path) -> Self {
        Self {
            workspace_root: workspace_root.to_path_buf(),
            rules: Vec::new(),
            cache: std::sync::Mutex::new(HashMap::new()),
            default: AccessLevel::None,
        }
    }

    /// Create a fully permissive gate (any principal may read/write any
    /// path).  Useful for local development or trusted automation.
    pub fn permissive(workspace_root: &Path) -> Self {
        Self {
            workspace_root: workspace_root.to_path_buf(),
            rules: Vec::new(),
            cache: std::sync::Mutex::new(HashMap::new()),
            default: AccessLevel::Write,
        }
    }

    /// Build a gate from an explicit list of [`Permission`] entries.
    pub fn from_permissions(
        workspace_root: &Path,
        permissions: &[Permission],
        default: AccessLevel,
    ) -> Self {
        let rules: Vec<(PathBuf, String, AccessLevel)> = permissions
            .iter()
            .map(|p| (PathBuf::from(&p.path_prefix), p.principal.clone(), p.access))
            .collect();

        Self {
            workspace_root: workspace_root.to_path_buf(),
            rules,
            cache: std::sync::Mutex::new(HashMap::new()),
            default,
        }
    }

    /// Check whether `principal` may read `path`.
    pub fn check_read(&self, path: &str, principal: &str) -> Result<(), NapError> {
        self.check(path, principal, AccessLevel::Read)
    }

    /// Check whether `principal` may write `path`.
    pub fn check_write(&self, path: &str, principal: &str) -> Result<(), NapError> {
        self.check(path, principal, AccessLevel::Write)
    }

    /// Core check: does the rule set grant `required` access for `principal`
    /// on `path`?
    fn check(&self, path: &str, principal: &str, required: AccessLevel) -> Result<(), NapError> {
        let cache_key = (PathBuf::from(path), principal.to_string());
        {
            let cache = self.cache.lock().unwrap();
            if let Some(&granted) = cache.get(&cache_key) {
                // Cache hit: check if the cached access level satisfies
                // the required level (Write implies Read).
                if granted == AccessLevel::Write {
                    return Ok(());
                }
                if granted == AccessLevel::Read && required == AccessLevel::Read {
                    return Ok(());
                }
                return Err(NapError::PermissionDenied(format!(
                    "access denied to '{}' for '{}' (cached)",
                    path, principal
                )));
            }
        }

        let result = self.check_uncached(path, principal, required);
        // Cache the granted access level (determined by re-checking with Read).
        let granted = self
            .check_uncached(path, principal, AccessLevel::Read)
            .map(|_| {
                // Check if Write is also granted.
                if self
                    .check_uncached(path, principal, AccessLevel::Write)
                    .is_ok()
                {
                    AccessLevel::Write
                } else {
                    AccessLevel::Read
                }
            })
            .unwrap_or(AccessLevel::None);

        {
            let mut cache = self.cache.lock().unwrap();
            cache.insert(cache_key, granted);
        }

        result
    }

    fn check_uncached(
        &self,
        path: &str,
        principal: &str,
        required: AccessLevel,
    ) -> Result<(), NapError> {
        // Normalize paths: strip leading `/` so `Path::join` works
        // correctly on all platforms (macOS treats `/public` as root).
        let norm_path = path.strip_prefix('/').unwrap_or(path);
        let norm_prefix = |p: &Path| -> PathBuf {
            let s = p.to_string_lossy();
            let relative = s.strip_prefix('/').unwrap_or(&s);
            self.workspace_root.join(relative)
        };

        let request_path = self.workspace_root.join(norm_path);

        // Collect all matching rules and pick the one with the longest
        // (most specific) prefix.  This way a `Write` rule on
        // `entities/characters` overrides a `Read` rule on `entities`.
        let mut best_match: Option<(usize, &AccessLevel)> = None;
        let mut best_prefix_len: usize = 0;

        for (rule_prefix, rule_principal, rule_access) in &self.rules {
            let prefix = norm_prefix(rule_prefix);

            if !request_path.starts_with(&prefix) {
                continue;
            }

            if rule_principal != "*" && rule_principal != principal {
                continue;
            }

            let prefix_len = prefix.as_os_str().len();
            if best_match.is_none() || prefix_len > best_prefix_len {
                best_match = Some((prefix_len, rule_access));
                best_prefix_len = prefix_len;
            }
        }

        // ── Apply the best (most specific) matching rule ──────────────
        if let Some((_, access)) = best_match {
            match access {
                AccessLevel::None => {
                    return Err(NapError::PermissionDenied(format!(
                        "principal '{}' is denied access to '{}'",
                        principal, path
                    )));
                }
                AccessLevel::Read => {
                    if required == AccessLevel::Write {
                        return Err(NapError::PermissionDenied(format!(
                            "principal '{}' has read-only access to '{}'",
                            principal, path
                        )));
                    }
                    return Ok(());
                }
                AccessLevel::Write => {
                    return Ok(());
                }
            }
        }

        // ── No rule matched → apply default ──────────────────────────
        match self.default {
            AccessLevel::None => Err(NapError::PermissionDenied(format!(
                "principal '{}' is denied access to '{}' (default deny)",
                principal, path
            ))),
            AccessLevel::Read => {
                if required == AccessLevel::Write {
                    return Err(NapError::PermissionDenied(format!(
                        "principal '{}' has read-only access to '{}' (default read)",
                        principal, path
                    )));
                }
                Ok(())
            }
            AccessLevel::Write => Ok(()),
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_permissive_gate_allows_all() {
        let dir = tempfile::TempDir::new().unwrap();
        let gate = PermissionGate::permissive(dir.path());
        assert!(gate.check_read("/any/path", "alice").is_ok());
        assert!(gate.check_write("/any/path", "alice").is_ok());
        assert!(gate.check_write("/any/path", "mallory").is_ok());
    }

    #[test]
    fn test_strict_gate_denies_all() {
        let dir = tempfile::TempDir::new().unwrap();
        let gate = PermissionGate::strict(dir.path());
        assert!(gate.check_read("/any/path", "alice").is_err());
        assert!(gate.check_write("/any/path", "alice").is_err());
    }

    #[test]
    fn test_from_permissions() {
        let dir = tempfile::TempDir::new().unwrap();
        let perms = vec![
            Permission {
                path_prefix: "/public".to_string(),
                principal: "*".to_string(),
                access: AccessLevel::Read,
            },
            Permission {
                path_prefix: "/admin".to_string(),
                principal: "alice".to_string(),
                access: AccessLevel::Write,
            },
        ];
        let gate = PermissionGate::from_permissions(dir.path(), &perms, AccessLevel::None);

        // Public is readable by anyone.
        assert!(gate.check_read("/public/readme.md", "bob").is_ok());
        // But not writable.
        assert!(gate.check_write("/public/readme.md", "bob").is_err());
        // Admin is writeable by alice.
        assert!(gate.check_write("/admin/secret.md", "alice").is_ok());
        // Admin is denied for bob.
        assert!(gate.check_write("/admin/secret.md", "bob").is_err());
        // Default deny path.
        assert!(gate.check_read("/other", "alice").is_err());
    }

    #[test]
    fn test_load_from_file() {
        let dir = tempfile::TempDir::new().unwrap();
        let context_dir = dir.path().join("context");
        fs::create_dir_all(&context_dir).unwrap();

        let config = r#"
default = "deny"

[[rules]]
path = "entities"
principal = "*"
access = "read"

[[rules]]
path = "entities/characters"
principal = "alice"
access = "write"
"#;
        fs::write(context_dir.join("nap-gate.toml"), config).unwrap();

        let gate = PermissionGate::load(dir.path()).unwrap();

        // Everyone can read entities.
        assert!(gate.check_read("entities/foo.yaml", "bob").is_ok());
        // But not write them unless they're alice.
        assert!(gate.check_write("entities/foo.yaml", "bob").is_err());
        assert!(gate.check_write("entities/foo.yaml", "alice").is_err()); // only characters/
        assert!(
            gate.check_write("entities/characters/hero.yaml", "alice")
                .is_ok()
        );
        // Default deny for unconfigured paths.
        assert!(gate.check_read("context/secret.md", "alice").is_err());
    }

    #[test]
    fn test_cache_hits() {
        let dir = tempfile::TempDir::new().unwrap();
        let gate = PermissionGate::permissive(dir.path());

        // First check populates the cache.
        assert!(gate.check_read("/file", "alice").is_ok());
        // Second check hits the cache (won't re-evaluate rules).
        assert!(gate.check_read("/file", "alice").is_ok());
    }

    #[test]
    fn test_cache_miss_different_principal() {
        let dir = tempfile::TempDir::new().unwrap();
        let perms = vec![Permission {
            path_prefix: "/".to_string(),
            principal: "alice".to_string(),
            access: AccessLevel::Write,
        }];
        let gate = PermissionGate::from_permissions(dir.path(), &perms, AccessLevel::None);

        assert!(gate.check_read("/file", "alice").is_ok());
        // Different principal → different cache key → re-evaluated.
        assert!(gate.check_read("/file", "bob").is_err());
    }

    #[test]
    fn test_invalid_config_default() {
        let dir = tempfile::TempDir::new().unwrap();
        let context_dir = dir.path().join("context");
        fs::create_dir_all(&context_dir).unwrap();
        fs::write(
            context_dir.join("nap-gate.toml"),
            r#"default = "superadmin""#,
        )
        .unwrap();

        let result = PermissionGate::load(dir.path());
        assert!(result.is_err());
        assert!(
            result.unwrap_err().to_string().contains("unknown default"),
            "expected 'unknown default' error"
        );
    }
}