structfs-core-store 0.2.0

Core StructFS store traits - Record, Value, Path, Format
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Composable store wrappers: capability restriction, layering, sharing,
//! path confinement, and redaction.

use std::sync::{Arc, Mutex};

use crate::{Error, Path, PathPattern, Reader, Record, Value, Writer};

/// A read-only view of a store: reads pass through, writes are rejected
/// with a `PermissionDenied` error.
///
/// Useful for handing a store to code that should only observe it (display
/// layers, documentation consumers).
pub struct ReadOnly<S>(S);

impl<S> ReadOnly<S> {
    /// Wrap a store in a read-only view.
    pub fn new(inner: S) -> Self {
        Self(inner)
    }

    /// Unwrap, returning the inner store.
    pub fn into_inner(self) -> S {
        self.0
    }
}

impl<S: Reader> Reader for ReadOnly<S> {
    fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
        self.0.read(from)
    }

    fn read_children(&mut self, from: &Path) -> Result<Option<Vec<String>>, Error> {
        self.0.read_children(from)
    }
}

impl<S: Reader> Writer for ReadOnly<S> {
    fn write(&mut self, to: &Path, _data: Record) -> Result<Path, Error> {
        Err(Error::permission_denied(format!(
            "store is read-only (write to {})",
            to
        )))
    }
}

/// A layered store: reads try the primary first, then fall back to the
/// secondary; writes always go to the primary.
///
/// This is layering (like an overlay filesystem), distinct from
/// `OverlayStore`, which *routes* by path prefix. Typical use: runtime
/// overrides cascading over immutable defaults.
pub struct Cascade<A, B> {
    primary: A,
    fallback: B,
}

impl<A, B> Cascade<A, B> {
    /// Layer `primary` over `fallback`.
    pub fn new(primary: A, fallback: B) -> Self {
        Self { primary, fallback }
    }

    /// Unwrap, returning `(primary, fallback)`.
    pub fn into_inner(self) -> (A, B) {
        (self.primary, self.fallback)
    }
}

impl<A: Reader, B: Reader> Reader for Cascade<A, B> {
    fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
        match self.primary.read(from)? {
            Some(record) => Ok(Some(record)),
            None => self.fallback.read(from),
        }
    }

    fn read_children(&mut self, from: &Path) -> Result<Option<Vec<String>>, Error> {
        match self.primary.read_children(from)? {
            Some(children) => Ok(Some(children)),
            None => self.fallback.read_children(from),
        }
    }
}

impl<A: Writer, B: Send + Sync> Writer for Cascade<A, B> {
    fn write(&mut self, to: &Path, data: Record) -> Result<Path, Error> {
        self.primary.write(to, data)
    }
}

/// A cloneable, shareable handle to a store.
///
/// `Reader`/`Writer` take `&mut self`, so sharing a store between owners
/// requires a lock. `Shared` is that lock, packaged: it implements the
/// store traits over `Arc<Mutex<S>>` so callers don't hand-roll the
/// wrapper. Lock poisoning is recovered from (the store may be mid-update,
/// but path-level operations are individually atomic).
pub struct Shared<S> {
    inner: Arc<Mutex<S>>,
}

impl<S> Shared<S> {
    /// Wrap a store for shared access.
    pub fn new(inner: S) -> Self {
        Self {
            inner: Arc::new(Mutex::new(inner)),
        }
    }

    /// Access the underlying store directly.
    pub fn lock(&self) -> std::sync::MutexGuard<'_, S> {
        self.inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }
}

impl<S> Clone for Shared<S> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<S: Reader> Reader for Shared<S> {
    fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
        self.lock().read(from)
    }

    fn read_children(&mut self, from: &Path) -> Result<Option<Vec<String>>, Error> {
        self.lock().read_children(from)
    }
}

impl<S: Writer> Writer for Shared<S> {
    fn write(&mut self, to: &Path, data: Record) -> Result<Path, Error> {
        self.lock().write(to, data)
    }
}

/// A store that redacts sensitive paths on read.
///
/// Paths matching any pattern read back as the mask value instead of
/// their contents; existence is preserved (a masked path that exists
/// reads `Some(mask)`, a missing one reads `None`). Writes pass through
/// unchanged — masking is a read-side lens, not write protection (wrap
/// in [`ReadOnly`] for that).
///
/// Matching is **component-wise** via [`PathPattern`]: masking
/// `gate/api_key` does not mask `gate/api_key_other`, which a string
/// prefix check would.
pub struct Masked<S> {
    inner: S,
    patterns: Vec<PathPattern>,
    mask: Value,
}

impl<S> Masked<S> {
    /// Mask paths matching `patterns` with the default `"[masked]"`.
    pub fn new(inner: S, patterns: Vec<PathPattern>) -> Self {
        Self::with_mask(inner, patterns, Value::from("[masked]"))
    }

