martensite-plugin 0.14.0

Wasmtime sandboxed plugin runtime for Martensite.
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
//! Capability-based security sandbox for Martensite plugins.
//!
//! Plugins start with no access to host resources. Each permission must be
//! explicitly granted through a [`Capability`] before the plugin runtime will
//! allow a host call to proceed. Unauthorized calls trap the guest cleanly.

use std::collections::HashSet;
use std::path::PathBuf;

use martensite_reactive::SignalId;

/// A single host resource permission that can be granted to a plugin.
///
/// Capabilities are compared by value, so two grants for the same signal or the
/// same filesystem path are equivalent.
///
/// # Examples
///
/// ```
/// use martensite_plugin::Capability;
/// use std::path::PathBuf;
///
/// let read_asset = Capability::FileRead(PathBuf::from("/assets"));
/// let write_log = Capability::FileWrite(PathBuf::from("/tmp/plugin.log"));
/// let network = Capability::Network;
///
/// assert_ne!(read_asset, network);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Capability {
    /// Permission to read the current value of the given reactive signal.
    SignalRead(SignalId),
    /// Permission to write a new value into the given reactive signal.
    SignalWrite(SignalId),
    /// Permission to read from the given filesystem path.
    FileRead(PathBuf),
    /// Permission to write to the given filesystem path.
    FileWrite(PathBuf),
    /// Permission to open network sockets.
    Network,
}

/// A set of capabilities held by a plugin instance.
///
/// Membership tests are `O(1)` on average.
///
/// # Examples
///
/// ```
/// use martensite_plugin::{Capability, CapabilitySet};
///
/// let mut caps = CapabilitySet::empty();
/// caps.grant(Capability::Network);
/// assert!(caps.contains(&Capability::Network));
/// caps.revoke(&Capability::Network);
/// assert!(!caps.contains(&Capability::Network));
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CapabilitySet(HashSet<Capability>);

impl CapabilitySet {
    /// Creates an empty capability set.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::CapabilitySet;
    ///
    /// let caps = CapabilitySet::empty();
    /// assert!(caps.is_empty());
    /// ```
    pub fn empty() -> Self {
        Self(HashSet::new())
    }

    /// Returns a builder for constructing a capability set fluently.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, CapabilitySet};
    ///
    /// let caps = CapabilitySet::builder().grant(Capability::Network).build();
    /// assert!(caps.contains(&Capability::Network));
    /// ```
    pub fn builder() -> PluginBuilder {
        PluginBuilder::new()
    }

    /// Returns the number of distinct capabilities in the set.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, CapabilitySet};
    ///
    /// let mut caps = CapabilitySet::empty();
    /// assert_eq!(caps.len(), 0);
    /// caps.grant(Capability::Network);
    /// assert_eq!(caps.len(), 1);
    /// ```
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if no capabilities have been granted.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::CapabilitySet;
    ///
    /// let caps = CapabilitySet::empty();
    /// assert!(caps.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Grants a capability, returning `true` if it was newly inserted.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, CapabilitySet};
    ///
    /// let mut caps = CapabilitySet::empty();
    /// assert!(caps.grant(Capability::Network));
    /// assert!(!caps.grant(Capability::Network)); // already granted
    /// ```
    pub fn grant(&mut self, cap: Capability) -> bool {
        self.0.insert(cap)
    }

    /// Revokes a capability, returning `true` if it was present.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, CapabilitySet};
    ///
    /// let mut caps = CapabilitySet::empty();
    /// caps.grant(Capability::Network);
    /// assert!(caps.revoke(&Capability::Network));
    /// assert!(!caps.revoke(&Capability::Network)); // already revoked
    /// ```
    pub fn revoke(&mut self, cap: &Capability) -> bool {
        self.0.remove(cap)
    }

    /// Returns `true` if the capability is currently granted.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, CapabilitySet};
    ///
    /// let mut caps = CapabilitySet::empty();
    /// caps.grant(Capability::Network);
    /// assert!(caps.contains(&Capability::Network));
    /// ```
    pub fn contains(&self, cap: &Capability) -> bool {
        self.0.contains(cap)
    }

    /// Returns `true` if a `file_read` request for `requested_path` is
    /// authorized by any granted [`Capability::FileRead`] entry.
    ///
    /// Authorization is performed by canonicalizing both the granted
    /// roots and the requested path, then requiring the requested path
    /// to be equal to, or descend into, at least one granted root. This
    /// defeats path-traversal attacks (`/assets/../etc/passwd`) that
    /// exact-match checks would otherwise miss when a directory is
    /// granted and a child file is requested.
    ///
    /// When the requested file does not exist on disk (so
    /// [`std::fs::canonicalize`] fails), the path is normalized
    /// lexically via [`std::path::Path::components`] stripping of `.`
    /// and resolving `..` against the granted root, and the prefix
    /// check is applied to the normalized form. This keeps the check
    /// total (no filesystem dependency) while still rejecting `..`
    /// escapes.
    ///
    /// Granting a directory (e.g. `FileRead("/assets")`) authorizes
    /// reads of any file beneath it (e.g. `/assets/textures/foo.png`).
    /// Granting a file authorizes only that exact file.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, CapabilitySet};
    /// use std::path::Path;
    ///
    /// let mut caps = CapabilitySet::empty();
    /// caps.grant(Capability::FileRead("/assets".into()));
    /// assert!(caps.file_read_allowed(Path::new("/assets/foo.txt")));
    /// assert!(!caps.file_read_allowed(Path::new("/etc/passwd")));
    /// ```
    pub fn file_read_allowed(&self, requested_path: &std::path::Path) -> bool {
        self.file_path_allowed(requested_path, true)
    }

