cheeseburger 0.1.0

The Safe Script Execution Environment.
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::io::{Error as IoError};
use std::fmt;
use regex::Regex;

#[derive(Debug)]
pub enum ScriptError {
    CommandNotAllowed(String),
    PathOutsideWorkingDir(PathBuf),
    ProtectedPath(PathBuf),
    IoError(IoError),
    ParseError(String),
}

impl fmt::Display for ScriptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ScriptError::CommandNotAllowed(cmd) => write!(f, "Command not allowed: {}", cmd),
            ScriptError::PathOutsideWorkingDir(path) => write!(f, "Path outside working directory: {:?}", path),
            ScriptError::ProtectedPath(path) => write!(f, "Path is protected: {:?}", path),
            ScriptError::IoError(err) => write!(f, "IO error: {}", err),
            ScriptError::ParseError(err) => write!(f, "Parse error: {}", err),
        }
    }
}

impl From<IoError> for ScriptError {
    fn from(error: IoError) -> Self {
        ScriptError::IoError(error)
    }
}

impl std::error::Error for ScriptError {}

#[derive(Debug)]
pub struct ScriptResult {
    pub stdout: String,
    pub stderr: String,
    pub exit_code: i32,
}

impl From<Output> for ScriptResult {
    fn from(output: Output) -> Self {
        ScriptResult {
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            exit_code: output.status.code().unwrap_or(-1),
        }
    }
}

#[derive(Debug, Clone)]
pub struct CommandProtection {
    /// Patterns that are protected for this specific command
    pub protected_patterns: Vec<String>,
    /// Patterns that are exempt from global protection for this command
    pub override_patterns: Vec<String>,
}

#[derive(Debug, Clone)]
struct ScriptCommand {
    name: String,
    args: Vec<String>,
}

impl ScriptCommand {
    fn new(name: String, args: Vec<String>) -> Self {
        ScriptCommand { name, args }
    }
}

pub struct BurgerFlipper {
    /// List of commands that are allowed to be executed
    allowed_commands: HashSet<String>,
    /// Working directory that commands should be confined to
    working_dir: PathBuf,
    /// Global pattern protection that applies to all commands
    global_protected_patterns: Vec<String>,
    /// Command-specific protections and overrides
    command_protections: HashMap<String, CommandProtection>,
    /// Commands that can interact with the file system
    fs_commands: HashSet<String>,
}

impl BurgerFlipper {
    pub fn new<P: AsRef<Path>>(
        allowed_commands: Vec<String>,
        working_dir: P,
        global_protected_patterns: Vec<String>,
    ) -> Self {
        let working_dir = working_dir.as_ref().to_path_buf();

        let fs_commands = vec![
            "ls".to_string(), "cat".to_string(), "cp".to_string(),
            "mv".to_string(), "rm".to_string(), "mkdir".to_string(),
            "rmdir".to_string(), "touch".to_string()
        ];

        BurgerFlipper {
            allowed_commands: allowed_commands.into_iter().collect(),
            working_dir,
            global_protected_patterns,
            command_protections: HashMap::new(),
            fs_commands: fs_commands.into_iter().collect(),
        }
    }

    pub fn add_command_protection(
        &mut self,
        command: String,
        protected_patterns: Vec<String>,
        override_patterns: Vec<String>,
    ) {
        self.command_protections.insert(
            command,
            CommandProtection {
                protected_patterns,
                override_patterns,
            },
        );
    }

    pub fn add_fs_command(&mut self, command: String) {
        self.fs_commands.insert(command);
    }

    pub fn execute(&self, script: &str) -> Result<ScriptResult, ScriptError> {
        let commands = self.parse_script(script)?;

        if commands.is_empty() {
            return Err(ScriptError::ParseError("Empty script".to_string()));
        }

        if commands.len() == 1 {
            return self.execute_command(&commands[0]);
        }

        if commands.len() == 2 && commands[0].name == "fs" && commands[0].args.is_empty() {
            if self.fs_commands.contains(&commands[1].name) {
                return self.execute_command(&commands[1]);
            } else {
                return Err(ScriptError::CommandNotAllowed(format!("fs {}", commands[1].name)));
            }
        }

        // For other multi-command scripts, this would need more complex handling
        Err(ScriptError::ParseError("Complex scripts not supported".to_string()))
    }

    /// Execute a single command
    fn execute_command(&self, cmd: &ScriptCommand) -> Result<ScriptResult, ScriptError> {
        // Check if the command is allowed
        if !self.allowed_commands.contains(&cmd.name) {
            return Err(ScriptError::CommandNotAllowed(cmd.name.clone()));
        }

        // Validate paths in arguments
        self.validate_paths(&cmd.name, &cmd.args)?;

        // Execute the command
        let output = Command::new(&cmd.name)
            .args(&cmd.args)
            .current_dir(&self.working_dir)
            .output()?;

        Ok(output.into())
    }

