use crate::error::InterpError;
use std::cell::RefCell;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FilesystemPermission {
Any,
Read,
Write,
ReadPath(String),
WritePath(String),
Path(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NetworkPermission {
Any,
Connect(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProcessPermission {
Any,
Command(String),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Permission {
Filesystem(FilesystemPermission),
Network(NetworkPermission),
Process(ProcessPermission),
Isolate,
Env,
ModuleFiles,
}
impl Permission {
fn describe(&self) -> String {
match self {
Permission::Filesystem(f) => format!("filesystem {f:?}"),
Permission::Network(n) => format!("network {n:?}"),
Permission::Process(p) => format!("process {p:?}"),
Permission::Isolate => "isolate".to_string(),
Permission::Env => "environment".to_string(),
Permission::ModuleFiles => "filesystem module loading".to_string(),
}
}
}
#[derive(Default)]
pub struct PermissionSet {
pub(crate) granted: RefCell<Vec<Permission>>,
}
impl PermissionSet {
pub fn new() -> Self {
PermissionSet::default()
}
pub fn grant(&self, permission: Permission) {
let mut g = self.granted.borrow_mut();
if !g.iter().any(|p| p == &permission) {
g.push(permission);
}
}
pub fn revoke(&self, permission: &Permission) {
self.granted.borrow_mut().retain(|p| p != permission);
}
pub fn allows(&self, requested: &Permission) -> bool {
self.granted.borrow().iter().any(|g| covers(g, requested))
}
pub fn require(&self, requested: &Permission) -> Result<(), InterpError> {
if self.allows(requested) {
Ok(())
} else {
Err(InterpError::runtime(format!(
"Permission denied: {} access is not granted to this context \
(use Context::grant to allow it)",
requested.describe()
)))
}
}
}
fn covers(granted: &Permission, requested: &Permission) -> bool {
match (granted, requested) {
(Permission::Filesystem(g), Permission::Filesystem(r)) => fs_covers(g, r),
(Permission::Network(g), Permission::Network(r)) => net_covers(g, r),
(Permission::Process(g), Permission::Process(r)) => proc_covers(g, r),
(Permission::Isolate, Permission::Isolate) => true,
(Permission::Env, Permission::Env) => true,
(Permission::ModuleFiles, Permission::ModuleFiles) => true,
_ => false,
}
}
fn fs_covers(granted: &FilesystemPermission, requested: &FilesystemPermission) -> bool {
match (granted, requested) {
(FilesystemPermission::Any, _) => true,
(FilesystemPermission::Read, FilesystemPermission::Read) => true,
(FilesystemPermission::Read, FilesystemPermission::ReadPath(_)) => true,
(FilesystemPermission::Write, FilesystemPermission::Write) => true,
(FilesystemPermission::Write, FilesystemPermission::WritePath(_)) => true,
(FilesystemPermission::ReadPath(g), FilesystemPermission::ReadPath(r)) => path_covers(g, r),
(FilesystemPermission::WritePath(g), FilesystemPermission::WritePath(r)) => {
path_covers(g, r)
}
(FilesystemPermission::Path(g), FilesystemPermission::ReadPath(r))
| (FilesystemPermission::Path(g), FilesystemPermission::WritePath(r))
| (FilesystemPermission::Path(g), FilesystemPermission::Path(r)) => path_covers(g, r),
_ => false,
}
}
fn path_covers(granted_prefix: &str, requested_path: &str) -> bool {
let g = granted_prefix.trim_end_matches('/');
requested_path == g || requested_path.starts_with(&format!("{g}/"))
}
fn net_covers(granted: &NetworkPermission, requested: &NetworkPermission) -> bool {
match (granted, requested) {
(NetworkPermission::Any, _) => true,
(NetworkPermission::Connect(g), NetworkPermission::Connect(r)) => {
let (gh, gp) = split_host_port(g);
let (rh, rp) = split_host_port(r);
match gp {
Some(gp) => gh == rh && rp.is_none_or(|rp| rp == gp),
None => gh == rh,
}
}
(NetworkPermission::Connect(_), NetworkPermission::Any) => false,
}
}
fn split_host_port(spec: &str) -> (&str, Option<u16>) {
match spec.rsplit_once(':') {
Some((host, port)) => match port.parse::<u16>() {
Ok(p) => (host, Some(p)),
Err(_) => (spec, None),
},
None => (spec, None),
}
}
fn proc_covers(granted: &ProcessPermission, requested: &ProcessPermission) -> bool {
match (granted, requested) {
(ProcessPermission::Any, _) => true,
(ProcessPermission::Command(g), ProcessPermission::Command(r)) => {
r == g || r.ends_with(&format!("/{g}"))
}
(ProcessPermission::Command(_), ProcessPermission::Any) => false,
}
}
pub fn current() -> PermissionSet {
let state = crate::state::current();
PermissionSet {
granted: state.permissions.granted.clone(),
}
}
pub fn with_current_permissions<T>(
f: impl FnOnce(&PermissionSet) -> Result<T, InterpError>,
) -> Result<T, InterpError> {
let state = crate::state::current();
f(&state.permissions)
}
pub fn require_fs_read(path: &str) -> Result<(), InterpError> {
with_current_permissions(|set| {
set.require(&Permission::Filesystem(FilesystemPermission::ReadPath(
path.to_string(),
)))
})
}
pub fn require_fs_write(path: &str) -> Result<(), InterpError> {
with_current_permissions(|set| {
set.require(&Permission::Filesystem(FilesystemPermission::WritePath(
path.to_string(),
)))
})
}
pub fn require_network(host: &str, port: u16) -> Result<(), InterpError> {
with_current_permissions(|set| {
set.require(&Permission::Network(NetworkPermission::Connect(format!(
"{host}:{port}"
))))
})
}
pub fn require_network_any() -> Result<(), InterpError> {
with_current_permissions(|set| set.require(&Permission::Network(NetworkPermission::Any)))
}
pub fn require_process(executable: &str) -> Result<(), InterpError> {
with_current_permissions(|set| {
set.require(&Permission::Process(ProcessPermission::Command(
executable.to_string(),
)))
})
}
pub fn require_isolate() -> Result<(), InterpError> {
with_current_permissions(|set| set.require(&Permission::Isolate))
}
pub fn require_env() -> Result<(), InterpError> {
with_current_permissions(|set| set.require(&Permission::Env))
}
pub fn require_module_files() -> Result<(), InterpError> {
with_current_permissions(|set| set.require(&Permission::ModuleFiles))
}