    /// Mask with a custom mask value.
    pub fn with_mask(inner: S, patterns: Vec<PathPattern>, mask: Value) -> Self {
        Self {
            inner,
            patterns,
            mask,
        }
    }

    /// Unwrap, returning the inner store.
    pub fn into_inner(self) -> S {
        self.inner
    }

    fn is_masked(&self, path: &Path) -> bool {
        self.patterns.iter().any(|pattern| pattern.matches(path))
    }
}

impl<S: Reader> Reader for Masked<S> {
    fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
        if self.is_masked(from) {
            // Preserve existence, redact content.
            return Ok(self
                .inner
                .read(from)?
                .map(|_| Record::parsed(self.mask.clone())));
        }
        self.inner.read(from)
    }

    fn read_children(&mut self, from: &Path) -> Result<Option<Vec<String>>, Error> {
        // Child names are structure, not content; they stay visible even
        // under a masked prefix.
        self.inner.read_children(from)
    }
}

impl<S: Writer> Writer for Masked<S> {
    fn write(&mut self, to: &Path, data: Record) -> Result<Path, Error> {
        self.inner.write(to, data)
    }
}

/// A store confined to a subtree of another store.
///
/// Incoming paths are joined under `root` before reaching the inner store,
/// and result paths from writes have the root stripped (component-wise)
/// before being returned, so the root never leaks to callers. A write
/// result that escapes the root is an error rather than a leak.
pub struct Rooted<S> {
    root: Path,
    inner: S,
}

impl<S> Rooted<S> {
    /// Confine `inner` to the subtree at `root`.
    pub fn new(root: Path, inner: S) -> Self {
        Self { root, inner }
    }

    /// Unwrap, returning the inner store.
    pub fn into_inner(self) -> S {
        self.inner
    }
}

impl<S: Reader> Reader for Rooted<S> {
    fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
        self.inner.read(&self.root.join(from))
    }

    fn read_children(&mut self, from: &Path) -> Result<Option<Vec<String>>, Error> {
        self.inner.read_children(&self.root.join(from))
    }
}