    /// Parse a script into a sequence of commands
    fn parse_script(&self, script: &str) -> Result<Vec<ScriptCommand>, ScriptError> {
        let tokens = self.tokenize_script(script)?;
        if tokens.is_empty() {
            return Ok(vec![]);
        }

        if tokens.len() >= 2 && tokens[0] == "fs" {
            if tokens.len() == 1 {
                return Err(ScriptError::ParseError("Incomplete fs command".to_string()));
            }

            let fs_cmd = ScriptCommand::new("fs".to_string(), vec![]);
            let cmd_name = tokens[1].to_string();
            let cmd_args = if tokens.len() > 2 {
                tokens[2..].to_vec()
            } else {
                vec![]
            };

            let sub_cmd = ScriptCommand::new(cmd_name, cmd_args);
            return Ok(vec![fs_cmd, sub_cmd]);
        }

        let mut commands = Vec::new();
        let mut i = 0;

        while i < tokens.len() {
            let start = i;

            while i < tokens.len() && tokens[i] != ";" {
                i += 1;
            }

            if i > start {
                let cmd_name = tokens[start].to_string();
                let cmd_args = if i > start + 1 {
                    tokens[start+1..i].to_vec()
                } else {
                    vec![]
                };

                commands.push(ScriptCommand::new(cmd_name, cmd_args));
            }

            if i < tokens.len() {
                i += 1;
            }
        }

        Ok(commands)
    }

    fn tokenize_script(&self, script: &str) -> Result<Vec<String>, ScriptError> {
        let mut tokens = Vec::new();
        let mut current_token = String::new();
        let mut in_single_quotes = false;
        let mut in_double_quotes = false;
        let mut escape_next = false;

        for c in script.chars() {
            if escape_next {
                current_token.push(c);
                escape_next = false;
            } else if c == '\\' {
                escape_next = true;
            } else if c == '\'' && !in_double_quotes {
                in_single_quotes = !in_single_quotes;
            } else if c == '"' && !in_single_quotes {
                in_double_quotes = !in_double_quotes;
            } else if (c.is_whitespace() || c == ';') && !in_single_quotes && !in_double_quotes {
                if !current_token.is_empty() {
                    tokens.push(current_token);
                    current_token = String::new();
                }
                if c == ';' {
                    tokens.push(";".to_string());
                }
            } else {
                current_token.push(c);
            }
        }

        if in_single_quotes || in_double_quotes {
            return Err(ScriptError::ParseError("Unterminated quotes".to_string()));
        }

        if escape_next {
            return Err(ScriptError::ParseError("Unterminated escape sequence".to_string()));
        }

        if !current_token.is_empty() {
            tokens.push(current_token);
        }

        Ok(tokens)
    }

    fn validate_paths(&self, cmd: &str, args: &[String]) -> Result<(), ScriptError> {
        if !self.fs_commands.contains(cmd) {
            return Ok(());
        }

        for arg in args {
            if arg.starts_with('-') {
                continue;
            }

            let path = PathBuf::from(arg);

            let abs_path = if path.is_absolute() {
                path.clone()
            } else {
                self.working_dir.join(&path)
            };

            if !is_path_within(&abs_path, &self.working_dir)? {
                return Err(ScriptError::PathOutsideWorkingDir(abs_path));
            }

            if self.is_path_protected(cmd, &abs_path)? {
                return Err(ScriptError::ProtectedPath(abs_path));
            }
        }

        Ok(())
    }

    fn is_path_protected(&self, cmd: &str, path: &Path) -> Result<bool, ScriptError> {
        let path_str = path.to_string_lossy().to_string();

        if let Some(protection) = self.command_protections.get(cmd) {
            for pattern in &protection.override_patterns {
                if path_matches_pattern(&path_str, pattern)? {
                    return Ok(false);
                }
            }

            for pattern in &protection.protected_patterns {
                if path_matches_pattern(&path_str, pattern)? {
                    return Ok(true);
                }
            }
        }

        for pattern in &self.global_protected_patterns {
            if path_matches_pattern(&path_str, pattern)? {
                return Ok(true);
            }
        }

        Ok(false)
    }
}

