fusabi-stdlib-ext 0.1.6

Extended standard library modules and domain packs for Fusabi
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
//! Safety controls for stdlib operations.

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::error::{Error, Result};

/// Allowlist for filesystem paths.
#[derive(Debug, Clone, Default)]
pub struct PathAllowlist {
    /// Allowed paths for reading.
    pub read: HashSet<PathBuf>,
    /// Allowed paths for writing.
    pub write: HashSet<PathBuf>,
    /// Denied paths (overrides allowlist).
    pub deny: HashSet<PathBuf>,
}

impl PathAllowlist {
    /// Create an empty allowlist (all paths denied).
    pub fn none() -> Self {
        Self::default()
    }

    /// Create an allowlist that allows all paths.
    pub fn all() -> Self {
        Self {
            read: [PathBuf::from("/")].into_iter().collect(),
            write: [PathBuf::from("/")].into_iter().collect(),
            deny: HashSet::new(),
        }
    }

    /// Add a path for reading.
    pub fn allow_read(mut self, path: impl Into<PathBuf>) -> Self {
        self.read.insert(path.into());
        self
    }

    /// Add a path for writing.
    pub fn allow_write(mut self, path: impl Into<PathBuf>) -> Self {
        self.write.insert(path.into());
        self
    }

    /// Add paths for reading and writing.
    pub fn allow_rw(self, path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        self.allow_read(path.clone()).allow_write(path)
    }

    /// Deny a path.
    pub fn deny(mut self, path: impl Into<PathBuf>) -> Self {
        self.deny.insert(path.into());
        self
    }

    /// Check if a path is allowed for reading.
    pub fn can_read(&self, path: &Path) -> bool {
        if self.is_denied(path) {
            return false;
        }
        self.read.iter().any(|allowed| path.starts_with(allowed))
    }

    /// Check if a path is allowed for writing.
    pub fn can_write(&self, path: &Path) -> bool {
        if self.is_denied(path) {
            return false;
        }
        self.write.iter().any(|allowed| path.starts_with(allowed))
    }

    /// Check if a path is denied.
    fn is_denied(&self, path: &Path) -> bool {
        self.deny.iter().any(|denied| path.starts_with(denied))
    }

    /// Check read permission, returning error if denied.
    pub fn check_read(&self, path: &Path) -> Result<()> {
        if self.can_read(path) {
            Ok(())
        } else {
            Err(Error::path_not_allowed(path.display().to_string()))
        }
    }

    /// Check write permission, returning error if denied.
    pub fn check_write(&self, path: &Path) -> Result<()> {
        if self.can_write(path) {
            Ok(())
        } else {
            Err(Error::path_not_allowed(path.display().to_string()))
        }
    }
}

/// Allowlist for network hosts.
#[derive(Debug, Clone, Default)]
pub struct HostAllowlist {
    /// Allowed hosts.
    pub allowed: HashSet<String>,
    /// Denied hosts.
    pub denied: HashSet<String>,
}

impl HostAllowlist {
    /// Create an empty allowlist (all hosts denied).
    pub fn none() -> Self {
        Self::default()
    }

    /// Create an allowlist that allows all hosts.
    pub fn all() -> Self {
        Self {
            allowed: ["*".to_string()].into_iter().collect(),
            denied: HashSet::new(),
        }
    }

    /// Add an allowed host.
    pub fn allow(mut self, host: impl Into<String>) -> Self {
        self.allowed.insert(host.into());
        self
    }

    /// Add a denied host.
    pub fn deny(mut self, host: impl Into<String>) -> Self {
        self.denied.insert(host.into());
        self
    }

    /// Check if a host is allowed.
    pub fn can_access(&self, host: &str) -> bool {
        let host = host.to_lowercase();

        // Check deny list first
        for denied in &self.denied {
            if Self::host_matches(&host, denied) {
                return false;
            }
        }

        // Check allow list
        for allowed in &self.allowed {
            if Self::host_matches(&host, allowed) {
                return true;
            }
        }

        false
    }

    fn host_matches(host: &str, pattern: &str) -> bool {
        let pattern = pattern.to_lowercase();

        if pattern == "*" {
            return true;
        }

        if pattern.starts_with("*.") {
            let suffix = &pattern[1..];
            host.ends_with(suffix) || host == &pattern[2..]
        } else {
            host == pattern
        }
    }

    /// Check host permission, returning error if denied.
    pub fn check(&self, host: &str) -> Result<()> {
        if self.can_access(host) {
            Ok(())
        } else {
            Err(Error::host_not_allowed(host))
        }
    }
}

/// Safety configuration for stdlib operations.
#[derive(Debug, Clone)]
pub struct SafetyConfig {
    /// Path allowlist.
    pub paths: PathAllowlist,
    /// Host allowlist.
    pub hosts: HostAllowlist,
    /// Allowed environment variable names (None = all denied).
    pub env_vars: Option<HashSet<String>>,
    /// Whether process execution is allowed.
    pub allow_process: bool,
    /// Allowed process commands (None = all allowed if allow_process is true).
    pub allowed_commands: Option<HashSet<String>>,
    /// Default timeout for operations.
    pub default_timeout: Duration,
    /// Maximum timeout allowed.
    pub max_timeout: Duration,
}

impl Default for SafetyConfig {
    fn default() -> Self {
        Self {
            paths: PathAllowlist::none(),
            hosts: HostAllowlist::none(),
            env_vars: Some(HashSet::new()),
            allow_process: false,
            allowed_commands: None,
            default_timeout: Duration::from_secs(30),
            max_timeout: Duration::from_secs(300),
        }
    }
}