    /// Returns `true` if a `file_write` request for `requested_path` is
    /// authorized by any granted [`Capability::FileWrite`] entry.
    /// See [`Self::file_read_allowed`] for canonicalization semantics.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, CapabilitySet};
    /// use std::path::Path;
    ///
    /// let mut caps = CapabilitySet::empty();
    /// caps.grant(Capability::FileWrite("/tmp/log".into()));
    /// assert!(caps.file_write_allowed(Path::new("/tmp/log")));
    /// assert!(!caps.file_write_allowed(Path::new("/etc/passwd")));
    /// ```
    pub fn file_write_allowed(&self, requested_path: &std::path::Path) -> bool {
        self.file_path_allowed(requested_path, false)
    }

    fn file_path_allowed(&self, requested_path: &std::path::Path, read: bool) -> bool {
        let requested_canon = std::fs::canonicalize(requested_path).ok();
        for cap in self.0.iter() {
            let granted = match cap {
                Capability::FileRead(p) if read => p,
                Capability::FileWrite(p) if !read => p,
                _ => continue,
            };
            // Try filesystem canonicalization first (strongest guarantee).
            if let (Some(req_c), Ok(grant_c)) = (&requested_canon, std::fs::canonicalize(granted)) {
                if req_c == &grant_c || req_c.starts_with(&grant_c) {
                    return true;
                }
                continue;
            }
            // Fall back to lexical normalization for paths that do not
            // exist yet (writes) or are inside a granted directory whose
            // own canonicalization also failed.
            if lexical_starts_with(requested_path, granted) {
                return true;
            }
        }
        false
    }
}

/// Lexically normalize `path` (resolving `.` and `..` components without
/// touching the filesystem) and return `true` if the normalized form is
/// equal to, or a descendant of, `root` (also lexically normalized).
///
/// This is the filesystem-independent fallback used when
/// [`std::fs::canonicalize`] cannot resolve a path (e.g. the file does
/// not yet exist). It rejects `..` escapes from a granted root while
/// permitting legitimate child paths.
fn lexical_starts_with(path: &std::path::Path, root: &std::path::Path) -> bool {
    let norm_path = lexical_normalize(path);
    let norm_root = lexical_normalize(root);
    norm_path == norm_root || norm_path.starts_with(&norm_root)
}

/// Lexically normalize a path by consuming `.` components and resolving
/// `..` components against the accumulated prefix, without touching the
/// filesystem. The result is a `PathBuf` containing only normal
/// components.
fn lexical_normalize(path: &std::path::Path) -> std::path::PathBuf {
    use std::path::Component;
    let mut out = std::path::PathBuf::new();
    for comp in path.components() {
        match comp {
            Component::CurDir => {}
            Component::ParentDir => {
                if !out.pop() {
                    // `..` that escapes the root: keep it so a prefix
                    // check will fail rather than silently allow.
                    out.push("..");
                }
            }
            Component::RootDir | Component::Prefix(_) => {
                out.push(comp.as_os_str());
            }
            Component::Normal(s) => out.push(s),
        }
    }
    out
}

/// Fluent builder for assembling a [`CapabilitySet`].
///
/// # Examples
///
/// ```
/// use martensite_plugin::{Capability, CapabilitySet, PluginBuilder};
/// use std::path::PathBuf;
///
/// let caps = PluginBuilder::new()
///     .grant(Capability::Network)
///     .grant(Capability::FileRead(PathBuf::from("/assets")))
///     .revoke(Capability::Network)
///     .build();
///
/// assert!(!caps.contains(&Capability::Network));
/// assert!(caps.contains(&Capability::FileRead(PathBuf::from("/assets"))));
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PluginBuilder {
    caps: CapabilitySet,
}

