1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-25 00:29:09 -05:00

refactor: Elevate DenoPermissions lock to top level (#3398)

This commit is contained in:
Kevin (Kun) "Kassimo" Qian 2019-11-24 07:42:30 -08:00 committed by Ry Dahl
parent 9e97eb2879
commit bca23e6433
9 changed files with 166 additions and 196 deletions

View file

@ -229,7 +229,7 @@ impl TsCompiler {
fn setup_worker(global_state: ThreadSafeGlobalState) -> Worker { fn setup_worker(global_state: ThreadSafeGlobalState) -> Worker {
let (int, ext) = ThreadSafeState::create_channels(); let (int, ext) = ThreadSafeState::create_channels();
let worker_state = let worker_state =
ThreadSafeState::new(global_state.clone(), None, true, int) ThreadSafeState::new(global_state.clone(), None, None, true, int)
.expect("Unable to create worker state"); .expect("Unable to create worker state");
// Count how many times we start the compiler worker. // Count how many times we start the compiler worker.

View file

@ -47,7 +47,7 @@ impl WasmCompiler {
fn setup_worker(global_state: ThreadSafeGlobalState) -> Worker { fn setup_worker(global_state: ThreadSafeGlobalState) -> Worker {
let (int, ext) = ThreadSafeState::create_channels(); let (int, ext) = ThreadSafeState::create_channels();
let worker_state = let worker_state =
ThreadSafeState::new(global_state.clone(), None, true, int) ThreadSafeState::new(global_state.clone(), None, None, true, int)
.expect("Unable to create worker state"); .expect("Unable to create worker state");
// Count how many times we start the compiler worker. // Count how many times we start the compiler worker.

View file

@ -118,6 +118,7 @@ fn create_worker_and_state(
let (int, ext) = ThreadSafeState::create_channels(); let (int, ext) = ThreadSafeState::create_channels();
let state = ThreadSafeState::new( let state = ThreadSafeState::new(
global_state.clone(), global_state.clone(),
None,
global_state.main_module.clone(), global_state.main_module.clone(),
true, true,
int, int,

View file

@ -33,7 +33,8 @@ pub fn op_query_permission(
_zero_copy: Option<PinnedBuf>, _zero_copy: Option<PinnedBuf>,
) -> Result<JsonOp, ErrBox> { ) -> Result<JsonOp, ErrBox> {
let args: PermissionArgs = serde_json::from_value(args)?; let args: PermissionArgs = serde_json::from_value(args)?;
let perm = state.permissions.get_permission_state( let permissions = state.permissions.lock().unwrap();
let perm = permissions.get_permission_state(
&args.name, &args.name,
&args.url.as_ref().map(String::as_str), &args.url.as_ref().map(String::as_str),
&args.path.as_ref().map(String::as_str), &args.path.as_ref().map(String::as_str),
@ -47,16 +48,17 @@ pub fn op_revoke_permission(
_zero_copy: Option<PinnedBuf>, _zero_copy: Option<PinnedBuf>,
) -> Result<JsonOp, ErrBox> { ) -> Result<JsonOp, ErrBox> {
let args: PermissionArgs = serde_json::from_value(args)?; let args: PermissionArgs = serde_json::from_value(args)?;
let mut permissions = state.permissions.lock().unwrap();
match args.name.as_ref() { match args.name.as_ref() {
"run" => state.permissions.allow_run.revoke(), "run" => permissions.allow_run.revoke(),
"read" => state.permissions.allow_read.revoke(), "read" => permissions.allow_read.revoke(),
"write" => state.permissions.allow_write.revoke(), "write" => permissions.allow_write.revoke(),
"net" => state.permissions.allow_net.revoke(), "net" => permissions.allow_net.revoke(),
"env" => state.permissions.allow_env.revoke(), "env" => permissions.allow_env.revoke(),
"hrtime" => state.permissions.allow_hrtime.revoke(), "hrtime" => permissions.allow_hrtime.revoke(),
_ => {} _ => {}
}; };
let perm = state.permissions.get_permission_state( let perm = permissions.get_permission_state(
&args.name, &args.name,
&args.url.as_ref().map(String::as_str), &args.url.as_ref().map(String::as_str),
&args.path.as_ref().map(String::as_str), &args.path.as_ref().map(String::as_str),
@ -70,23 +72,18 @@ pub fn op_request_permission(
_zero_copy: Option<PinnedBuf>, _zero_copy: Option<PinnedBuf>,
) -> Result<JsonOp, ErrBox> { ) -> Result<JsonOp, ErrBox> {
let args: PermissionArgs = serde_json::from_value(args)?; let args: PermissionArgs = serde_json::from_value(args)?;
let mut permissions = state.permissions.lock().unwrap();
let perm = match args.name.as_ref() { let perm = match args.name.as_ref() {
"run" => Ok(state.permissions.request_run()), "run" => Ok(permissions.request_run()),
"read" => Ok( "read" => {
state Ok(permissions.request_read(&args.path.as_ref().map(String::as_str)))
.permissions }
.request_read(&args.path.as_ref().map(String::as_str)), "write" => {
), Ok(permissions.request_write(&args.path.as_ref().map(String::as_str)))
"write" => Ok( }
state "net" => permissions.request_net(&args.url.as_ref().map(String::as_str)),
.permissions "env" => Ok(permissions.request_env()),
.request_write(&args.path.as_ref().map(String::as_str)), "hrtime" => Ok(permissions.request_hrtime()),
),
"net" => state
.permissions
.request_net(&args.url.as_ref().map(String::as_str)),
"env" => Ok(state.permissions.request_env()),
"hrtime" => Ok(state.permissions.request_hrtime()),
n => Err(type_error(format!("No such permission name: {}", n))), n => Err(type_error(format!("No such permission name: {}", n))),
}?; }?;
Ok(JsonOp::Sync(json!({ "state": perm.to_string() }))) Ok(JsonOp::Sync(json!({ "state": perm.to_string() })))

View file

@ -66,11 +66,12 @@ fn op_now(
let seconds = state.start_time.elapsed().as_secs(); let seconds = state.start_time.elapsed().as_secs();
let mut subsec_nanos = state.start_time.elapsed().subsec_nanos(); let mut subsec_nanos = state.start_time.elapsed().subsec_nanos();
let reduced_time_precision = 2_000_000; // 2ms in nanoseconds let reduced_time_precision = 2_000_000; // 2ms in nanoseconds
let permissions = state.permissions.lock().unwrap();
// If the permission is not enabled // If the permission is not enabled
// Round the nano result on 2 milliseconds // Round the nano result on 2 milliseconds
// see: https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#Reduced_time_precision // see: https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#Reduced_time_precision
if !state.permissions.allow_hrtime.is_allow() { if !permissions.allow_hrtime.is_allow() {
subsec_nanos -= subsec_nanos % reduced_time_precision subsec_nanos -= subsec_nanos % reduced_time_precision
} }

View file

@ -142,10 +142,13 @@ fn op_create_worker(
let (int, ext) = ThreadSafeState::create_channels(); let (int, ext) = ThreadSafeState::create_channels();
let child_state = ThreadSafeState::new( let child_state = ThreadSafeState::new(
state.global_state.clone(), state.global_state.clone(),
Some(parent_state.permissions.clone()), // by default share with parent
Some(module_specifier.clone()), Some(module_specifier.clone()),
include_deno_namespace, include_deno_namespace,
int, int,
)?; )?;
// TODO: add a new option to make child worker not sharing permissions
// with parent (aka .clone(), requests from child won't reflect in parent)
let name = format!("USER-WORKER-{}", specifier); let name = format!("USER-WORKER-{}", specifier);
let deno_main_call = format!("denoMain({})", include_deno_namespace); let deno_main_call = format!("denoMain({})", include_deno_namespace);
let mut worker = let mut worker =

View file

@ -13,166 +13,131 @@ use std::io;
use std::path::PathBuf; use std::path::PathBuf;
#[cfg(test)] #[cfg(test)]
use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicBool;
use std::sync::atomic::{AtomicUsize, Ordering}; #[cfg(test)]
use std::sync::Arc; use std::sync::atomic::Ordering;
use url::Url; use url::Url;
const PERMISSION_EMOJI: &str = "⚠️"; const PERMISSION_EMOJI: &str = "⚠️";
/// Tri-state value for storing permission state /// Tri-state value for storing permission state
#[derive(PartialEq, Debug)] #[derive(PartialEq, Debug, Clone, Copy)]
pub enum PermissionAccessorState { pub enum PermissionState {
Allow = 0, Allow = 0,
Ask = 1, Ask = 1,
Deny = 2, Deny = 2,
} }
impl PermissionAccessorState { impl PermissionState {
/// Checks the permission state and returns the result. /// Checks the permission state and returns the result.
pub fn check(self, msg: &str, err_msg: &str) -> Result<(), ErrBox> { pub fn check(self, msg: &str, err_msg: &str) -> Result<(), ErrBox> {
if self == PermissionAccessorState::Allow { if self == PermissionState::Allow {
log_perm_access(msg); log_perm_access(msg);
return Ok(()); return Ok(());
} }
Err(permission_denied_msg(err_msg.to_string())) Err(permission_denied_msg(err_msg.to_string()))
} }
pub fn is_allow(self) -> bool {
self == PermissionState::Allow
}
/// If the state is "Allow" walk it back to the default "Ask"
/// Don't do anything if state is "Deny"
pub fn revoke(&mut self) {
if *self == PermissionState::Allow {
*self = PermissionState::Ask;
}
}
/// Requests the permission.
pub fn request(&mut self, msg: &str) -> PermissionState {
if *self != PermissionState::Ask {
return *self;
}
if permission_prompt(msg) {
*self = PermissionState::Allow;
} else {
*self = PermissionState::Deny;
}
*self
}
} }
impl From<usize> for PermissionAccessorState { impl From<usize> for PermissionState {
fn from(val: usize) -> Self { fn from(val: usize) -> Self {
match val { match val {
0 => PermissionAccessorState::Allow, 0 => PermissionState::Allow,
1 => PermissionAccessorState::Ask, 1 => PermissionState::Ask,
2 => PermissionAccessorState::Deny, 2 => PermissionState::Deny,
_ => unreachable!(), _ => unreachable!(),
} }
} }
} }
impl From<bool> for PermissionAccessorState { impl From<bool> for PermissionState {
fn from(val: bool) -> Self { fn from(val: bool) -> Self {
if val { if val {
PermissionAccessorState::Allow PermissionState::Allow
} else { } else {
PermissionAccessorState::Ask PermissionState::Ask
} }
} }
} }
impl fmt::Display for PermissionAccessorState { impl fmt::Display for PermissionState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
PermissionAccessorState::Allow => f.pad("granted"), PermissionState::Allow => f.pad("granted"),
PermissionAccessorState::Ask => f.pad("prompt"), PermissionState::Ask => f.pad("prompt"),
PermissionAccessorState::Deny => f.pad("denied"), PermissionState::Deny => f.pad("denied"),
} }
} }
} }
#[derive(Clone, Debug)] impl Default for PermissionState {
pub struct PermissionAccessor {
state: Arc<AtomicUsize>,
}
impl PermissionAccessor {
pub fn new(state: PermissionAccessorState) -> Self {
Self {
state: Arc::new(AtomicUsize::new(state as usize)),
}
}
/// If the state is "Allow" walk it back to the default "Ask"
/// Don't do anything if state is "Deny"
pub fn revoke(&self) {
if self.is_allow() {
self.set_state(PermissionAccessorState::Ask)
}
}
/// Requests the permission.
pub fn request(&self, msg: &str) -> PermissionAccessorState {
let state = self.get_state();
if state != PermissionAccessorState::Ask {
return state;
}
self.set_state(if permission_prompt(msg) {
PermissionAccessorState::Allow
} else {
PermissionAccessorState::Deny
});
self.get_state()
}
pub fn is_allow(&self) -> bool {
self.get_state() == PermissionAccessorState::Allow
}
#[inline]
pub fn get_state(&self) -> PermissionAccessorState {
self.state.load(Ordering::SeqCst).into()
}
fn set_state(&self, state: PermissionAccessorState) {
self.state.store(state as usize, Ordering::SeqCst)
}
}
impl From<bool> for PermissionAccessor {
fn from(val: bool) -> Self {
Self::new(PermissionAccessorState::from(val))
}
}
impl Default for PermissionAccessor {
fn default() -> Self { fn default() -> Self {
Self { PermissionState::Ask
state: Arc::new(AtomicUsize::new(PermissionAccessorState::Ask as usize)),
}
} }
} }
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct DenoPermissions { pub struct DenoPermissions {
// Keep in sync with cli/js/permissions.ts // Keep in sync with cli/js/permissions.ts
pub allow_read: PermissionAccessor, pub allow_read: PermissionState,
pub read_whitelist: Arc<HashSet<String>>, pub read_whitelist: HashSet<String>,
pub allow_write: PermissionAccessor, pub allow_write: PermissionState,
pub write_whitelist: Arc<HashSet<String>>, pub write_whitelist: HashSet<String>,
pub allow_net: PermissionAccessor, pub allow_net: PermissionState,
pub net_whitelist: Arc<HashSet<String>>, pub net_whitelist: HashSet<String>,
pub allow_env: PermissionAccessor, pub allow_env: PermissionState,
pub allow_run: PermissionAccessor, pub allow_run: PermissionState,
pub allow_hrtime: PermissionAccessor, pub allow_hrtime: PermissionState,
} }
impl DenoPermissions { impl DenoPermissions {
pub fn from_flags(flags: &DenoFlags) -> Self { pub fn from_flags(flags: &DenoFlags) -> Self {
Self { Self {
allow_read: PermissionAccessor::from(flags.allow_read), allow_read: PermissionState::from(flags.allow_read),
read_whitelist: Arc::new(flags.read_whitelist.iter().cloned().collect()), read_whitelist: flags.read_whitelist.iter().cloned().collect(),
allow_write: PermissionAccessor::from(flags.allow_write), allow_write: PermissionState::from(flags.allow_write),
write_whitelist: Arc::new( write_whitelist: flags.write_whitelist.iter().cloned().collect(),
flags.write_whitelist.iter().cloned().collect(), allow_net: PermissionState::from(flags.allow_net),
), net_whitelist: flags.net_whitelist.iter().cloned().collect(),
allow_net: PermissionAccessor::from(flags.allow_net), allow_env: PermissionState::from(flags.allow_env),
net_whitelist: Arc::new(flags.net_whitelist.iter().cloned().collect()), allow_run: PermissionState::from(flags.allow_run),
allow_env: PermissionAccessor::from(flags.allow_env), allow_hrtime: PermissionState::from(flags.allow_hrtime),
allow_run: PermissionAccessor::from(flags.allow_run),
allow_hrtime: PermissionAccessor::from(flags.allow_hrtime),
} }
} }
pub fn check_run(&self) -> Result<(), ErrBox> { pub fn check_run(&self) -> Result<(), ErrBox> {
self.allow_run.get_state().check( self.allow_run.check(
"access to run a subprocess", "access to run a subprocess",
"run again with the --allow-run flag", "run again with the --allow-run flag",
) )
} }
fn get_state_read(&self, filename: &Option<&str>) -> PermissionAccessorState { fn get_state_read(&self, filename: &Option<&str>) -> PermissionState {
if check_path_white_list(filename, &self.read_whitelist) { if check_path_white_list(filename, &self.read_whitelist) {
return PermissionAccessorState::Allow; return PermissionState::Allow;
} }
self.allow_read.get_state() self.allow_read
} }
pub fn check_read(&self, filename: &str) -> Result<(), ErrBox> { pub fn check_read(&self, filename: &str) -> Result<(), ErrBox> {
@ -182,14 +147,11 @@ impl DenoPermissions {
) )
} }
fn get_state_write( fn get_state_write(&self, filename: &Option<&str>) -> PermissionState {
&self,
filename: &Option<&str>,
) -> PermissionAccessorState {
if check_path_white_list(filename, &self.write_whitelist) { if check_path_white_list(filename, &self.write_whitelist) {
return PermissionAccessorState::Allow; return PermissionState::Allow;
} }
self.allow_write.get_state() self.allow_write
} }
pub fn check_write(&self, filename: &str) -> Result<(), ErrBox> { pub fn check_write(&self, filename: &str) -> Result<(), ErrBox> {
@ -199,23 +161,19 @@ impl DenoPermissions {
) )
} }
fn get_state_net( fn get_state_net(&self, host: &str, port: Option<u16>) -> PermissionState {
&self,
host: &str,
port: Option<u16>,
) -> PermissionAccessorState {
if check_host_and_port_whitelist(host, port, &self.net_whitelist) { if check_host_and_port_whitelist(host, port, &self.net_whitelist) {
return PermissionAccessorState::Allow; return PermissionState::Allow;
} }
self.allow_net.get_state() self.allow_net
} }
fn get_state_net_url( fn get_state_net_url(
&self, &self,
url: &Option<&str>, url: &Option<&str>,
) -> Result<PermissionAccessorState, ErrBox> { ) -> Result<PermissionState, ErrBox> {
if url.is_none() { if url.is_none() {
return Ok(self.allow_net.get_state()); return Ok(self.allow_net);
} }
let url: &str = url.unwrap(); let url: &str = url.unwrap();
// If url is invalid, then throw a TypeError. // If url is invalid, then throw a TypeError.
@ -243,21 +201,21 @@ impl DenoPermissions {
} }
pub fn check_env(&self) -> Result<(), ErrBox> { pub fn check_env(&self) -> Result<(), ErrBox> {
self.allow_env.get_state().check( self.allow_env.check(
"access to environment variables", "access to environment variables",
"run again with the --allow-env flag", "run again with the --allow-env flag",
) )
} }
pub fn request_run(&self) -> PermissionAccessorState { pub fn request_run(&mut self) -> PermissionState {
self self
.allow_run .allow_run
.request("Deno requests to access to run a subprocess.") .request("Deno requests to access to run a subprocess.")
} }
pub fn request_read(&self, path: &Option<&str>) -> PermissionAccessorState { pub fn request_read(&mut self, path: &Option<&str>) -> PermissionState {
if check_path_white_list(path, &self.read_whitelist) { if check_path_white_list(path, &self.read_whitelist) {
return PermissionAccessorState::Allow; return PermissionState::Allow;
}; };
self.allow_write.request(&match path { self.allow_write.request(&match path {
None => "Deno requests read access.".to_string(), None => "Deno requests read access.".to_string(),
@ -265,9 +223,9 @@ impl DenoPermissions {
}) })
} }
pub fn request_write(&self, path: &Option<&str>) -> PermissionAccessorState { pub fn request_write(&mut self, path: &Option<&str>) -> PermissionState {
if check_path_white_list(path, &self.write_whitelist) { if check_path_white_list(path, &self.write_whitelist) {
return PermissionAccessorState::Allow; return PermissionState::Allow;
}; };
self.allow_write.request(&match path { self.allow_write.request(&match path {
None => "Deno requests write access.".to_string(), None => "Deno requests write access.".to_string(),
@ -276,10 +234,10 @@ impl DenoPermissions {
} }
pub fn request_net( pub fn request_net(
&self, &mut self,
url: &Option<&str>, url: &Option<&str>,
) -> Result<PermissionAccessorState, ErrBox> { ) -> Result<PermissionState, ErrBox> {
if self.get_state_net_url(url)? == PermissionAccessorState::Ask { if self.get_state_net_url(url)? == PermissionState::Ask {
return Ok(self.allow_run.request(&match url { return Ok(self.allow_run.request(&match url {
None => "Deno requests network access.".to_string(), None => "Deno requests network access.".to_string(),
Some(url) => format!("Deno requests network access to \"{}\".", url), Some(url) => format!("Deno requests network access to \"{}\".", url),
@ -288,13 +246,13 @@ impl DenoPermissions {
self.get_state_net_url(url) self.get_state_net_url(url)
} }
pub fn request_env(&self) -> PermissionAccessorState { pub fn request_env(&mut self) -> PermissionState {
self self
.allow_env .allow_env
.request("Deno requests to access to environment variables.") .request("Deno requests to access to environment variables.")
} }
pub fn request_hrtime(&self) -> PermissionAccessorState { pub fn request_hrtime(&mut self) -> PermissionState {
self self
.allow_hrtime .allow_hrtime
.request("Deno requests to access to high precision time.") .request("Deno requests to access to high precision time.")
@ -305,14 +263,14 @@ impl DenoPermissions {
name: &str, name: &str,
url: &Option<&str>, url: &Option<&str>,
path: &Option<&str>, path: &Option<&str>,
) -> Result<PermissionAccessorState, ErrBox> { ) -> Result<PermissionState, ErrBox> {
match name { match name {
"run" => Ok(self.allow_run.get_state()), "run" => Ok(self.allow_run),
"read" => Ok(self.get_state_read(path)), "read" => Ok(self.get_state_read(path)),
"write" => Ok(self.get_state_write(path)), "write" => Ok(self.get_state_write(path)),
"net" => self.get_state_net_url(url), "net" => self.get_state_net_url(url),
"env" => Ok(self.allow_env.get_state()), "env" => Ok(self.allow_env),
"hrtime" => Ok(self.allow_hrtime.get_state()), "hrtime" => Ok(self.allow_hrtime),
n => Err(type_error(format!("No such permission name: {}", n))), n => Err(type_error(format!("No such permission name: {}", n))),
} }
} }
@ -380,7 +338,7 @@ fn log_perm_access(message: &str) {
fn check_path_white_list( fn check_path_white_list(
filename: &Option<&str>, filename: &Option<&str>,
white_list: &Arc<HashSet<String>>, white_list: &HashSet<String>,
) -> bool { ) -> bool {
if filename.is_none() { if filename.is_none() {
return false; return false;
@ -400,7 +358,7 @@ fn check_path_white_list(
fn check_host_and_port_whitelist( fn check_host_and_port_whitelist(
host: &str, host: &str,
port: Option<u16>, port: Option<u16>,
whitelist: &Arc<HashSet<String>>, whitelist: &HashSet<String>,
) -> bool { ) -> bool {
whitelist.contains(host) whitelist.contains(host)
|| (port.is_some() || (port.is_some()
@ -544,23 +502,23 @@ mod tests {
#[test] #[test]
fn test_permissions_request_run() { fn test_permissions_request_run() {
let perms0 = DenoPermissions::from_flags(&DenoFlags { let mut perms0 = DenoPermissions::from_flags(&DenoFlags {
..Default::default() ..Default::default()
}); });
set_prompt_result(true); set_prompt_result(true);
assert_eq!(perms0.request_run(), PermissionAccessorState::Allow); assert_eq!(perms0.request_run(), PermissionState::Allow);
let perms1 = DenoPermissions::from_flags(&DenoFlags { let mut perms1 = DenoPermissions::from_flags(&DenoFlags {
..Default::default() ..Default::default()
}); });
set_prompt_result(false); set_prompt_result(false);
assert_eq!(perms1.request_run(), PermissionAccessorState::Deny); assert_eq!(perms1.request_run(), PermissionState::Deny);
} }
#[test] #[test]
fn test_permissions_request_read() { fn test_permissions_request_read() {
let whitelist = svec!["/foo/bar"]; let whitelist = svec!["/foo/bar"];
let perms0 = DenoPermissions::from_flags(&DenoFlags { let mut perms0 = DenoPermissions::from_flags(&DenoFlags {
read_whitelist: whitelist.clone(), read_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
@ -569,34 +527,34 @@ mod tests {
// regardless of prompt result // regardless of prompt result
assert_eq!( assert_eq!(
perms0.request_read(&Some("/foo/bar")), perms0.request_read(&Some("/foo/bar")),
PermissionAccessorState::Allow PermissionState::Allow
); );
let perms1 = DenoPermissions::from_flags(&DenoFlags { let mut perms1 = DenoPermissions::from_flags(&DenoFlags {
read_whitelist: whitelist.clone(), read_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
set_prompt_result(true); set_prompt_result(true);
assert_eq!( assert_eq!(
perms1.request_read(&Some("/foo/baz")), perms1.request_read(&Some("/foo/baz")),
PermissionAccessorState::Allow PermissionState::Allow
); );
let perms2 = DenoPermissions::from_flags(&DenoFlags { let mut perms2 = DenoPermissions::from_flags(&DenoFlags {
read_whitelist: whitelist.clone(), read_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
set_prompt_result(false); set_prompt_result(false);
assert_eq!( assert_eq!(
perms2.request_read(&Some("/foo/baz")), perms2.request_read(&Some("/foo/baz")),
PermissionAccessorState::Deny PermissionState::Deny
); );
} }
#[test] #[test]
fn test_permissions_request_write() { fn test_permissions_request_write() {
let whitelist = svec!["/foo/bar"]; let whitelist = svec!["/foo/bar"];
let perms0 = DenoPermissions::from_flags(&DenoFlags { let mut perms0 = DenoPermissions::from_flags(&DenoFlags {
write_whitelist: whitelist.clone(), write_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
@ -605,27 +563,27 @@ mod tests {
// regardless of prompt result // regardless of prompt result
assert_eq!( assert_eq!(
perms0.request_write(&Some("/foo/bar")), perms0.request_write(&Some("/foo/bar")),
PermissionAccessorState::Allow PermissionState::Allow
); );
let perms1 = DenoPermissions::from_flags(&DenoFlags { let mut perms1 = DenoPermissions::from_flags(&DenoFlags {
write_whitelist: whitelist.clone(), write_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
set_prompt_result(true); set_prompt_result(true);
assert_eq!( assert_eq!(
perms1.request_write(&Some("/foo/baz")), perms1.request_write(&Some("/foo/baz")),
PermissionAccessorState::Allow PermissionState::Allow
); );
let perms2 = DenoPermissions::from_flags(&DenoFlags { let mut perms2 = DenoPermissions::from_flags(&DenoFlags {
write_whitelist: whitelist.clone(), write_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
set_prompt_result(false); set_prompt_result(false);
assert_eq!( assert_eq!(
perms2.request_write(&Some("/foo/baz")), perms2.request_write(&Some("/foo/baz")),
PermissionAccessorState::Deny PermissionState::Deny
); );
} }
@ -633,7 +591,7 @@ mod tests {
fn test_permission_request_net() { fn test_permission_request_net() {
let whitelist = svec!["localhost:8080"]; let whitelist = svec!["localhost:8080"];
let perms0 = DenoPermissions::from_flags(&DenoFlags { let mut perms0 = DenoPermissions::from_flags(&DenoFlags {
net_whitelist: whitelist.clone(), net_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
@ -644,10 +602,10 @@ mod tests {
perms0 perms0
.request_net(&Some("http://localhost:8080/")) .request_net(&Some("http://localhost:8080/"))
.expect("Testing expect"), .expect("Testing expect"),
PermissionAccessorState::Allow PermissionState::Allow
); );
let perms1 = DenoPermissions::from_flags(&DenoFlags { let mut perms1 = DenoPermissions::from_flags(&DenoFlags {
net_whitelist: whitelist.clone(), net_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
@ -656,10 +614,10 @@ mod tests {
perms1 perms1
.request_net(&Some("http://deno.land/")) .request_net(&Some("http://deno.land/"))
.expect("Testing expect"), .expect("Testing expect"),
PermissionAccessorState::Allow PermissionState::Allow
); );
let perms2 = DenoPermissions::from_flags(&DenoFlags { let mut perms2 = DenoPermissions::from_flags(&DenoFlags {
net_whitelist: whitelist.clone(), net_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
@ -668,10 +626,10 @@ mod tests {
perms2 perms2
.request_net(&Some("http://deno.land/")) .request_net(&Some("http://deno.land/"))
.expect("Testing expect"), .expect("Testing expect"),
PermissionAccessorState::Deny PermissionState::Deny
); );
let perms3 = DenoPermissions::from_flags(&DenoFlags { let mut perms3 = DenoPermissions::from_flags(&DenoFlags {
net_whitelist: whitelist.clone(), net_whitelist: whitelist.clone(),
..Default::default() ..Default::default()
}); });
@ -681,31 +639,31 @@ mod tests {
#[test] #[test]
fn test_permissions_request_env() { fn test_permissions_request_env() {
let perms0 = DenoPermissions::from_flags(&DenoFlags { let mut perms0 = DenoPermissions::from_flags(&DenoFlags {
..Default::default() ..Default::default()
}); });
set_prompt_result(true); set_prompt_result(true);
assert_eq!(perms0.request_env(), PermissionAccessorState::Allow); assert_eq!(perms0.request_env(), PermissionState::Allow);
let perms1 = DenoPermissions::from_flags(&DenoFlags { let mut perms1 = DenoPermissions::from_flags(&DenoFlags {
..Default::default() ..Default::default()
}); });
set_prompt_result(false); set_prompt_result(false);
assert_eq!(perms1.request_env(), PermissionAccessorState::Deny); assert_eq!(perms1.request_env(), PermissionState::Deny);
} }
#[test] #[test]
fn test_permissions_request_hrtime() { fn test_permissions_request_hrtime() {
let perms0 = DenoPermissions::from_flags(&DenoFlags { let mut perms0 = DenoPermissions::from_flags(&DenoFlags {
..Default::default() ..Default::default()
}); });
set_prompt_result(true); set_prompt_result(true);
assert_eq!(perms0.request_hrtime(), PermissionAccessorState::Allow); assert_eq!(perms0.request_hrtime(), PermissionState::Allow);
let perms1 = DenoPermissions::from_flags(&DenoFlags { let mut perms1 = DenoPermissions::from_flags(&DenoFlags {
..Default::default() ..Default::default()
}); });
set_prompt_result(false); set_prompt_result(false);
assert_eq!(perms1.request_hrtime(), PermissionAccessorState::Deny); assert_eq!(perms1.request_hrtime(), PermissionState::Deny);
} }
} }

View file

@ -44,7 +44,7 @@ pub struct ThreadSafeState(Arc<State>);
pub struct State { pub struct State {
pub global_state: ThreadSafeGlobalState, pub global_state: ThreadSafeGlobalState,
pub modules: Arc<Mutex<deno::Modules>>, pub modules: Arc<Mutex<deno::Modules>>,
pub permissions: DenoPermissions, pub permissions: Arc<Mutex<DenoPermissions>>,
pub main_module: Option<ModuleSpecifier>, pub main_module: Option<ModuleSpecifier>,
pub worker_channels: Mutex<WorkerChannels>, pub worker_channels: Mutex<WorkerChannels>,
/// When flags contains a `.import_map_path` option, the content of the /// When flags contains a `.import_map_path` option, the content of the
@ -213,6 +213,8 @@ impl ThreadSafeState {
pub fn new( pub fn new(
global_state: ThreadSafeGlobalState, global_state: ThreadSafeGlobalState,
// If Some(perm), use perm. Else copy from global_state.
shared_permissions: Option<Arc<Mutex<DenoPermissions>>>,
main_module: Option<ModuleSpecifier>, main_module: Option<ModuleSpecifier>,
include_deno_namespace: bool, include_deno_namespace: bool,
internal_channels: WorkerChannels, internal_channels: WorkerChannels,
@ -229,7 +231,11 @@ impl ThreadSafeState {
}; };
let modules = Arc::new(Mutex::new(deno::Modules::new())); let modules = Arc::new(Mutex::new(deno::Modules::new()));
let permissions = global_state.permissions.clone(); let permissions = if let Some(perm) = shared_permissions {
perm
} else {
Arc::new(Mutex::new(global_state.permissions.clone()))
};
let state = State { let state = State {
global_state, global_state,
@ -260,32 +266,32 @@ impl ThreadSafeState {
#[inline] #[inline]
pub fn check_read(&self, filename: &str) -> Result<(), ErrBox> { pub fn check_read(&self, filename: &str) -> Result<(), ErrBox> {
self.permissions.check_read(filename) self.permissions.lock().unwrap().check_read(filename)
} }
#[inline] #[inline]
pub fn check_write(&self, filename: &str) -> Result<(), ErrBox> { pub fn check_write(&self, filename: &str) -> Result<(), ErrBox> {
self.permissions.check_write(filename) self.permissions.lock().unwrap().check_write(filename)
} }
#[inline] #[inline]
pub fn check_env(&self) -> Result<(), ErrBox> { pub fn check_env(&self) -> Result<(), ErrBox> {
self.permissions.check_env() self.permissions.lock().unwrap().check_env()
} }
#[inline] #[inline]
pub fn check_net(&self, hostname: &str, port: u16) -> Result<(), ErrBox> { pub fn check_net(&self, hostname: &str, port: u16) -> Result<(), ErrBox> {
self.permissions.check_net(hostname, port) self.permissions.lock().unwrap().check_net(hostname, port)
} }
#[inline] #[inline]
pub fn check_net_url(&self, url: &url::Url) -> Result<(), ErrBox> { pub fn check_net_url(&self, url: &url::Url) -> Result<(), ErrBox> {
self.permissions.check_net_url(url) self.permissions.lock().unwrap().check_net_url(url)
} }
#[inline] #[inline]
pub fn check_run(&self) -> Result<(), ErrBox> { pub fn check_run(&self) -> Result<(), ErrBox> {
self.permissions.check_run() self.permissions.lock().unwrap().check_run()
} }
pub fn check_dyn_import( pub fn check_dyn_import(
@ -327,6 +333,7 @@ impl ThreadSafeState {
ThreadSafeState::new( ThreadSafeState::new(
ThreadSafeGlobalState::mock(argv), ThreadSafeGlobalState::mock(argv),
None,
module_specifier, module_specifier,
true, true,
internal_channels, internal_channels,

View file

@ -248,6 +248,7 @@ mod tests {
let (int, ext) = ThreadSafeState::create_channels(); let (int, ext) = ThreadSafeState::create_channels();
let state = ThreadSafeState::new( let state = ThreadSafeState::new(
global_state, global_state,
None,
Some(module_specifier.clone()), Some(module_specifier.clone()),
true, true,
int, int,
@ -288,6 +289,7 @@ mod tests {
let (int, ext) = ThreadSafeState::create_channels(); let (int, ext) = ThreadSafeState::create_channels();
let state = ThreadSafeState::new( let state = ThreadSafeState::new(
global_state, global_state,
None,
Some(module_specifier.clone()), Some(module_specifier.clone()),
true, true,
int, int,
@ -331,6 +333,7 @@ mod tests {
let (int, ext) = ThreadSafeState::create_channels(); let (int, ext) = ThreadSafeState::create_channels();
let state = ThreadSafeState::new( let state = ThreadSafeState::new(
global_state.clone(), global_state.clone(),
None,
Some(module_specifier.clone()), Some(module_specifier.clone()),
true, true,
int, int,