impl<S: Writer> Writer for Rooted<S> {
    fn write(&mut self, to: &Path, data: Record) -> Result<Path, Error> {
        let result = self.inner.write(&self.root.join(to), data)?;
        result.strip_prefix(&self.root).ok_or_else(|| {
            Error::store(
                "rooted",
                "write",
                format!("inner store returned path outside root: {}", result),
            )
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{path, Value};
    use std::collections::HashMap;

    struct MapStore {
        data: HashMap<Path, Record>,
    }

    impl MapStore {
        fn new() -> Self {
            Self {
                data: HashMap::new(),
            }
        }
    }

    impl Reader for MapStore {
        fn read(&mut self, from: &Path) -> Result<Option<Record>, Error> {
            Ok(self.data.get(from).cloned())
        }
    }

    impl Writer for MapStore {
        fn write(&mut self, to: &Path, data: Record) -> Result<Path, Error> {
            self.data.insert(to.clone(), data);
            Ok(to.clone())
        }
    }

    #[test]
    fn read_only_passes_reads_rejects_writes() {
        let mut inner = MapStore::new();
        inner
            .write(&path!("key"), Record::parsed(Value::from("v")))
            .unwrap();

        let mut ro = ReadOnly::new(inner);
        assert!(ro.read(&path!("key")).unwrap().is_some());

        let err = ro
            .write(&path!("key"), Record::parsed(Value::from("w")))
            .unwrap_err();
        assert!(matches!(err, Error::PermissionDenied { .. }));

        // Inner store unchanged
        let mut inner = ro.into_inner();
        assert_eq!(
            inner.read(&path!("key")).unwrap().unwrap().as_value(),
            Some(&Value::from("v"))
        );
    }

    #[test]
    fn cascade_layers_reads_and_writes_to_primary() {
        let mut fallback = MapStore::new();
        fallback
            .write(&path!("base"), Record::parsed(Value::from("default")))
            .unwrap();
        fallback
            .write(&path!("both"), Record::parsed(Value::from("under")))
            .unwrap();

        let mut primary = MapStore::new();
        primary
            .write(&path!("both"), Record::parsed(Value::from("over")))
            .unwrap();

        let mut cascade = Cascade::new(primary, fallback);

        // Fallback shows through where primary has nothing
        assert_eq!(
            cascade.read(&path!("base")).unwrap().unwrap().as_value(),
            Some(&Value::from("default"))
        );
        // Primary wins where both exist
        assert_eq!(
            cascade.read(&path!("both")).unwrap().unwrap().as_value(),
            Some(&Value::from("over"))
        );
        // Missing everywhere
        assert!(cascade.read(&path!("missing")).unwrap().is_none());

        // Writes land in primary only
        cascade
            .write(&path!("new"), Record::parsed(Value::from("x")))
            .unwrap();
        let (mut primary, mut fallback) = cascade.into_inner();
        assert!(primary.read(&path!("new")).unwrap().is_some());
        assert!(fallback.read(&path!("new")).unwrap().is_none());
    }

    #[test]
    fn shared_clones_access_same_store() {
        let shared = Shared::new(MapStore::new());
        let mut a = shared.clone();
        let mut b = shared;

        a.write(&path!("key"), Record::parsed(Value::from("v")))
            .unwrap();
        assert!(b.read(&path!("key")).unwrap().is_some());
    }

    #[test]
    fn shared_is_send_and_usable_across_threads() {
        let shared = Shared::new(MapStore::new());
        let mut clone = shared.clone();
        let handle = std::thread::spawn(move || {
            clone
                .write(&path!("from_thread"), Record::parsed(Value::from(1i64)))
                .unwrap();
        });
        handle.join().unwrap();
        assert!(shared.lock().read(&path!("from_thread")).unwrap().is_some());
    }

    #[test]
    fn masked_redacts_component_wise() {
        let mut inner = MapStore::new();
        inner
            .write(
                &path!("gate/api_key"),
                Record::parsed(Value::from("s3cret")),
            )
            .unwrap();
        inner
            .write(
                &path!("gate/api_key_other"),
                Record::parsed(Value::from("visible")),
            )
            .unwrap();
        inner
            .write(&path!("gate/model"), Record::parsed(Value::from("gpt-oss")))
            .unwrap();

        let mut masked = Masked::new(inner, vec![PathPattern::prefix(path!("gate/api_key"))]);

        // The secret reads as the mask; existence is preserved.
        assert_eq!(
            masked
                .read(&path!("gate/api_key"))
                .unwrap()
                .unwrap()
                .as_value(),
            Some(&Value::from("[masked]"))
        );
        // The byte-prefix bug: a component-wise sibling stays visible.
        assert_eq!(
            masked
                .read(&path!("gate/api_key_other"))
                .unwrap()
                .unwrap()
                .as_value(),
            Some(&Value::from("visible"))
        );
        // Unmasked paths pass through.
        assert_eq!(
            masked
                .read(&path!("gate/model"))
                .unwrap()
                .unwrap()
                .as_value(),
            Some(&Value::from("gpt-oss"))
        );
        // Missing masked paths stay absent — no fabricated existence.
        assert!(masked.read(&path!("gate/api_key/sub")).unwrap().is_none());
    }

    #[test]
    fn masked_passes_writes_through() {
        let inner = MapStore::new();
        let mut masked = Masked::with_mask(
            inner,
            vec![PathPattern::exact(path!("secret"))],
            Value::Null,
        );
        masked
            .write(&path!("secret"), Record::parsed(Value::from("v")))
            .unwrap();
        // Read of the freshly written secret is masked (custom mask).
        assert_eq!(
            masked.read(&path!("secret")).unwrap().unwrap().as_value(),
            Some(&Value::Null)
        );
        // The inner store holds the real value.
        let mut inner = masked.into_inner();
        assert_eq!(
            inner.read(&path!("secret")).unwrap().unwrap().as_value(),
            Some(&Value::from("v"))
        );
    }

    #[test]
    fn rooted_confines_and_strips() {
        let mut rooted = Rooted::new(path!("export/v1"), MapStore::new());

        let result = rooted
            .write(&path!("users/alice"), Record::parsed(Value::from("a")))
            .unwrap();
        // Root is stripped from the result path
        assert_eq!(result, path!("users/alice"));

        // Data actually lives under the root
        let mut inner = rooted.into_inner();
        assert!(inner
            .read(&path!("export/v1/users/alice"))
            .unwrap()
            .is_some());
    }

    #[test]
    fn rooted_reads_under_root() {
        let mut inner = MapStore::new();
        inner
            .write(&path!("jail/key"), Record::parsed(Value::from("v")))
            .unwrap();

        let mut rooted = Rooted::new(path!("jail"), inner);
        assert!(rooted.read(&path!("key")).unwrap().is_some());
        // Sibling paths outside the root are unreachable
        assert!(rooted.read(&path!("jail/key")).unwrap().is_none());
    }

    #[test]
    fn rooted_escaping_write_result_is_error() {
        /// Store whose write returns a path outside the requested subtree.
        struct EscapingStore;

        impl Reader for EscapingStore {
            fn read(&mut self, _from: &Path) -> Result<Option<Record>, Error> {
                Ok(None)
            }
        }

        impl Writer for EscapingStore {
            fn write(&mut self, _to: &Path, _data: Record) -> Result<Path, Error> {
                Ok(path!("elsewhere/entirely"))
            }
        }

        let mut rooted = Rooted::new(path!("jail"), EscapingStore);
        let err = rooted
            .write(&path!("key"), Record::parsed(Value::Null))
            .unwrap_err();
        assert!(err.to_string().contains("outside root"));
    }
}