fn is_path_within(path: &Path, base: &Path) -> Result<bool, ScriptError> {
    let path_canon = match path.canonicalize() {
        Ok(p) => p,
        Err(_) => {
            match path.parent() {
                Some(parent) => {
                    match parent.canonicalize() {
                        Ok(p) => {
                            if let Some(filename) = path.file_name() {
                                p.join(filename)
                            } else {
                                path.to_path_buf()
                            }
                        },
                        Err(_) => path.to_path_buf()
                    }
                },
                None => path.to_path_buf()
            }
        }
    };

    let base_canon = base.canonicalize().unwrap_or_else(|_| base.to_path_buf());

    Ok(path_canon.starts_with(&base_canon))
}

fn path_matches_pattern(path: &str, pattern: &str) -> Result<bool, ScriptError> {
    let regex_pattern = glob_to_regex(pattern)?;
    let regex = Regex::new(&regex_pattern)
        .map_err(|e| ScriptError::ParseError(format!("Invalid regex: {}", e)))?;

    Ok(regex.is_match(path))
}

fn glob_to_regex(pattern: &str) -> Result<String, ScriptError> {
    let mut regex = "^".to_string();

    let mut chars = pattern.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '*' => {
                if chars.peek() == Some(&'*') {
                    // ** matches any subdirectory recursively
                    chars.next();
                    regex.push_str(".*");
                } else {
                    // * matches any characters except /
                    regex.push_str("[^/]*");
                }
            },
            '?' => regex.push('.'),
            '[' => {
                regex.push('[');
                let mut in_bracket = true;
                while let Some(&next_c) = chars.peek() {
                    chars.next();
                    if next_c == ']' {
                        regex.push(']');
                        in_bracket = false;
                        break;
                    } else {
                        regex.push(next_c);
                    }
                }
                if in_bracket {
                    return Err(ScriptError::ParseError("Unterminated bracket expression".to_string()));
                }
            },
            '{' => {
                regex.push('(');
                let mut in_brace = true;
                while let Some(&next_c) = chars.peek() {
                    chars.next();
                    if next_c == '}' {
                        regex.push(')');
                        in_brace = false;
                        break;
                    } else if next_c == ',' {
                        regex.push('|');
                    } else {
                        regex.push(next_c);
                    }
                }
                if in_brace {
                    return Err(ScriptError::ParseError("Unterminated brace expression".to_string()));
                }
            },
            '.' | '+' | '(' | ')' | '^' | '$' | '\\' | '|' => {
                regex.push('\\');
                regex.push(c);
            },
            _ => regex.push(c),
        }
    }

    regex.push('$');
    Ok(regex)
}

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

    #[test]
    fn test_basic_command_execution() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        let executor = BurgerFlipper::new(
            vec!["echo".to_string()],
            temp_path,
            vec![],
        );

        let result = executor.execute("echo cheeseburger").unwrap();
        assert_eq!(result.stdout.trim(), "cheeseburger");
        assert_eq!(result.exit_code, 0);
    }

    #[test]
    fn test_command_not_allowed() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        let executor = BurgerFlipper::new(
            vec!["echo".to_string()],
            temp_path,
            vec![],
        );

        let result = executor.execute("ls");
        assert!(matches!(result, Err(ScriptError::CommandNotAllowed(_))));
    }

    #[test]
    fn test_protected_path() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        let secret_path = temp_path.join("secret_file.txt");
        fs::write(&secret_path, "secret content").unwrap();

        let mut executor = BurgerFlipper::new(
            vec!["cat".to_string()],
            temp_path,
            vec!["**/secret*".to_string()],
        );

        executor.add_fs_command("cat".to_string());

        let result = executor.execute(&format!("cat {}", secret_path.display()));
        assert!(matches!(result, Err(ScriptError::ProtectedPath(_))));
    }

    #[test]
    fn test_command_specific_override() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        let secret_path = temp_path.join("secret_but_allowed.txt");
        fs::write(&secret_path, "viewable content").unwrap();

        let mut executor = BurgerFlipper::new(
            vec!["cat".to_string()],
            temp_path,
            vec!["**/secret*".to_string()],
        );

        executor.add_fs_command("cat".to_string());
        executor.add_command_protection(
            "cat".to_string(),
            vec![],
            vec!["**/secret_but_allowed.txt".to_string()]
        );

        let result = executor.execute(&format!("cat {}", secret_path.display())).unwrap();
        assert_eq!(result.stdout.trim(), "viewable content");
    }

    #[test]
    fn test_fs_namespace() {
        let temp_dir = TempDir::new().unwrap();
        let temp_path = temp_dir.path();

        let executor = BurgerFlipper::new(
            vec!["ls".to_string()],
            temp_path,
            vec![],
        );

        let result = executor.execute("fs ls");
        assert!(result.is_ok());
    }
}