1use crate::vfs::{
2 validate_path, VfsError, VfsResult, VirtualDirEntry, VirtualFileSystem, VirtualStat,
3 VirtualUtimeSpec,
4};
5use std::collections::{BTreeMap, HashMap};
6use std::error::Error;
7use std::fmt;
8use std::path::Path;
9use std::sync::Arc;
10
11pub type FsPermissionCheck = Arc<dyn Fn(&FsAccessRequest) -> PermissionDecision + Send + Sync>;
12pub type NetworkPermissionCheck =
13 Arc<dyn Fn(&NetworkAccessRequest) -> PermissionDecision + Send + Sync>;
14pub type CommandPermissionCheck =
15 Arc<dyn Fn(&CommandAccessRequest) -> PermissionDecision + Send + Sync>;
16pub type EnvironmentPermissionCheck =
17 Arc<dyn Fn(&EnvAccessRequest) -> PermissionDecision + Send + Sync>;
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct PermissionDecision {
21 pub allow: bool,
22 pub reason: Option<String>,
23}
24
25impl PermissionDecision {
26 pub fn allow() -> Self {
27 Self {
28 allow: true,
29 reason: None,
30 }
31 }
32
33 pub fn deny(reason: impl Into<String>) -> Self {
34 Self {
35 allow: false,
36 reason: Some(reason.into()),
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct PermissionError {
43 code: &'static str,
44 message: String,
45}
46
47impl PermissionError {
48 pub fn code(&self) -> &'static str {
49 self.code
50 }
51
52 fn access_denied(subject: impl Into<String>, reason: Option<&str>) -> Self {
53 let subject = subject.into();
54 let message = match reason {
55 Some(reason) => format!("permission denied, {subject}: {reason}"),
56 None => format!("permission denied, {subject}"),
57 };
58
59 Self {
60 code: "EACCES",
61 message,
62 }
63 }
64}
65
66impl fmt::Display for PermissionError {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 write!(f, "{}: {}", self.code, self.message)
69 }
70}
71
72impl Error for PermissionError {}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum FsOperation {
76 Read,
77 Write,
78 Mkdir,
79 CreateDir,
80 ReadDir,
81 Stat,
82 Remove,
83 Rename,
84 Exists,
85 Symlink,
86 ReadLink,
87 Link,
88 Chmod,
89 Chown,
90 Utimes,
91 Truncate,
92 MountSensitive,
93}
94
95impl FsOperation {
96 fn as_str(self) -> &'static str {
97 match self {
98 Self::Read => "read",
99 Self::Write => "write",
100 Self::Mkdir => "mkdir",
101 Self::CreateDir => "createDir",
102 Self::ReadDir => "readdir",
103 Self::Stat => "stat",
104 Self::Remove => "rm",
105 Self::Rename => "rename",
106 Self::Exists => "exists",
107 Self::Symlink => "symlink",
108 Self::ReadLink => "readlink",
109 Self::Link => "link",
110 Self::Chmod => "chmod",
111 Self::Chown => "chown",
112 Self::Utimes => "utimes",
113 Self::Truncate => "truncate",
114 Self::MountSensitive => "mount",
115 }
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct FsAccessRequest {
121 pub vm_id: String,
122 pub op: FsOperation,
123 pub path: String,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum NetworkOperation {
128 Fetch,
129 Http,
130 Dns,
131 Listen,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub struct NetworkAccessRequest {
136 pub vm_id: String,
137 pub op: NetworkOperation,
138 pub resource: String,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct CommandAccessRequest {
143 pub vm_id: String,
144 pub command: String,
145 pub args: Vec<String>,
146 pub cwd: Option<String>,
147 pub env: BTreeMap<String, String>,
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
151pub enum EnvironmentOperation {
152 Read,
153 Write,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct EnvAccessRequest {
158 pub vm_id: String,
159 pub op: EnvironmentOperation,
160 pub key: String,
161 pub value: Option<String>,
162}
163
164#[derive(Clone, Default)]
165pub struct Permissions {
166 pub filesystem: Option<FsPermissionCheck>,
167 pub network: Option<NetworkPermissionCheck>,
168 pub child_process: Option<CommandPermissionCheck>,
169 pub environment: Option<EnvironmentPermissionCheck>,
170}
171
172impl Permissions {
173 pub fn allow_all() -> Self {
174 Self {
175 filesystem: Some(Arc::new(|_: &FsAccessRequest| PermissionDecision::allow())),
176 network: Some(Arc::new(|_: &NetworkAccessRequest| {
177 PermissionDecision::allow()
178 })),
179 child_process: Some(Arc::new(|_: &CommandAccessRequest| {
180 PermissionDecision::allow()
181 })),
182 environment: Some(Arc::new(|_: &EnvAccessRequest| PermissionDecision::allow())),
183 }
184 }
185}
186
187pub fn permission_glob_matches(pattern: &str, value: &str) -> bool {
188 fn matches(
189 pattern: &[u8],
190 value: &[u8],
191 pattern_index: usize,
192 value_index: usize,
193 memo: &mut HashMap<(usize, usize), bool>,
194 ) -> bool {
195 if let Some(result) = memo.get(&(pattern_index, value_index)) {
196 return *result;
197 }
198
199 let result = if pattern_index == pattern.len() {
200 value_index == value.len()
201 } else {
202 match pattern[pattern_index] {
203 b'?' => {
204 value_index < value.len()
205 && value[value_index] != b'/'
206 && matches(pattern, value, pattern_index + 1, value_index + 1, memo)
207 }
208 b'*' => {
209 let mut next_pattern_index = pattern_index;
210 while next_pattern_index < pattern.len() && pattern[next_pattern_index] == b'*'
211 {
212 next_pattern_index += 1;
213 }
214
215 if matches(pattern, value, next_pattern_index, value_index, memo) {
216 true
217 } else {
218 let crosses_separators = next_pattern_index - pattern_index > 1;
219 let mut next_value_index = value_index;
220 while next_value_index < value.len()
221 && (crosses_separators || value[next_value_index] != b'/')
222 {
223 next_value_index += 1;
224 if matches(pattern, value, next_pattern_index, next_value_index, memo) {
225 return true;
226 }
227 }
228 false
229 }
230 }
231 expected => {
232 value_index < value.len()
233 && expected == value[value_index]
234 && matches(pattern, value, pattern_index + 1, value_index + 1, memo)
235 }
236 }
237 };
238
239 memo.insert((pattern_index, value_index), result);
240 result
241 }
242
243 matches(
244 pattern.as_bytes(),
245 value.as_bytes(),
246 0,
247 0,
248 &mut HashMap::new(),
249 )
250}
251
252pub fn filter_env(
253 vm_id: &str,
254 env: &BTreeMap<String, String>,
255 permissions: &Permissions,
256) -> BTreeMap<String, String> {
257 let Some(check) = permissions.environment.as_ref() else {
258 return BTreeMap::new();
259 };
260
261 env.iter()
262 .filter_map(|(key, value)| {
263 let request = EnvAccessRequest {
264 vm_id: vm_id.to_owned(),
265 op: EnvironmentOperation::Read,
266 key: key.clone(),
267 value: Some(value.clone()),
268 };
269 let decision = check(&request);
270 decision.allow.then(|| (key.clone(), value.clone()))
271 })
272 .collect()
273}
274
275pub fn check_command_execution(
276 vm_id: &str,
277 permissions: &Permissions,
278 command: &str,
279 args: &[String],
280 cwd: Option<&str>,
281 env: &BTreeMap<String, String>,
282) -> Result<(), PermissionError> {
283 let Some(check) = permissions.child_process.as_ref() else {
284 return Ok(());
285 };
286
287 let request = CommandAccessRequest {
288 vm_id: vm_id.to_owned(),
289 command: command.to_owned(),
290 args: args.to_vec(),
291 cwd: cwd.map(ToOwned::to_owned),
292 env: env.clone(),
293 };
294 let decision = check(&request);
295 if decision.allow {
296 Ok(())
297 } else {
298 Err(PermissionError::access_denied(
299 format!("spawn '{command}'"),
300 decision.reason.as_deref(),
301 ))
302 }
303}
304
305pub fn check_network_access(
306 vm_id: &str,
307 permissions: &Permissions,
308 op: NetworkOperation,
309 resource: &str,
310) -> Result<(), PermissionError> {
311 let Some(check) = permissions.network.as_ref() else {
312 return Ok(());
313 };
314
315 let request = NetworkAccessRequest {
316 vm_id: vm_id.to_owned(),
317 op,
318 resource: resource.to_owned(),
319 };
320 let decision = check(&request);
321 if decision.allow {
322 Ok(())
323 } else {
324 Err(PermissionError::access_denied(
325 resource,
326 decision.reason.as_deref(),
327 ))
328 }
329}
330
331#[derive(Clone)]
332pub struct PermissionedFileSystem<F> {
333 inner: F,
334 vm_id: String,
335 permissions: Permissions,
336}
337
338impl<F> PermissionedFileSystem<F> {
339 pub fn new(inner: F, vm_id: impl Into<String>, permissions: Permissions) -> Self {
340 Self {
341 inner,
342 vm_id: vm_id.into(),
343 permissions,
344 }
345 }
346
347 pub fn into_inner(self) -> F {
348 self.inner
349 }
350
351 pub fn inner(&self) -> &F {
352 &self.inner
353 }
354
355 pub fn inner_mut(&mut self) -> &mut F {
356 &mut self.inner
357 }
358
359 fn check(&self, op: FsOperation, path: &str) -> VfsResult<()> {
360 validate_path(path)?;
361 let Some(check) = self.permissions.filesystem.as_ref() else {
362 return Err(VfsError::access_denied(op.as_str(), path, None));
363 };
364
365 let request = FsAccessRequest {
366 vm_id: self.vm_id.clone(),
367 op,
368 path: path.to_owned(),
369 };
370 let decision = check(&request);
371 if decision.allow {
372 Ok(())
373 } else {
374 Err(VfsError::access_denied(
375 op.as_str(),
376 path,
377 decision.reason.as_deref(),
378 ))
379 }
380 }
381}
382
383impl<F: VirtualFileSystem> PermissionedFileSystem<F> {
384 fn resolved_existing_path(&self, path: &str) -> VfsResult<String> {
385 self.inner.realpath(path)
386 }
387
388 fn resolved_destination_path(&self, path: &str) -> VfsResult<String> {
389 let normalized = crate::vfs::normalize_path(path);
390 if normalized == "/" {
391 return Ok(normalized);
392 }
393
394 let parent = Path::new(&normalized)
395 .parent()
396 .unwrap_or_else(|| Path::new("/"))
397 .to_string_lossy()
398 .into_owned();
399 let basename = Path::new(&normalized)
400 .file_name()
401 .map(|value| value.to_string_lossy().into_owned())
402 .unwrap_or_default();
403
404 let mut candidate = parent;
405 let mut unresolved_segments = Vec::new();
406
407 let resolved_parent = loop {
408 match self.inner.realpath(&candidate) {
409 Ok(resolved) => break resolved,
410 Err(error) if matches!(error.code(), "ENOENT" | "ENOTDIR") => {
411 if candidate == "/" {
412 break String::from("/");
413 }
414 let candidate_path = Path::new(&candidate);
415 if let Some(segment) = candidate_path.file_name() {
416 unresolved_segments.push(segment.to_string_lossy().into_owned());
417 }
418 candidate = candidate_path
419 .parent()
420 .unwrap_or_else(|| Path::new("/"))
421 .to_string_lossy()
422 .into_owned();
423 }
424 Err(error) => return Err(error),
425 }
426 };
427
428 let mut resolved = resolved_parent;
429 for segment in unresolved_segments.iter().rev() {
430 if resolved == "/" {
431 resolved = format!("/{segment}");
432 } else {
433 resolved = format!("{resolved}/{segment}");
434 }
435 }
436
437 if resolved == "/" {
438 Ok(format!("/{basename}"))
439 } else {
440 Ok(format!("{resolved}/{basename}"))
441 }
442 }
443
444 fn permission_subject(&self, op: FsOperation, path: &str) -> VfsResult<String> {
445 validate_path(path)?;
446 match op {
447 FsOperation::Read
448 | FsOperation::ReadDir
449 | FsOperation::Stat
450 | FsOperation::ReadLink
451 | FsOperation::Chmod
452 | FsOperation::Chown
453 | FsOperation::Utimes
454 | FsOperation::Truncate => self.resolved_existing_path(path),
455 FsOperation::Exists | FsOperation::Write => self
456 .resolved_existing_path(path)
457 .or_else(|_| self.resolved_destination_path(path)),
458 FsOperation::Mkdir
459 | FsOperation::CreateDir
460 | FsOperation::Rename
461 | FsOperation::Symlink
462 | FsOperation::Link
463 | FsOperation::MountSensitive
464 | FsOperation::Remove => self.resolved_destination_path(path),
465 }
466 }
467
468 fn check_subject(&self, op: FsOperation, path: &str) -> VfsResult<()> {
469 let subject = self.permission_subject(op, path)?;
470 self.check(op, &subject)
471 }
472
473 fn check_existing_subject(&self, op: FsOperation, path: &str) -> VfsResult<()> {
474 validate_path(path)?;
475 let subject = self.resolved_existing_path(path)?;
476 self.check(op, &subject)
477 }
478
479 fn check_destination_subject(&self, op: FsOperation, path: &str) -> VfsResult<()> {
480 validate_path(path)?;
481 let subject = self.resolved_destination_path(path)?;
482 self.check(op, &subject)
483 }
484
485 pub fn check_path(&self, op: FsOperation, path: &str) -> VfsResult<()> {
486 self.check_subject(op, path)
487 }
488
489 pub fn check_virtual_path(&self, op: FsOperation, path: &str) -> VfsResult<()> {
490 self.check(op, path)
491 }
492
493 pub fn exists(&self, path: &str) -> VfsResult<bool> {
494 if let Err(error) = self.check_subject(FsOperation::Exists, path) {
495 if matches!(error.code(), "EACCES" | "ENOENT" | "ENOTDIR" | "ELOOP") {
496 return Ok(false);
497 }
498 return Err(error);
499 }
500 Ok(self.inner.exists(path))
501 }
502}
503
504impl<F: VirtualFileSystem> VirtualFileSystem for PermissionedFileSystem<F> {
505 fn read_file(&mut self, path: &str) -> VfsResult<Vec<u8>> {
506 self.check_subject(FsOperation::Read, path)?;
507 self.inner.read_file(path)
508 }
509
510 fn read_dir(&mut self, path: &str) -> VfsResult<Vec<String>> {
511 self.check_subject(FsOperation::ReadDir, path)?;
512 self.inner.read_dir(path)
513 }
514
515 fn read_dir_limited(&mut self, path: &str, max_entries: usize) -> VfsResult<Vec<String>> {
516 self.check_subject(FsOperation::ReadDir, path)?;
517 self.inner.read_dir_limited(path, max_entries)
518 }
519
520 fn read_dir_with_types(&mut self, path: &str) -> VfsResult<Vec<VirtualDirEntry>> {
521 self.check_subject(FsOperation::ReadDir, path)?;
522 self.inner.read_dir_with_types(path)
523 }
524
525 fn write_file(&mut self, path: &str, content: impl Into<Vec<u8>>) -> VfsResult<()> {
526 self.check_subject(FsOperation::Write, path)?;
527 self.inner.write_file(path, content)
528 }
529
530 fn create_file_exclusive(&mut self, path: &str, content: impl Into<Vec<u8>>) -> VfsResult<()> {
531 self.check_subject(FsOperation::Write, path)?;
532 self.inner.create_file_exclusive(path, content)
533 }
534
535 fn append_file(&mut self, path: &str, content: impl Into<Vec<u8>>) -> VfsResult<u64> {
536 self.check_subject(FsOperation::Write, path)?;
537 self.inner.append_file(path, content)
538 }
539
540 fn create_dir(&mut self, path: &str) -> VfsResult<()> {
541 self.check_subject(FsOperation::CreateDir, path)?;
542 self.inner.create_dir(path)
543 }
544
545 fn mkdir(&mut self, path: &str, recursive: bool) -> VfsResult<()> {
546 self.check_subject(FsOperation::Mkdir, path)?;
547 self.inner.mkdir(path, recursive)
548 }
549
550 fn exists(&self, path: &str) -> bool {
551 PermissionedFileSystem::exists(self, path).unwrap_or(false)
552 }
553
554 fn stat(&mut self, path: &str) -> VfsResult<VirtualStat> {
555 self.check_subject(FsOperation::Stat, path)?;
556 self.inner.stat(path)
557 }
558
559 fn remove_file(&mut self, path: &str) -> VfsResult<()> {
560 self.check_subject(FsOperation::Remove, path)?;
561 self.inner.remove_file(path)
562 }
563
564 fn remove_dir(&mut self, path: &str) -> VfsResult<()> {
565 self.check_subject(FsOperation::Remove, path)?;
566 self.inner.remove_dir(path)
567 }
568
569 fn rename(&mut self, old_path: &str, new_path: &str) -> VfsResult<()> {
570 self.check_subject(FsOperation::Rename, old_path)?;
571 self.check_subject(FsOperation::Rename, new_path)?;
572 self.inner.rename(old_path, new_path)
573 }
574
575 fn realpath(&self, path: &str) -> VfsResult<String> {
576 self.check_subject(FsOperation::Read, path)?;
577 self.inner.realpath(path)
578 }
579
580 fn symlink(&mut self, target: &str, link_path: &str) -> VfsResult<()> {
581 self.check_subject(FsOperation::Symlink, link_path)?;
582 self.inner.symlink(target, link_path)
583 }
584
585 fn read_link(&self, path: &str) -> VfsResult<String> {
586 self.check(FsOperation::ReadLink, &crate::vfs::normalize_path(path))?;
587 self.inner.read_link(path)
588 }
589
590 fn lstat(&self, path: &str) -> VfsResult<VirtualStat> {
591 self.check(FsOperation::Stat, &crate::vfs::normalize_path(path))?;
592 self.inner.lstat(path)
593 }
594
595 fn link(&mut self, old_path: &str, new_path: &str) -> VfsResult<()> {
596 self.check_existing_subject(FsOperation::Link, old_path)?;
597 self.check_destination_subject(FsOperation::Link, new_path)?;
598 self.inner.link(old_path, new_path)
599 }
600
601 fn chmod(&mut self, path: &str, mode: u32) -> VfsResult<()> {
602 self.check_subject(FsOperation::Chmod, path)?;
603 self.inner.chmod(path, mode)
604 }
605
606 fn chown(&mut self, path: &str, uid: u32, gid: u32) -> VfsResult<()> {
607 self.check_subject(FsOperation::Chown, path)?;
608 self.inner.chown(path, uid, gid)
609 }
610
611 fn utimes(&mut self, path: &str, atime_ms: u64, mtime_ms: u64) -> VfsResult<()> {
612 self.check_subject(FsOperation::Utimes, path)?;
613 self.inner.utimes(path, atime_ms, mtime_ms)
614 }
615
616 fn utimes_spec(
617 &mut self,
618 path: &str,
619 atime: VirtualUtimeSpec,
620 mtime: VirtualUtimeSpec,
621 follow_symlinks: bool,
622 ) -> VfsResult<()> {
623 self.check_subject(FsOperation::Utimes, path)?;
624 self.inner.utimes_spec(path, atime, mtime, follow_symlinks)
625 }
626
627 fn truncate(&mut self, path: &str, length: u64) -> VfsResult<()> {
628 self.check_subject(FsOperation::Truncate, path)?;
629 self.inner.truncate(path, length)
630 }
631
632 fn pread(&mut self, path: &str, offset: u64, length: usize) -> VfsResult<Vec<u8>> {
633 self.check_subject(FsOperation::Read, path)?;
634 self.inner.pread(path, offset, length)
635 }
636}