impl SafetyConfig {
    /// Create a new safety configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a permissive configuration (for trusted code only).
    pub fn permissive() -> Self {
        Self {
            paths: PathAllowlist::all(),
            hosts: HostAllowlist::all(),
            env_vars: None,
            allow_process: true,
            allowed_commands: None,
            default_timeout: Duration::from_secs(60),
            max_timeout: Duration::from_secs(3600),
        }
    }

    /// Create a strict configuration.
    pub fn strict() -> Self {
        Self {
            paths: PathAllowlist::none(),
            hosts: HostAllowlist::none(),
            env_vars: Some(HashSet::new()),
            allow_process: false,
            allowed_commands: Some(HashSet::new()),
            default_timeout: Duration::from_secs(10),
            max_timeout: Duration::from_secs(30),
        }
    }

    /// Set path allowlist.
    pub fn with_paths(mut self, paths: PathAllowlist) -> Self {
        self.paths = paths;
        self
    }

    /// Set host allowlist.
    pub fn with_hosts(mut self, hosts: HostAllowlist) -> Self {
        self.hosts = hosts;
        self
    }

    /// Allow specific environment variables.
    pub fn with_env_vars<I, S>(mut self, vars: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.env_vars = Some(vars.into_iter().map(Into::into).collect());
        self
    }

    /// Allow all environment variables.
    pub fn allow_all_env(mut self) -> Self {
        self.env_vars = None;
        self
    }

    /// Allow process execution.
    pub fn with_allow_process(mut self, allow: bool) -> Self {
        self.allow_process = allow;
        self
    }

    /// Set allowed commands.
    pub fn with_allowed_commands<I, S>(mut self, commands: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allowed_commands = Some(commands.into_iter().map(Into::into).collect());
        self
    }

    /// Set default timeout.
    pub fn with_default_timeout(mut self, timeout: Duration) -> Self {
        self.default_timeout = timeout;
        self
    }

    /// Set maximum timeout.
    pub fn with_max_timeout(mut self, timeout: Duration) -> Self {
        self.max_timeout = timeout;
        self
    }

    /// Check if an environment variable is accessible.
    pub fn can_access_env(&self, name: &str) -> bool {
        match &self.env_vars {
            None => true,
            Some(allowed) => allowed.contains(name),
        }
    }

    /// Check environment variable access, returning error if denied.
    pub fn check_env(&self, name: &str) -> Result<()> {
        if self.can_access_env(name) {
            Ok(())
        } else {
            Err(Error::not_permitted(format!(
                "environment variable access denied: {}",
                name
            )))
        }
    }

    /// Check if a command is allowed.
    pub fn can_execute(&self, command: &str) -> bool {
        if !self.allow_process {
            return false;
        }

        match &self.allowed_commands {
            None => true,
            Some(allowed) => allowed.contains(command),
        }
    }

    /// Check command execution, returning error if denied.
    pub fn check_execute(&self, command: &str) -> Result<()> {
        if !self.allow_process {
            return Err(Error::not_permitted("process execution not allowed"));
        }

        if let Some(ref allowed) = self.allowed_commands {
            if !allowed.contains(command) {
                return Err(Error::not_permitted(format!(
                    "command not allowed: {}",
                    command
                )));
            }
        }

        Ok(())
    }

    /// Clamp a timeout to the maximum allowed.
    pub fn clamp_timeout(&self, timeout: Duration) -> Duration {
        timeout.min(self.max_timeout)
    }
}

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

    #[test]
    fn test_path_allowlist() {
        let paths = PathAllowlist::none()
            .allow_read("/tmp")
            .allow_rw("/home/user/data")
            .deny("/home/user/data/secret");

        assert!(paths.can_read(Path::new("/tmp/file.txt")));
        assert!(!paths.can_write(Path::new("/tmp/file.txt")));

        assert!(paths.can_read(Path::new("/home/user/data/file.txt")));
        assert!(paths.can_write(Path::new("/home/user/data/file.txt")));

        assert!(!paths.can_read(Path::new("/home/user/data/secret/key")));
        assert!(!paths.can_write(Path::new("/home/user/data/secret/key")));

        assert!(!paths.can_read(Path::new("/etc/passwd")));
    }

    #[test]
    fn test_host_allowlist() {
        let hosts = HostAllowlist::none()
            .allow("api.example.com")
            .allow("*.trusted.org")
            .deny("evil.trusted.org");

        assert!(hosts.can_access("api.example.com"));
        assert!(hosts.can_access("sub.trusted.org"));
        assert!(hosts.can_access("trusted.org"));
        assert!(!hosts.can_access("evil.trusted.org"));
        assert!(!hosts.can_access("other.com"));
    }

    #[test]
    fn test_safety_config() {
        let config = SafetyConfig::new()
            .with_env_vars(["PATH", "HOME"])
            .with_allow_process(true)
            .with_allowed_commands(["ls", "cat"]);

        assert!(config.can_access_env("PATH"));
        assert!(!config.can_access_env("SECRET"));

        assert!(config.can_execute("ls"));
        assert!(!config.can_execute("rm"));
    }

    #[test]
    fn test_timeout_clamping() {
        let config = SafetyConfig::new().with_max_timeout(Duration::from_secs(60));

        assert_eq!(
            config.clamp_timeout(Duration::from_secs(30)),
            Duration::from_secs(30)
        );
        assert_eq!(
            config.clamp_timeout(Duration::from_secs(120)),
            Duration::from_secs(60)
        );
    }
}