deno_simple_runtime 0.68.0

Provides the deno runtime library
Documentation
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.

use crate::colors;
use crate::fs_util::resolve_from_cwd;
use deno_core::error::custom_error;
use deno_core::error::uri_error;
use deno_core::error::AnyError;
#[cfg(test)]
use deno_core::parking_lot::Mutex;
use deno_core::serde::de;
use deno_core::serde::Deserialize;
use deno_core::serde::Deserializer;
use deno_core::serde::Serialize;
use deno_core::serde_json;
use deno_core::url;
use deno_core::ModuleSpecifier;
use deno_core::OpState;
use log;
use once_cell::sync::Lazy;
use std::collections::HashSet;
use std::fmt;
use std::hash::Hash;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::string::ToString;
#[cfg(test)]
use std::sync::atomic::AtomicBool;
#[cfg(test)]
use std::sync::atomic::Ordering;

const PERMISSION_EMOJI: &str = "⚠️";

static DEBUG_LOG_ENABLED: Lazy<bool> = Lazy::new(|| log::log_enabled!(log::Level::Debug));

/// Tri-state value for storing permission state
#[derive(PartialEq, Debug, Clone, Copy, Deserialize, PartialOrd)]
pub enum PermissionState {
    Granted = 0,
    Prompt = 1,
    Denied = 2,
}

impl PermissionState {
    #[inline(always)]
    fn log_perm_access(name: &str, info: Option<&str>) {
        // Eliminates log overhead (when logging is disabled),
        // log_enabled!(Debug) check in a hot path still has overhead
        // TODO(AaronO): generalize or upstream this optimization
        if *DEBUG_LOG_ENABLED {
            log::debug!(
                "{}",
                colors::bold(&format!(
                    "{}️  Granted {}",
                    PERMISSION_EMOJI,
                    Self::fmt_access(name, info)
                ))
            );
        }
    }

    fn fmt_access(name: &str, info: Option<&str>) -> String {
        format!(
            "{} access{}",
            name,
            info.map_or(String::new(), |info| { format!(" to {}", info) }),
        )
    }

    fn error(name: &str, info: Option<&str>) -> AnyError {
        custom_error(
            "PermissionDenied",
            format!(
                "Requires {}, run again with the --allow-{} flag",
                Self::fmt_access(name, info),
                name
            ),
        )
    }

    /// Check the permission state. bool is whether a prompt was issued.
    fn check(self, name: &str, info: Option<&str>, prompt: bool) -> (Result<(), AnyError>, bool) {
        match self {
            PermissionState::Granted => {
                Self::log_perm_access(name, info);
                (Ok(()), false)
            }
            PermissionState::Prompt if prompt => {
                let msg = Self::fmt_access(name, info);
                if permission_prompt(&msg, name) {
                    Self::log_perm_access(name, info);
                    (Ok(()), true)
                } else {
                    (Err(Self::error(name, info)), true)
                }
            }
            _ => (Err(Self::error(name, info)), false),
        }
    }
}

impl fmt::Display for PermissionState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PermissionState::Granted => f.pad("granted"),
            PermissionState::Prompt => f.pad("prompt"),
            PermissionState::Denied => f.pad("denied"),
        }
    }
}

impl Default for PermissionState {
    fn default() -> Self {
        PermissionState::Prompt
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct UnitPermission {
    pub name: &'static str,
    pub description: &'static str,
    pub state: PermissionState,
    pub prompt: bool,
}

impl UnitPermission {
    pub fn query(&self) -> PermissionState {
        self.state
    }

    pub fn request(&mut self) -> PermissionState {
        if self.state == PermissionState::Prompt {
            if permission_prompt(&format!("access to {}", self.description), self.name) {
                self.state = PermissionState::Granted;
            } else {
                self.state = PermissionState::Denied;
            }
        }
        self.state
    }

    pub fn revoke(&mut self) -> PermissionState {
        if self.state == PermissionState::Granted {
            self.state = PermissionState::Prompt;
        }
        self.state
    }

    pub fn check(&mut self) -> Result<(), AnyError> {
        let (result, prompted) = self.state.check(self.name, None, self.prompt);
        if prompted {
            if result.is_ok() {
                self.state = PermissionState::Granted;
            } else {
                self.state = PermissionState::Denied;
            }
        }
        result
    }
}

/// A normalized environment variable name. On Windows this will
/// be uppercase and on other platforms it will stay as-is.
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
struct EnvVarName {
    inner: String,
}

impl EnvVarName {
    pub fn new(env: impl AsRef<str>) -> Self {
        Self {
            inner: if cfg!(windows) {
                env.as_ref().to_uppercase()
            } else {
                env.as_ref().to_string()
            },
        }
    }
}

impl AsRef<str> for EnvVarName {
    fn as_ref(&self) -> &str {
        self.inner.as_str()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct UnaryPermission<T: Eq + Hash> {
    pub name: &'static str,
    pub description: &'static str,
    pub global_state: PermissionState,
    pub granted_list: HashSet<T>,
    pub denied_list: HashSet<T>,
    pub prompt: bool,
}

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct ReadDescriptor(pub PathBuf);

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct WriteDescriptor(pub PathBuf);

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct NetDescriptor(pub String, pub Option<u16>);

impl NetDescriptor {
    fn new<T: AsRef<str>>(host: &&(T, Option<u16>)) -> Self {
        NetDescriptor(host.0.as_ref().to_string(), host.1)
    }

    pub fn from_string(host: String) -> Self {
        let url = url::Url::parse(&format!("http://{}", host)).unwrap();
        let hostname = url.host_str().unwrap().to_string();

        NetDescriptor(hostname, url.port())
    }
}

impl fmt::Display for NetDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&match self.1 {
            None => self.0.clone(),
            Some(port) => format!("{}:{}", self.0, port),
        })
    }
}

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct EnvDescriptor(EnvVarName);

impl EnvDescriptor {
    pub fn new(env: impl AsRef<str>) -> Self {
        Self(EnvVarName::new(env))
    }
}

impl AsRef<str> for EnvDescriptor {
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub enum RunDescriptor {
    Name(String),
    Path(PathBuf),
}

impl FromStr for RunDescriptor {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let is_path = s.contains('/');
        #[cfg(windows)]
        let is_path = is_path || s.contains('\\') || Path::new(s).is_absolute();
        if is_path {
            Ok(Self::Path(resolve_from_cwd(Path::new(s)).unwrap()))
        } else {
            Ok(Self::Name(s.to_string()))
        }
    }
}

impl ToString for RunDescriptor {
    fn to_string(&self) -> String {
        match self {
            RunDescriptor::Name(s) => s.clone(),
            RunDescriptor::Path(p) => p.to_string_lossy().to_string(),
        }
    }
}

#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct FfiDescriptor(pub PathBuf);

impl UnaryPermission<ReadDescriptor> {
    pub fn query(&self, path: Option<&Path>) -> PermissionState {
        let path = path.map(|p| resolve_from_cwd(p).unwrap());
        if self.global_state == PermissionState::Denied
            && match path.as_ref() {
                None => true,
                Some(path) => self
                    .denied_list
                    .iter()
                    .any(|path_| path_.0.starts_with(path)),
            }
        {
            PermissionState::Denied
        } else if self.global_state == PermissionState::Granted
            || match path.as_ref() {
                None => false,
                Some(path) => self
                    .granted_list
                    .iter()
                    .any(|path_| path.starts_with(&path_.0)),
            }
        {
            PermissionState::Granted
        } else {
            PermissionState::Prompt
        }
    }