impl PluginBuilder {
    /// Creates a new builder with no capabilities granted.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::PluginBuilder;
    ///
    /// let builder = PluginBuilder::new();
    /// let caps = builder.build();
    /// assert!(caps.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            caps: CapabilitySet::empty(),
        }
    }

    /// Grants the given capability and returns the builder.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, PluginBuilder};
    ///
    /// let caps = PluginBuilder::new().grant(Capability::Network).build();
    /// assert!(caps.contains(&Capability::Network));
    /// ```
    pub fn grant(mut self, cap: Capability) -> Self {
        self.caps.grant(cap);
        self
    }

    /// Revokes the given capability and returns the builder.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, PluginBuilder};
    ///
    /// let caps = PluginBuilder::new()
    ///     .grant(Capability::Network)
    ///     .revoke(Capability::Network)
    ///     .build();
    /// assert!(!caps.contains(&Capability::Network));
    /// ```
    pub fn revoke(mut self, cap: Capability) -> Self {
        self.caps.revoke(&cap);
        self
    }

    /// Finalizes the builder into an immutable capability set.
    ///
    /// # Examples
    ///
    /// ```
    /// use martensite_plugin::{Capability, PluginBuilder};
    ///
    /// let caps = PluginBuilder::new().grant(Capability::Network).build();
    /// assert!(caps.contains(&Capability::Network));
    /// ```
    pub fn build(self) -> CapabilitySet {
        self.caps
    }
}

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

    #[test]
    fn empty_set_contains_nothing() {
        let caps = CapabilitySet::empty();
        assert!(caps.is_empty());
        assert_eq!(caps.len(), 0);
        assert!(!caps.contains(&Capability::Network));
    }

    #[test]
    fn grant_and_revoke_signal() {
        let mut caps = CapabilitySet::empty();
        let id = SignalId::next();
        let cap = Capability::SignalRead(id);

        assert!(caps.grant(cap.clone()));
        assert!(caps.contains(&cap));
        assert!(!caps.grant(cap.clone()));

        assert!(caps.revoke(&cap));
        assert!(!caps.contains(&cap));
        assert!(!caps.revoke(&cap));
    }

    #[test]
    fn builder_assembles_caps() {
        let path = PathBuf::from("/assets");
        let caps = PluginBuilder::new()
            .grant(Capability::Network)
            .grant(Capability::FileRead(path.clone()))
            .grant(Capability::SignalWrite(SignalId::next()))
            .revoke(Capability::Network)
            .build();

        assert_eq!(caps.len(), 2);
        assert!(!caps.contains(&Capability::Network));
        assert!(caps.contains(&Capability::FileRead(path)));
    }

    #[test]
    fn file_capabilities_are_distinct_by_path() {
        let a = Capability::FileRead(PathBuf::from("/a"));
        let b = Capability::FileRead(PathBuf::from("/b"));
        let mut caps = CapabilitySet::empty();
        caps.grant(a.clone());
        assert!(caps.contains(&a));
        assert!(!caps.contains(&b));
    }

    #[test]
    fn file_read_allowed_rejects_traversal_lexically() {
        // Grant a directory and verify that a `..` escape is rejected
        // even when the filesystem cannot canonicalize the path.
        let mut caps = CapabilitySet::empty();
        caps.grant(Capability::FileRead(PathBuf::from("/assets")));

        // Legitimate child path is allowed (lexical fallback).
        assert!(caps.file_read_allowed(std::path::Path::new("/assets/foo.txt")));
        // Traversal escape is rejected.
        assert!(!caps.file_read_allowed(std::path::Path::new("/assets/../etc/passwd")));
        // Sibling directory is rejected.
        assert!(!caps.file_read_allowed(std::path::Path::new("/etc/passwd")));
        // Exact granted root is allowed.
        assert!(caps.file_read_allowed(std::path::Path::new("/assets")));
    }

    #[test]
    fn file_read_allowed_exact_file_grant() {
        let mut caps = CapabilitySet::empty();
        caps.grant(Capability::FileRead(PathBuf::from("/assets/secret.txt")));
        assert!(caps.file_read_allowed(std::path::Path::new("/assets/secret.txt")));
        // A sibling file under the same directory is not allowed.
        assert!(!caps.file_read_allowed(std::path::Path::new("/assets/other.txt")));
    }

    #[test]
    fn file_read_allowed_real_dir_traversal() {
        // Use the tempdir crate pattern via std::env::temp_dir for a
        // real filesystem traversal test.
        let tmp = std::env::temp_dir().join("martensite_plugin_traversal_test");
        std::fs::create_dir_all(&tmp).unwrap();
        let sub = tmp.join("sub");
        std::fs::create_dir_all(&sub).unwrap();
        let secret = tmp.join("secret.txt");
        std::fs::write(&secret, b"x").unwrap();
        let child = sub.join("child.txt");
        std::fs::write(&child, b"y").unwrap();

        let mut caps = CapabilitySet::empty();
        caps.grant(Capability::FileRead(sub.clone()));

        // Child inside the granted dir is allowed.
        assert!(caps.file_read_allowed(&child));
        // Sibling outside the granted dir is rejected even with `..`.
        let escape = sub.join("..").join("secret.txt");
        assert!(!caps.file_read_allowed(&escape));

        std::fs::remove_dir_all(&tmp).ok();
    }

    #[test]
    fn lexical_normalize_strips_dot_and_resolves_dotdot() {
        assert_eq!(
            lexical_normalize(std::path::Path::new("/a/b/./c")),
            std::path::PathBuf::from("/a/b/c")
        );
        assert_eq!(
            lexical_normalize(std::path::Path::new("/a/b/../c")),
            std::path::PathBuf::from("/a/c")
        );
        // `..` that escapes the root is preserved (cannot pop the root
        // component), so a prefix check against the original root fails.
        let escaped = lexical_normalize(std::path::Path::new("/a/../../etc"));
        assert!(!escaped.starts_with(std::path::Path::new("/a")));
    }
}