    pub fn request(&mut self, path: Option<&Path>) -> PermissionState {
        if let Some(path) = path {
            let (resolved_path, display_path) = resolved_and_display_path(path);
            let state = self.query(Some(&resolved_path));
            if state == PermissionState::Prompt {
                if permission_prompt(
                    &format!("read access to \"{}\"", display_path.display()),
                    self.name,
                ) {
                    self.granted_list.insert(ReadDescriptor(resolved_path));
                    PermissionState::Granted
                } else {
                    self.denied_list.insert(ReadDescriptor(resolved_path));
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else if state == PermissionState::Granted {
                self.granted_list.insert(ReadDescriptor(resolved_path));
                PermissionState::Granted
            } else {
                state
            }
        } else {
            let state = self.query(None);
            if state == PermissionState::Prompt {
                if permission_prompt("read access", self.name) {
                    self.granted_list.clear();
                    self.global_state = PermissionState::Granted;
                    PermissionState::Granted
                } else {
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else {
                state
            }
        }
    }

    pub fn revoke(&mut self, path: Option<&Path>) -> PermissionState {
        if let Some(path) = path {
            let path = resolve_from_cwd(path).unwrap();
            self.granted_list
                .retain(|path_| !path.starts_with(&path_.0));
        } else {
            self.granted_list.clear();
        }
        if self.global_state == PermissionState::Granted {
            self.global_state = PermissionState::Prompt;
        }
        self.query(path)
    }

    pub fn check(&mut self, path: &Path) -> Result<(), AnyError> {
        let (resolved_path, display_path) = resolved_and_display_path(path);
        let (result, prompted) = self.query(Some(&resolved_path)).check(
            self.name,
            Some(&format!("\"{}\"", display_path.display())),
            self.prompt,
        );
        if prompted {
            if result.is_ok() {
                self.granted_list.insert(ReadDescriptor(resolved_path));
            } else {
                self.denied_list.insert(ReadDescriptor(resolved_path));
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }

    /// As `check()`, but permission error messages will anonymize the path
    /// by replacing it with the given `display`.
    pub fn check_blind(&mut self, path: &Path, display: &str) -> Result<(), AnyError> {
        let resolved_path = resolve_from_cwd(path).unwrap();
        let (result, prompted) = self.query(Some(&resolved_path)).check(
            self.name,
            Some(&format!("<{}>", display)),
            self.prompt,
        );
        if prompted {
            if result.is_ok() {
                self.granted_list.insert(ReadDescriptor(resolved_path));
            } else {
                self.denied_list.insert(ReadDescriptor(resolved_path));
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }

    pub fn check_all(&mut self) -> Result<(), AnyError> {
        let (result, prompted) = self.query(None).check(self.name, Some("all"), self.prompt);
        if prompted {
            if result.is_ok() {
                self.global_state = PermissionState::Granted;
            } else {
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }
}

impl Default for UnaryPermission<ReadDescriptor> {
    fn default() -> Self {
        UnaryPermission::<ReadDescriptor> {
            name: "read",
            description: "read the file system",
            global_state: Default::default(),
            granted_list: Default::default(),
            denied_list: Default::default(),
            prompt: false,
        }
    }
}

impl UnaryPermission<WriteDescriptor> {
    pub fn query(&self, path: Option<&Path>) -> PermissionState {
        let path = path.map(|p| resolve_from_cwd(p).unwrap());
        if self.global_state == PermissionState::Denied
            && match path.as_ref() {
                None => true,
                Some(path) => self
                    .denied_list
                    .iter()
                    .any(|path_| path_.0.starts_with(path)),
            }
        {
            PermissionState::Denied
        } else if self.global_state == PermissionState::Granted
            || match path.as_ref() {
                None => false,
                Some(path) => self
                    .granted_list
                    .iter()
                    .any(|path_| path.starts_with(&path_.0)),
            }
        {
            PermissionState::Granted
        } else {
            PermissionState::Prompt
        }
    }

    pub fn request(&mut self, path: Option<&Path>) -> PermissionState {
        if let Some(path) = path {
            let (resolved_path, display_path) = resolved_and_display_path(path);
            let state = self.query(Some(&resolved_path));
            if state == PermissionState::Prompt {
                if permission_prompt(
                    &format!("write access to \"{}\"", display_path.display()),
                    self.name,
                ) {
                    self.granted_list.insert(WriteDescriptor(resolved_path));
                    PermissionState::Granted
                } else {
                    self.denied_list.insert(WriteDescriptor(resolved_path));
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else if state == PermissionState::Granted {
                self.granted_list.insert(WriteDescriptor(resolved_path));
                PermissionState::Granted
            } else {
                state
            }
        } else {
            let state = self.query(None);
            if state == PermissionState::Prompt {
                if permission_prompt("write access", self.name) {
                    self.granted_list.clear();
                    self.global_state = PermissionState::Granted;
                    PermissionState::Granted
                } else {
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else {
                state
            }
        }
    }

    pub fn revoke(&mut self, path: Option<&Path>) -> PermissionState {
        if let Some(path) = path {
            let path = resolve_from_cwd(path).unwrap();
            self.granted_list
                .retain(|path_| !path.starts_with(&path_.0));
        } else {
            self.granted_list.clear();
        }
        if self.global_state == PermissionState::Granted {
            self.global_state = PermissionState::Prompt;
        }
        self.query(path)
    }

    pub fn check(&mut self, path: &Path) -> Result<(), AnyError> {
        let (resolved_path, display_path) = resolved_and_display_path(path);
        let (result, prompted) = self.query(Some(&resolved_path)).check(
            self.name,
            Some(&format!("\"{}\"", display_path.display())),
            self.prompt,
        );
        if prompted {
            if result.is_ok() {
                self.granted_list.insert(WriteDescriptor(resolved_path));
            } else {
                self.denied_list.insert(WriteDescriptor(resolved_path));
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }

    pub fn check_all(&mut self) -> Result<(), AnyError> {
        let (result, prompted) = self.query(None).check(self.name, Some("all"), self.prompt);
        if prompted {
            if result.is_ok() {
                self.global_state = PermissionState::Granted;
            } else {
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }
}

impl Default for UnaryPermission<WriteDescriptor> {
    fn default() -> Self {
        UnaryPermission::<WriteDescriptor> {
            name: "write",
            description: "write to the file system",
            global_state: Default::default(),
            granted_list: Default::default(),
            denied_list: Default::default(),
            prompt: false,
        }
    }
}

impl UnaryPermission<NetDescriptor> {
    pub fn query<T: AsRef<str>>(&self, host: Option<&(T, Option<u16>)>) -> PermissionState {
        if self.global_state == PermissionState::Denied
            && match host.as_ref() {
                None => true,
                Some(host) => match host.1 {
                    None => self
                        .denied_list
                        .iter()
                        .any(|host_| host.0.as_ref() == host_.0),
                    Some(_) => self.denied_list.contains(&NetDescriptor::new(host)),
                },
            }
        {
            PermissionState::Denied
        } else if self.global_state == PermissionState::Granted
            || match host.as_ref() {
                None => false,
                Some(host) => {
                    self.granted_list
                        .contains(&NetDescriptor::new(&&(host.0.as_ref().to_string(), None)))
                        || self.granted_list.contains(&NetDescriptor::new(host))
                }
            }
        {
            PermissionState::Granted
        } else {
            PermissionState::Prompt
        }
    }

    pub fn request<T: AsRef<str>>(&mut self, host: Option<&(T, Option<u16>)>) -> PermissionState {
        if let Some(host) = host {
            let state = self.query(Some(host));
            let host = NetDescriptor::new(&host);
            if state == PermissionState::Prompt {
                if permission_prompt(&format!("network access to \"{}\"", host), self.name) {
                    self.granted_list.insert(host);
                    PermissionState::Granted
                } else {
                    self.denied_list.insert(host);
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else if state == PermissionState::Granted {
                self.granted_list.insert(host);
                PermissionState::Granted
            } else {
                state
            }
        } else {
            let state = self.query::<&str>(None);
            if state == PermissionState::Prompt {
                if permission_prompt("network access", self.name) {
                    self.granted_list.clear();
                    self.global_state = PermissionState::Granted;
                    PermissionState::Granted
                } else {
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else {
                state
            }
        }
    }

    pub fn revoke<T: AsRef<str>>(&mut self, host: Option<&(T, Option<u16>)>) -> PermissionState {
        if let Some(host) = host {
            if host.1.is_some() {
                self.granted_list
                    .remove(&NetDescriptor(host.0.as_ref().to_string(), host.1));
            }
            self.granted_list
                .remove(&NetDescriptor(host.0.as_ref().to_string(), None));
        } else {
            self.granted_list.clear();
        }
        if self.global_state == PermissionState::Granted {
            self.global_state = PermissionState::Prompt;
        }
        self.query(host)
    }

    pub fn check<T: AsRef<str>>(&mut self, host: &(T, Option<u16>)) -> Result<(), AnyError> {
        let new_host = NetDescriptor::new(&host);
        let (result, prompted) = self.query(Some(host)).check(
            self.name,
            Some(&format!("\"{}\"", new_host)),
            self.prompt,
        );
        if prompted {
            if result.is_ok() {
                self.granted_list.insert(new_host);
            } else {
                self.denied_list.insert(new_host);
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }

    pub fn check_url(&mut self, url: &url::Url) -> Result<(), AnyError> {
        let hostname = url
            .host_str()
            .ok_or_else(|| uri_error("Missing host"))?
            .to_string();
        let display_host = match url.port() {
            None => hostname.clone(),
            Some(port) => format!("{}:{}", hostname, port),
        };
        let host = &(&hostname, url.port_or_known_default());
        let (result, prompted) = self.query(Some(host)).check(
            self.name,
            Some(&format!("\"{}\"", display_host)),
            self.prompt,
        );
        if prompted {
            if result.is_ok() {
                self.granted_list.insert(NetDescriptor::new(&host));
            } else {
                self.denied_list.insert(NetDescriptor::new(&host));
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }

    pub fn check_all(&mut self) -> Result<(), AnyError> {
        let (result, prompted) =
            self.query::<&str>(None)
                .check(self.name, Some("all"), self.prompt);
        if prompted {
            if result.is_ok() {
                self.global_state = PermissionState::Granted;
            } else {
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }
}

impl Default for UnaryPermission<NetDescriptor> {
    fn default() -> Self {
        UnaryPermission::<NetDescriptor> {
            name: "net",
            description: "network",
            global_state: Default::default(),
            granted_list: Default::default(),
            denied_list: Default::default(),
            prompt: false,
        }
    }
}

impl UnaryPermission<EnvDescriptor> {
    pub fn query(&self, env: Option<&str>) -> PermissionState {
        let env = env.map(EnvVarName::new);
        if self.global_state == PermissionState::Denied
            && match env.as_ref() {
                None => true,
                Some(env) => self.denied_list.contains(&EnvDescriptor::new(env)),
            }
        {
            PermissionState::Denied
        } else if self.global_state == PermissionState::Granted
            || match env.as_ref() {
                None => false,
                Some(env) => self.granted_list.contains(&EnvDescriptor::new(env)),
            }
        {
            PermissionState::Granted
        } else {
            PermissionState::Prompt
        }
    }

    pub fn request(&mut self, env: Option<&str>) -> PermissionState {
        if let Some(env) = env {
            let state = self.query(Some(env));
            if state == PermissionState::Prompt {
                if permission_prompt(&format!("env access to \"{}\"", env), self.name) {
                    self.granted_list.insert(EnvDescriptor::new(env));
                    PermissionState::Granted
                } else {
                    self.denied_list.insert(EnvDescriptor::new(env));
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else if state == PermissionState::Granted {
                self.granted_list.insert(EnvDescriptor::new(env));
                PermissionState::Granted
            } else {
                state
            }
        } else {
            let state = self.query(None);
            if state == PermissionState::Prompt {
                if permission_prompt("env access", self.name) {
                    self.granted_list.clear();
                    self.global_state = PermissionState::Granted;
                    PermissionState::Granted
                } else {
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else {
                state
            }
        }
    }

    pub fn revoke(&mut self, env: Option<&str>) -> PermissionState {
        if let Some(env) = env {
            self.granted_list.remove(&EnvDescriptor::new(env));
        } else {
            self.granted_list.clear();
        }
        if self.global_state == PermissionState::Granted {
            self.global_state = PermissionState::Prompt;
        }
        self.query(env)
    }

    pub fn check(&mut self, env: &str) -> Result<(), AnyError> {
        let (result, prompted) =
            self.query(Some(env))
                .check(self.name, Some(&format!("\"{}\"", env)), self.prompt);
        if prompted {
            if result.is_ok() {
                self.granted_list.insert(EnvDescriptor::new(env));
            } else {
                self.denied_list.insert(EnvDescriptor::new(env));
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }

    pub fn check_all(&mut self) -> Result<(), AnyError> {
        let (result, prompted) = self.query(None).check(self.name, Some("all"), self.prompt);
        if prompted {
            if result.is_ok() {
                self.global_state = PermissionState::Granted;
            } else {
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }
}

impl Default for UnaryPermission<EnvDescriptor> {
    fn default() -> Self {
        UnaryPermission::<EnvDescriptor> {
            name: "env",
            description: "environment variables",
            global_state: Default::default(),
            granted_list: Default::default(),
            denied_list: Default::default(),
            prompt: false,
        }
    }
}

impl UnaryPermission<RunDescriptor> {
    pub fn query(&self, cmd: Option<&str>) -> PermissionState {
        if self.global_state == PermissionState::Denied
            && match cmd {
                None => true,
                Some(cmd) => self
                    .denied_list
                    .contains(&RunDescriptor::from_str(cmd).unwrap()),
            }
        {
            PermissionState::Denied
        } else if self.global_state == PermissionState::Granted
            || match cmd {
                None => false,
                Some(cmd) => self
                    .granted_list
                    .contains(&RunDescriptor::from_str(cmd).unwrap()),
            }
        {
            PermissionState::Granted
        } else {
            PermissionState::Prompt
        }
    }

    pub fn request(&mut self, cmd: Option<&str>) -> PermissionState {
        if let Some(cmd) = cmd {
            let state = self.query(Some(cmd));
            if state == PermissionState::Prompt {
                if permission_prompt(&format!("run access to \"{}\"", cmd), self.name) {
                    self.granted_list
                        .insert(RunDescriptor::from_str(cmd).unwrap());
                    PermissionState::Granted
                } else {
                    self.denied_list
                        .insert(RunDescriptor::from_str(cmd).unwrap());
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else if state == PermissionState::Granted {
                self.granted_list
                    .insert(RunDescriptor::from_str(cmd).unwrap());
                PermissionState::Granted
            } else {
                state
            }
        } else {
            let state = self.query(None);
            if state == PermissionState::Prompt {
                if permission_prompt("run access", self.name) {
                    self.granted_list.clear();
                    self.global_state = PermissionState::Granted;
                    PermissionState::Granted
                } else {
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else {
                state
            }
        }
    }

    pub fn revoke(&mut self, cmd: Option<&str>) -> PermissionState {
        if let Some(cmd) = cmd {
            self.granted_list
                .remove(&RunDescriptor::from_str(cmd).unwrap());
        } else {
            self.granted_list.clear();
        }
        if self.global_state == PermissionState::Granted {
            self.global_state = PermissionState::Prompt;
        }
        self.query(cmd)
    }

    pub fn check(&mut self, cmd: &str) -> Result<(), AnyError> {
        let (result, prompted) =
            self.query(Some(cmd))
                .check(self.name, Some(&format!("\"{}\"", cmd)), self.prompt);
        if prompted {
            if result.is_ok() {
                self.granted_list
                    .insert(RunDescriptor::from_str(cmd).unwrap());
            } else {
                self.denied_list
                    .insert(RunDescriptor::from_str(cmd).unwrap());
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }

    pub fn check_all(&mut self) -> Result<(), AnyError> {
        let (result, prompted) = self.query(None).check(self.name, Some("all"), self.prompt);
        if prompted {
            if result.is_ok() {
                self.global_state = PermissionState::Granted;
            } else {
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }
}

impl Default for UnaryPermission<RunDescriptor> {
    fn default() -> Self {
        UnaryPermission::<RunDescriptor> {
            name: "run",
            description: "run a subprocess",
            global_state: Default::default(),
            granted_list: Default::default(),
            denied_list: Default::default(),
            prompt: false,
        }
    }
}

impl UnaryPermission<FfiDescriptor> {
    pub fn query(&self, path: Option<&Path>) -> PermissionState {
        let path = path.map(|p| resolve_from_cwd(p).unwrap());
        if self.global_state == PermissionState::Denied
            && match path.as_ref() {
                None => true,
                Some(path) => self.denied_list.contains(&FfiDescriptor(path.clone())),
            }
        {
            PermissionState::Denied
        } else if self.global_state == PermissionState::Granted
            || match path.as_ref() {
                None => false,
                Some(path) => self.granted_list.contains(&FfiDescriptor(path.clone())),
            }
        {
            PermissionState::Granted
        } else {
            PermissionState::Prompt
        }
    }

    pub fn request(&mut self, path: Option<&Path>) -> PermissionState {
        if let Some(path) = path {
            let (resolved_path, display_path) = resolved_and_display_path(path);
            let state = self.query(Some(&resolved_path));
            if state == PermissionState::Prompt {
                if permission_prompt(
                    &format!("ffi access to \"{}\"", display_path.display()),
                    self.name,
                ) {
                    self.granted_list.insert(FfiDescriptor(resolved_path));
                    PermissionState::Granted
                } else {
                    self.denied_list.insert(FfiDescriptor(resolved_path));
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else if state == PermissionState::Granted {
                self.granted_list.insert(FfiDescriptor(resolved_path));
                PermissionState::Granted
            } else {
                state
            }
        } else {
            let state = self.query(None);
            if state == PermissionState::Prompt {
                if permission_prompt("ffi access", self.name) {
                    self.granted_list.clear();
                    self.global_state = PermissionState::Granted;
                    PermissionState::Granted
                } else {
                    self.global_state = PermissionState::Denied;
                    PermissionState::Denied
                }
            } else {
                state
            }
        }
    }

    pub fn revoke(&mut self, path: Option<&Path>) -> PermissionState {
        if let Some(path) = path {
            let path = resolve_from_cwd(path).unwrap();
            self.granted_list.remove(&FfiDescriptor(path));
        } else {
            self.granted_list.clear();
        }
        if self.global_state == PermissionState::Granted {
            self.global_state = PermissionState::Prompt;
        }
        self.query(path)
    }

    pub fn check(&mut self, path: Option<&Path>) -> Result<(), AnyError> {
        if let Some(path) = path {
            let (resolved_path, display_path) = resolved_and_display_path(path);
            let (result, prompted) = self.query(Some(&resolved_path)).check(
                self.name,
                Some(&format!("\"{}\"", display_path.display())),
                self.prompt,
            );

            if prompted {
                if result.is_ok() {
                    self.granted_list.insert(FfiDescriptor(resolved_path));
                } else {
                    self.denied_list.insert(FfiDescriptor(resolved_path));
                    self.global_state = PermissionState::Denied;
                }
            }

            result
        } else {
            let (result, prompted) = self.query(None).check(self.name, None, self.prompt);

            if prompted {
                if result.is_ok() {
                    self.global_state = PermissionState::Granted;
                } else {
                    self.global_state = PermissionState::Denied;
                }
            }

            result
        }
    }

    pub fn check_all(&mut self) -> Result<(), AnyError> {
        let (result, prompted) = self.query(None).check(self.name, Some("all"), self.prompt);
        if prompted {
            if result.is_ok() {
                self.global_state = PermissionState::Granted;
            } else {
                self.global_state = PermissionState::Denied;
            }
        }
        result
    }
}

impl Default for UnaryPermission<FfiDescriptor> {
    fn default() -> Self {
        UnaryPermission::<FfiDescriptor> {
            name: "ffi",
            description: "load a dynamic library",
            global_state: Default::default(),
            granted_list: Default::default(),
            denied_list: Default::default(),
            prompt: false,
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct Permissions {
    pub read: UnaryPermission<ReadDescriptor>,
    pub write: UnaryPermission<WriteDescriptor>,
    pub net: UnaryPermission<NetDescriptor>,
    pub env: UnaryPermission<EnvDescriptor>,
    pub run: UnaryPermission<RunDescriptor>,
    pub ffi: UnaryPermission<FfiDescriptor>,
    pub hrtime: UnitPermission,
}

impl Default for Permissions {
    fn default() -> Self {
        Self {
            read: Permissions::new_read(&None, false),
            write: Permissions::new_write(&None, false),
            net: Permissions::new_net(&None, false),
            env: Permissions::new_env(&None, false),
            run: Permissions::new_run(&None, false),
            ffi: Permissions::new_ffi(&None, false),
            hrtime: Permissions::new_hrtime(false),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PermissionsOptions {
    pub allow_env: Option<Vec<String>>,
    pub allow_hrtime: bool,
    pub allow_net: Option<Vec<String>>,
    pub allow_ffi: Option<Vec<PathBuf>>,
    pub allow_read: Option<Vec<PathBuf>>,
    pub allow_run: Option<Vec<String>>,
    pub allow_write: Option<Vec<PathBuf>>,
    pub prompt: bool,
}

impl Permissions {
    pub fn new_read(state: &Option<Vec<PathBuf>>, prompt: bool) -> UnaryPermission<ReadDescriptor> {
        UnaryPermission::<ReadDescriptor> {
            global_state: global_state_from_option(state),
            granted_list: resolve_read_allowlist(state),
            prompt,
            ..Default::default()
        }
    }

    pub fn new_write(
        state: &Option<Vec<PathBuf>>,
        prompt: bool,
    ) -> UnaryPermission<WriteDescriptor> {
        UnaryPermission::<WriteDescriptor> {
            global_state: global_state_from_option(state),
            granted_list: resolve_write_allowlist(state),
            prompt,
            ..Default::default()
        }
    }

    pub fn new_net(state: &Option<Vec<String>>, prompt: bool) -> UnaryPermission<NetDescriptor> {
        UnaryPermission::<NetDescriptor> {
            global_state: global_state_from_option(state),
            granted_list: state
                .as_ref()
                .map(|v| {
                    v.iter()
                        .map(|x| NetDescriptor::from_string(x.clone()))
                        .collect()
                })
                .unwrap_or_else(HashSet::new),
            prompt,
            ..Default::default()
        }
    }

    pub fn new_env(state: &Option<Vec<String>>, prompt: bool) -> UnaryPermission<EnvDescriptor> {
        UnaryPermission::<EnvDescriptor> {
            global_state: global_state_from_option(state),
            granted_list: state
                .as_ref()
                .map(|v| v.iter().map(EnvDescriptor::new).collect())
                .unwrap_or_else(HashSet::new),
            prompt,
            ..Default::default()
        }
    }

    pub fn new_run(state: &Option<Vec<String>>, prompt: bool) -> UnaryPermission<RunDescriptor> {
        UnaryPermission::<RunDescriptor> {
            global_state: global_state_from_option(state),
            granted_list: state
                .as_ref()
                .map(|v| {
                    v.iter()
                        .map(|x| RunDescriptor::from_str(x).unwrap())
                        .collect()
                })
                .unwrap_or_else(HashSet::new),
            prompt,
            ..Default::default()
        }
    }

    pub fn new_ffi(state: &Option<Vec<PathBuf>>, prompt: bool) -> UnaryPermission<FfiDescriptor> {
        UnaryPermission::<FfiDescriptor> {
            global_state: global_state_from_option(state),
            granted_list: resolve_ffi_allowlist(state),
            prompt,
            ..Default::default()
        }
    }

    pub fn new_hrtime(state: bool) -> UnitPermission {
        unit_permission_from_flag_bool(
            state,
            "hrtime",
            "high precision time",
            false, // never prompt for hrtime
        )
    }

    pub fn from_options(opts: &PermissionsOptions) -> Self {
        Self {
            read: Permissions::new_read(&opts.allow_read, opts.prompt),
            write: Permissions::new_write(&opts.allow_write, opts.prompt),
            net: Permissions::new_net(&opts.allow_net, opts.prompt),
            env: Permissions::new_env(&opts.allow_env, opts.prompt),
            run: Permissions::new_run(&opts.allow_run, opts.prompt),
            ffi: Permissions::new_ffi(&opts.allow_ffi, opts.prompt),
            hrtime: Permissions::new_hrtime(opts.allow_hrtime),
        }
    }

    pub fn allow_all() -> Self {
        Self {
            read: Permissions::new_read(&Some(vec![]), false),
            write: Permissions::new_write(&Some(vec![]), false),
            net: Permissions::new_net(&Some(vec![]), false),
            env: Permissions::new_env(&Some(vec![]), false),
            run: Permissions::new_run(&Some(vec![]), false),
            ffi: Permissions::new_ffi(&Some(vec![]), false),
            hrtime: Permissions::new_hrtime(true),
        }
    }

    /// A helper function that determines if the module specifier is a local or
    /// remote, and performs a read or net check for the specifier.
    pub fn check_specifier(&mut self, specifier: &ModuleSpecifier) -> Result<(), AnyError> {
        match specifier.scheme() {
            "file" => match specifier.to_file_path() {
                Ok(path) => self.read.check(&path),
                Err(_) => Err(uri_error(format!(
                    "Invalid file path.\n  Specifier: {}",
                    specifier
                ))),
            },
            "data" => Ok(()),
            "blob" => Ok(()),
            _ => self.net.check_url(specifier),
        }
    }
}

impl deno_net::NetPermissions for Permissions {
    fn check_net<T: AsRef<str>>(&mut self, host: &(T, Option<u16>)) -> Result<(), AnyError> {
        self.net.check(host)
    }

    fn check_read(&mut self, path: &Path) -> Result<(), AnyError> {
        self.read.check(path)
    }

    fn check_write(&mut self, path: &Path) -> Result<(), AnyError> {
        self.write.check(path)
    }
}

impl deno_fetch::FetchPermissions for Permissions {
    fn check_net_url(&mut self, url: &url::Url) -> Result<(), AnyError> {
        self.net.check_url(url)
    }

    fn check_read(&mut self, path: &Path) -> Result<(), AnyError> {
        self.read.check(path)
    }
}

impl deno_web::TimersPermission for Permissions {
    fn allow_hrtime(&mut self) -> bool {
        self.hrtime.check().is_ok()
    }

    fn check_unstable(&self, state: &OpState, api_name: &'static str) {
        crate::ops::check_unstable(state, api_name);
    }
}

impl deno_websocket::WebSocketPermissions for Permissions {
    fn check_net_url(&mut self, url: &url::Url) -> Result<(), AnyError> {
        self.net.check_url(url)
    }
}

#[cfg(feature = "ext_ffi")]
impl deno_ffi::FfiPermissions for Permissions {
    fn check(&mut self, path: Option<&Path>) -> Result<(), AnyError> {
        self.ffi.check(path)
    }
}

fn unit_permission_from_flag_bool(
    flag: bool,
    name: &'static str,
    description: &'static str,
    prompt: bool,
) -> UnitPermission {
    UnitPermission {
        name,
        description,
        state: if flag {
            PermissionState::Granted
        } else {
            PermissionState::Prompt
        },
        prompt,
    }
}

fn global_state_from_option<T>(flag: &Option<Vec<T>>) -> PermissionState {
    if matches!(flag, Some(v) if v.is_empty()) {
        PermissionState::Granted
    } else {
        PermissionState::Prompt
    }
}

pub fn resolve_read_allowlist(allow: &Option<Vec<PathBuf>>) -> HashSet<ReadDescriptor> {
    if let Some(v) = allow {
        v.iter()
            .map(|raw_path| ReadDescriptor(resolve_from_cwd(Path::new(&raw_path)).unwrap()))
            .collect()
    } else {
        HashSet::new()
    }
}

pub fn resolve_write_allowlist(allow: &Option<Vec<PathBuf>>) -> HashSet<WriteDescriptor> {
    if let Some(v) = allow {
        v.iter()
            .map(|raw_path| WriteDescriptor(resolve_from_cwd(Path::new(&raw_path)).unwrap()))
            .collect()
    } else {
        HashSet::new()
    }
}

pub fn resolve_ffi_allowlist(allow: &Option<Vec<PathBuf>>) -> HashSet<FfiDescriptor> {
    if let Some(v) = allow {
        v.iter()
            .map(|raw_path| FfiDescriptor(resolve_from_cwd(Path::new(&raw_path)).unwrap()))
            .collect()
    } else {
        HashSet::new()
    }
}

/// Arbitrary helper. Resolves the path from CWD, and also gets a path that
/// can be displayed without leaking the CWD when not allowed.
fn resolved_and_display_path(path: &Path) -> (PathBuf, PathBuf) {
    let resolved_path = resolve_from_cwd(path).unwrap();
    let display_path = path.to_path_buf();
    (resolved_path, display_path)
}

fn escalation_error() -> AnyError {
    custom_error(
        "PermissionDenied",
        "Can't escalate parent thread permissions",
    )
}

#[derive(Debug, PartialEq)]
pub enum ChildUnitPermissionArg {
    Inherit,
    Granted,
    NotGranted,
}

impl<'de> Deserialize<'de> for ChildUnitPermissionArg {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ChildUnitPermissionArgVisitor;
        impl<'de> de::Visitor<'de> for ChildUnitPermissionArgVisitor {
            type Value = ChildUnitPermissionArg;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("\"inherit\" or boolean")
            }

            fn visit_unit<E>(self) -> Result<ChildUnitPermissionArg, E>
            where
                E: de::Error,
            {
                Ok(ChildUnitPermissionArg::NotGranted)
            }

            fn visit_str<E>(self, v: &str) -> Result<ChildUnitPermissionArg, E>
            where
                E: de::Error,
            {
                if v == "inherit" {
                    Ok(ChildUnitPermissionArg::Inherit)
                } else {
                    Err(de::Error::invalid_value(de::Unexpected::Str(v), &self))
                }
            }

            fn visit_bool<E>(self, v: bool) -> Result<ChildUnitPermissionArg, E>
            where
                E: de::Error,
            {
                match v {
                    true => Ok(ChildUnitPermissionArg::Granted),
                    false => Ok(ChildUnitPermissionArg::NotGranted),
                }
            }
        }
        deserializer.deserialize_any(ChildUnitPermissionArgVisitor)
    }
}

#[derive(Debug, PartialEq)]
pub enum ChildUnaryPermissionArg {
    Inherit,
    Granted,
    NotGranted,
    GrantedList(Vec<String>),
}

impl<'de> Deserialize<'de> for ChildUnaryPermissionArg {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ChildUnaryPermissionArgVisitor;
        impl<'de> de::Visitor<'de> for ChildUnaryPermissionArgVisitor {
            type Value = ChildUnaryPermissionArg;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("\"inherit\" or boolean or string[]")
            }

            fn visit_unit<E>(self) -> Result<ChildUnaryPermissionArg, E>
            where
                E: de::Error,
            {
                Ok(ChildUnaryPermissionArg::NotGranted)
            }

            fn visit_str<E>(self, v: &str) -> Result<ChildUnaryPermissionArg, E>
            where
                E: de::Error,
            {
                if v == "inherit" {
                    Ok(ChildUnaryPermissionArg::Inherit)
                } else {
                    Err(de::Error::invalid_value(de::Unexpected::Str(v), &self))
                }
            }

            fn visit_bool<E>(self, v: bool) -> Result<ChildUnaryPermissionArg, E>
            where
                E: de::Error,
            {
                match v {
                    true => Ok(ChildUnaryPermissionArg::Granted),
                    false => Ok(ChildUnaryPermissionArg::NotGranted),
                }
            }

            fn visit_seq<V>(self, mut v: V) -> Result<ChildUnaryPermissionArg, V::Error>
            where
                V: de::SeqAccess<'de>,
            {
                let mut granted_list = vec![];
                while let Some(value) = v.next_element::<String>()? {
                    granted_list.push(value);
                }
                Ok(ChildUnaryPermissionArg::GrantedList(granted_list))
            }
        }
        deserializer.deserialize_any(ChildUnaryPermissionArgVisitor)
    }
}

/// Directly deserializable from JS worker and test permission options.
#[derive(Debug, PartialEq)]
pub struct ChildPermissionsArg {
    env: ChildUnaryPermissionArg,
    hrtime: ChildUnitPermissionArg,
    net: ChildUnaryPermissionArg,
    ffi: ChildUnaryPermissionArg,
    read: ChildUnaryPermissionArg,
    run: ChildUnaryPermissionArg,
    write: ChildUnaryPermissionArg,
}

impl ChildPermissionsArg {
    pub fn inherit() -> Self {
        ChildPermissionsArg {
            env: ChildUnaryPermissionArg::Inherit,
            hrtime: ChildUnitPermissionArg::Inherit,
            net: ChildUnaryPermissionArg::Inherit,
            ffi: ChildUnaryPermissionArg::Inherit,
            read: ChildUnaryPermissionArg::Inherit,
            run: ChildUnaryPermissionArg::Inherit,
            write: ChildUnaryPermissionArg::Inherit,
        }
    }

    pub fn none() -> Self {
        ChildPermissionsArg {
            env: ChildUnaryPermissionArg::NotGranted,
            hrtime: ChildUnitPermissionArg::NotGranted,
            net: ChildUnaryPermissionArg::NotGranted,
            ffi: ChildUnaryPermissionArg::NotGranted,
            read: ChildUnaryPermissionArg::NotGranted,
            run: ChildUnaryPermissionArg::NotGranted,
            write: ChildUnaryPermissionArg::NotGranted,
        }
    }
}

impl<'de> Deserialize<'de> for ChildPermissionsArg {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ChildPermissionsArgVisitor;
        impl<'de> de::Visitor<'de> for ChildPermissionsArgVisitor {
            type Value = ChildPermissionsArg;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("\"inherit\" or \"none\" or object")
            }

            fn visit_unit<E>(self) -> Result<ChildPermissionsArg, E>
            where
                E: de::Error,
            {
                Ok(ChildPermissionsArg::inherit())
            }

            fn visit_str<E>(self, v: &str) -> Result<ChildPermissionsArg, E>
            where
                E: de::Error,
            {
                if v == "inherit" {
                    Ok(ChildPermissionsArg::inherit())
                } else if v == "none" {
                    Ok(ChildPermissionsArg::none())
                } else {
                    Err(de::Error::invalid_value(de::Unexpected::Str(v), &self))
                }
            }

            fn visit_map<V>(self, mut v: V) -> Result<ChildPermissionsArg, V::Error>
            where
                V: de::MapAccess<'de>,
            {
                let mut child_permissions_arg = ChildPermissionsArg::none();
                while let Some((key, value)) = v.next_entry::<String, serde_json::Value>()? {
                    if key == "env" {
                        let arg = serde_json::from_value::<ChildUnaryPermissionArg>(value);
                        child_permissions_arg.env = arg.map_err(|e| {
                            de::Error::custom(format!("(deno.permissions.env) {}", e))
                        })?;
                    } else if key == "hrtime" {
                        let arg = serde_json::from_value::<ChildUnitPermissionArg>(value);
                        child_permissions_arg.hrtime = arg.map_err(|e| {
                            de::Error::custom(format!("(deno.permissions.hrtime) {}", e))
                        })?;
                    } else if key == "net" {
                        let arg = serde_json::from_value::<ChildUnaryPermissionArg>(value);
                        child_permissions_arg.net = arg.map_err(|e| {
                            de::Error::custom(format!("(deno.permissions.net) {}", e))
                        })?;
                    } else if key == "ffi" {
                        let arg = serde_json::from_value::<ChildUnaryPermissionArg>(value);
                        child_permissions_arg.ffi = arg.map_err(|e| {
                            de::Error::custom(format!("(deno.permissions.ffi) {}", e))
                        })?;
                    } else if key == "read" {
                        let arg = serde_json::from_value::<ChildUnaryPermissionArg>(value);
                        child_permissions_arg.read = arg.map_err(|e| {
                            de::Error::custom(format!("(deno.permissions.read) {}", e))
                        })?;
                    } else if key == "run" {
                        let arg = serde_json::from_value::<ChildUnaryPermissionArg>(value);
                        child_permissions_arg.run = arg.map_err(|e| {
                            de::Error::custom(format!("(deno.permissions.run) {}", e))
                        })?;
                    } else if key == "write" {
                        let arg = serde_json::from_value::<ChildUnaryPermissionArg>(value);
                        child_permissions_arg.write = arg.map_err(|e| {
                            de::Error::custom(format!("(deno.permissions.write) {}", e))
                        })?;
                    } else {
                        return Err(de::Error::custom("unknown permission name"));
                    }
                }
                Ok(child_permissions_arg)
            }
        }
        deserializer.deserialize_any(ChildPermissionsArgVisitor)
    }
}

pub fn create_child_permissions(
    main_perms: &mut Permissions,
    child_permissions_arg: ChildPermissionsArg,
) -> Result<Permissions, AnyError> {
    let mut worker_perms = Permissions::default();
    match child_permissions_arg.env {
        ChildUnaryPermissionArg::Inherit => {
            worker_perms.env = main_perms.env.clone();
        }
        ChildUnaryPermissionArg::Granted => {
            if main_perms.env.check_all().is_err() {
                return Err(escalation_error());
            }
            worker_perms.env.global_state = PermissionState::Granted;
        }
        ChildUnaryPermissionArg::NotGranted => {}
        ChildUnaryPermissionArg::GrantedList(granted_list) => {
            worker_perms.env.granted_list =
                Permissions::new_env(&Some(granted_list), false).granted_list;
            if !worker_perms
                .env
                .granted_list
                .iter()
                .all(|desc| main_perms.env.check(desc.as_ref()).is_ok())
            {
                return Err(escalation_error());
            }
        }
    }
    worker_perms.env.denied_list = main_perms.env.denied_list.clone();
    if main_perms.env.global_state == PermissionState::Denied {
        worker_perms.env.global_state = PermissionState::Denied;
    }
    worker_perms.env.prompt = main_perms.env.prompt;
    match child_permissions_arg.hrtime {
        ChildUnitPermissionArg::Inherit => {
            worker_perms.hrtime = main_perms.hrtime.clone();
        }
        ChildUnitPermissionArg::Granted => {
            if main_perms.hrtime.check().is_err() {
                return Err(escalation_error());
            }
            worker_perms.hrtime.state = PermissionState::Granted;
        }
        ChildUnitPermissionArg::NotGranted => {}
    }
    if main_perms.hrtime.state == PermissionState::Denied {
        worker_perms.hrtime.state = PermissionState::Denied;
    }
    worker_perms.hrtime.prompt = main_perms.hrtime.prompt;
    match child_permissions_arg.net {
        ChildUnaryPermissionArg::Inherit => {
            worker_perms.net = main_perms.net.clone();
        }
        ChildUnaryPermissionArg::Granted => {
            if main_perms.net.check_all().is_err() {
                return Err(escalation_error());
            }
            worker_perms.net.global_state = PermissionState::Granted;
        }
        ChildUnaryPermissionArg::NotGranted => {}
        ChildUnaryPermissionArg::GrantedList(granted_list) => {
            worker_perms.net.granted_list =