forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
permissions.rs
715 lines (652 loc) · 19.5 KB
/
permissions.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
use atty;
use crate::flags::DenoFlags;
use ansi_term::Style;
use crate::errors::permission_denied;
use crate::errors::DenoResult;
use std::collections::HashSet;
use std::fmt;
use std::io;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
/// Tri-state value for storing permission state
pub enum PermissionAccessorState {
Allow = 0,
Ask = 1,
Deny = 2,
}
impl From<usize> for PermissionAccessorState {
fn from(val: usize) -> Self {
match val {
0 => PermissionAccessorState::Allow,
1 => PermissionAccessorState::Ask,
2 => PermissionAccessorState::Deny,
_ => unreachable!(),
}
}
}
impl From<bool> for PermissionAccessorState {
fn from(val: bool) -> Self {
if val {
PermissionAccessorState::Allow
} else {
PermissionAccessorState::Ask
}
}
}
impl fmt::Display for PermissionAccessorState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PermissionAccessorState::Allow => f.pad("Allow"),
PermissionAccessorState::Ask => f.pad("Ask"),
PermissionAccessorState::Deny => f.pad("Deny"),
}
}
}
#[derive(Debug)]
pub struct PermissionAccessor {
state: Arc<AtomicUsize>,
}
impl PermissionAccessor {
pub fn new(state: PermissionAccessorState) -> Self {
Self {
state: Arc::new(AtomicUsize::new(state as usize)),
}
}
pub fn is_allow(&self) -> bool {
match self.get_state() {
PermissionAccessorState::Allow => true,
_ => false,
}
}
/// 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.ask();
}
}
pub fn allow(&self) {
self.set_state(PermissionAccessorState::Allow)
}
pub fn ask(&self) {
self.set_state(PermissionAccessorState::Ask)
}
pub fn deny(&self) {
self.set_state(PermissionAccessorState::Deny)
}
/// Update this accessors state based on a PromptResult value
/// This will only update the state if the PromptResult value
/// is one of the "Always" values
pub fn update_with_prompt_result(&self, prompt_result: &PromptResult) {
match prompt_result {
PromptResult::AllowAlways => self.allow(),
PromptResult::DenyAlways => self.deny(),
_ => {}
}
}
#[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 {
Self {
state: Arc::new(AtomicUsize::new(PermissionAccessorState::Ask as usize)),
}
}
}
#[derive(Debug, Default)]
pub struct DenoPermissions {
// Keep in sync with src/permissions.ts
pub allow_read: PermissionAccessor,
pub read_whitelist: Arc<HashSet<String>>,
pub allow_write: PermissionAccessor,
pub write_whitelist: Arc<HashSet<String>>,
pub allow_net: PermissionAccessor,
pub net_whitelist: Arc<HashSet<String>>,
pub allow_env: PermissionAccessor,
pub allow_run: PermissionAccessor,
pub allow_hrtime: PermissionAccessor,
pub no_prompts: AtomicBool,
}
impl DenoPermissions {
pub fn from_flags(flags: &DenoFlags) -> Self {
Self {
allow_read: PermissionAccessor::from(flags.allow_read),
read_whitelist: Arc::new(flags.read_whitelist.iter().cloned().collect()),
allow_write: PermissionAccessor::from(flags.allow_write),
write_whitelist: Arc::new(
flags.write_whitelist.iter().cloned().collect(),
),
allow_net: PermissionAccessor::from(flags.allow_net),
net_whitelist: Arc::new(flags.net_whitelist.iter().cloned().collect()),
allow_env: PermissionAccessor::from(flags.allow_env),
allow_run: PermissionAccessor::from(flags.allow_run),
allow_hrtime: PermissionAccessor::from(flags.allow_hrtime),
no_prompts: AtomicBool::new(flags.no_prompts),
}
}
pub fn check_run(&self) -> DenoResult<()> {
match self.allow_run.get_state() {
PermissionAccessorState::Allow => Ok(()),
PermissionAccessorState::Ask => {
match self.try_permissions_prompt("access to run a subprocess") {
Err(e) => Err(e),
Ok(v) => {
self.allow_run.update_with_prompt_result(&v);
v.check()?;
Ok(())
}
}
}
PermissionAccessorState::Deny => Err(permission_denied()),
}
}
pub fn check_read(&self, filename: &str) -> DenoResult<()> {
match self.allow_read.get_state() {
PermissionAccessorState::Allow => Ok(()),
state => {
if check_path_white_list(filename, &self.read_whitelist) {
Ok(())
} else {
match state {
PermissionAccessorState::Ask => match self.try_permissions_prompt(
&format!("read access to \"{}\"", filename),
) {
Err(e) => Err(e),
Ok(v) => {
self.allow_read.update_with_prompt_result(&v);
v.check()?;
Ok(())
}
},
PermissionAccessorState::Deny => Err(permission_denied()),
_ => unreachable!(),
}
}
}
}
}
pub fn check_write(&self, filename: &str) -> DenoResult<()> {
match self.allow_write.get_state() {
PermissionAccessorState::Allow => Ok(()),
state => {
if check_path_white_list(filename, &self.write_whitelist) {
Ok(())
} else {
match state {
PermissionAccessorState::Ask => match self.try_permissions_prompt(
&format!("write access to \"{}\"", filename),
) {
Err(e) => Err(e),
Ok(v) => {
self.allow_write.update_with_prompt_result(&v);
v.check()?;
Ok(())
}
},
PermissionAccessorState::Deny => Err(permission_denied()),
_ => unreachable!(),
}
}
}
}
}
pub fn check_net(&self, host_and_port: &str) -> DenoResult<()> {
match self.allow_net.get_state() {
PermissionAccessorState::Allow => Ok(()),
state => {
let parts = host_and_port.split(':').collect::<Vec<&str>>();
if match parts.len() {
2 => {
if self.net_whitelist.contains(parts[0]) {
true
} else {
self
.net_whitelist
.contains(&format!("{}:{}", parts[0], parts[1]))
}
}
1 => self.net_whitelist.contains(parts[0]),
_ => panic!("Failed to parse origin string: {}", host_and_port),
} {
Ok(())
} else {
self.check_net_inner(state, host_and_port)
}
}
}
}
pub fn check_net_url(&self, url: url::Url) -> DenoResult<()> {
match self.allow_net.get_state() {
PermissionAccessorState::Allow => Ok(()),
state => {
let host = url.host().unwrap();
let whitelist_result = {
if self.net_whitelist.contains(&format!("{}", host)) {
true
} else {
match url.port() {
Some(port) => {
self.net_whitelist.contains(&format!("{}:{}", host, port))
}
None => false,
}
}
};
if whitelist_result {
Ok(())
} else {
self.check_net_inner(state, &url.to_string())
}
}
}
}
fn check_net_inner(
&self,
state: PermissionAccessorState,
prompt_str: &str,
) -> DenoResult<()> {
match state {
PermissionAccessorState::Ask => match self.try_permissions_prompt(
&format!("network access to \"{}\"", prompt_str),
) {
Err(e) => Err(e),
Ok(v) => {
self.allow_net.update_with_prompt_result(&v);
v.check()?;
Ok(())
}
},
PermissionAccessorState::Deny => Err(permission_denied()),
_ => unreachable!(),
}
}
pub fn check_env(&self) -> DenoResult<()> {
match self.allow_env.get_state() {
PermissionAccessorState::Allow => Ok(()),
PermissionAccessorState::Ask => {
match self.try_permissions_prompt("access to environment variables") {
Err(e) => Err(e),
Ok(v) => {
self.allow_env.update_with_prompt_result(&v);
v.check()?;
Ok(())
}
}
}
PermissionAccessorState::Deny => Err(permission_denied()),
}
}
/// Try to present the user with a permission prompt
/// will error with permission_denied if no_prompts is enabled
fn try_permissions_prompt(&self, message: &str) -> DenoResult<PromptResult> {
if self.no_prompts.load(Ordering::SeqCst) {
return Err(permission_denied());
}
if !atty::is(atty::Stream::Stdin) || !atty::is(atty::Stream::Stderr) {
return Err(permission_denied());
};
permission_prompt(message)
}
pub fn allows_run(&self) -> bool {
self.allow_run.is_allow()
}
pub fn allows_read(&self) -> bool {
self.allow_read.is_allow()
}
pub fn allows_write(&self) -> bool {
self.allow_write.is_allow()
}
pub fn allows_net(&self) -> bool {
self.allow_net.is_allow()
}
pub fn allows_env(&self) -> bool {
self.allow_env.is_allow()
}
pub fn allows_hrtime(&self) -> bool {
self.allow_hrtime.is_allow()
}
pub fn revoke_run(&self) -> DenoResult<()> {
self.allow_run.revoke();
Ok(())
}
pub fn revoke_read(&self) -> DenoResult<()> {
self.allow_read.revoke();
Ok(())
}
pub fn revoke_write(&self) -> DenoResult<()> {
self.allow_write.revoke();
Ok(())
}
pub fn revoke_net(&self) -> DenoResult<()> {
self.allow_net.revoke();
Ok(())
}
pub fn revoke_env(&self) -> DenoResult<()> {
self.allow_env.revoke();
Ok(())
}
pub fn revoke_hrtime(&self) -> DenoResult<()> {
self.allow_hrtime.revoke();
Ok(())
}
}
/// Quad-state value for representing user input on permission prompt
#[derive(Debug, Clone)]
pub enum PromptResult {
AllowAlways = 0,
AllowOnce = 1,
DenyOnce = 2,
DenyAlways = 3,
}
impl PromptResult {
/// If value is any form of deny this will error with permission_denied
pub fn check(&self) -> DenoResult<()> {
match self {
PromptResult::DenyOnce => Err(permission_denied()),
PromptResult::DenyAlways => Err(permission_denied()),
_ => Ok(()),
}
}
}
impl fmt::Display for PromptResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PromptResult::AllowAlways => f.pad("AllowAlways"),
PromptResult::AllowOnce => f.pad("AllowOnce"),
PromptResult::DenyOnce => f.pad("DenyOnce"),
PromptResult::DenyAlways => f.pad("DenyAlways"),
}
}
}
fn permission_prompt(message: &str) -> DenoResult<PromptResult> {
let msg = format!("⚠️ Deno requests {}. Grant? [a/y/n/d (a = allow always, y = allow once, n = deny once, d = deny always)] ", message);
// print to stderr so that if deno is > to a file this is still displayed.
eprint!("{}", Style::new().bold().paint(msg));
loop {
let mut input = String::new();
let stdin = io::stdin();
let _nread = stdin.read_line(&mut input)?;
let ch = input.chars().next().unwrap();
match ch.to_ascii_lowercase() {
'a' => return Ok(PromptResult::AllowAlways),
'y' => return Ok(PromptResult::AllowOnce),
'n' => return Ok(PromptResult::DenyOnce),
'd' => return Ok(PromptResult::DenyAlways),
_ => {
// If we don't get a recognized option try again.
let msg_again = format!("Unrecognized option '{}' [a/y/n/d (a = allow always, y = allow once, n = deny once, d = deny always)] ", ch);
eprint!("{}", Style::new().bold().paint(msg_again));
}
};
}
}
fn check_path_white_list(
filename: &str,
white_list: &Arc<HashSet<String>>,
) -> bool {
let mut path_buf = PathBuf::from(filename);
loop {
if white_list.contains(path_buf.to_str().unwrap()) {
return true;
}
if !path_buf.pop() {
break;
}
}
false
}
#[cfg(test)]
mod tests {
#![allow(clippy::cyclomatic_complexity)]
use super::*;
// Creates vector of strings, Vec<String>
macro_rules! svec {
($($x:expr),*) => (vec![$($x.to_string()),*]);
}
#[test]
fn check_paths() {
let whitelist = svec!["/a/specific/dir/name", "/a/specific", "/b/c"];
let perms = DenoPermissions::from_flags(&DenoFlags {
read_whitelist: whitelist.clone(),
write_whitelist: whitelist.clone(),
no_prompts: true,
..Default::default()
});
// Inside of /a/specific and /a/specific/dir/name
assert!(perms.check_read("/a/specific/dir/name").is_ok());
assert!(perms.check_write("/a/specific/dir/name").is_ok());
// Inside of /a/specific but outside of /a/specific/dir/name
assert!(perms.check_read("/a/specific/dir").is_ok());
assert!(perms.check_write("/a/specific/dir").is_ok());
// Inside of /a/specific and /a/specific/dir/name
assert!(perms.check_read("/a/specific/dir/name/inner").is_ok());
assert!(perms.check_write("/a/specific/dir/name/inner").is_ok());
// Inside of /a/specific but outside of /a/specific/dir/name
assert!(perms.check_read("/a/specific/other/dir").is_ok());
assert!(perms.check_write("/a/specific/other/dir").is_ok());
// Exact match with /b/c
assert!(perms.check_read("/b/c").is_ok());
assert!(perms.check_write("/b/c").is_ok());
// Sub path within /b/c
assert!(perms.check_read("/b/c/sub/path").is_ok());
assert!(perms.check_write("/b/c/sub/path").is_ok());
// Inside of /b but outside of /b/c
assert!(perms.check_read("/b/e").is_err());
assert!(perms.check_write("/b/e").is_err());
// Inside of /a but outside of /a/specific
assert!(perms.check_read("/a/b").is_err());
assert!(perms.check_write("/a/b").is_err());
}
#[test]
fn check_net() {
let perms = DenoPermissions::from_flags(&DenoFlags {
net_whitelist: svec![
"localhost",
"deno.land",
"github.com:3000",
"127.0.0.1",
"172.16.0.2:8000"
],
no_prompts: true,
..Default::default()
});
// Any protocol + port for localhost should be ok, since we don't specify
assert!(
perms
.check_net_url(url::Url::parse("http:https://localhost").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("http:https://localhost:8080").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("https://localhost").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("https://localhost:4443").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://localhost:5000").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("udp:https://localhost:6000").unwrap())
.is_ok()
);
assert!(perms.check_net("localhost:1234").is_ok());
// Correct domain + any port and protocol should be ok incorrect shouldn't
assert!(perms.check_net("deno.land").is_ok());
assert!(
perms
.check_net_url(
url::Url::parse("https://deno.land/std/example/welcome.ts").unwrap()
).is_ok()
);
assert!(perms.check_net("deno.land:3000").is_ok());
assert!(
perms
.check_net_url(
url::Url::parse("https://deno.land:3000/std/example/welcome.ts")
.unwrap()
).is_ok()
);
assert!(perms.check_net("deno.lands").is_err());
assert!(
perms
.check_net_url(
url::Url::parse("https://deno.lands/std/example/welcome.ts").unwrap()
).is_err()
);
assert!(perms.check_net("deno.lands:3000").is_err());
assert!(
perms
.check_net_url(
url::Url::parse("https://deno.lands:3000/std/example/welcome.ts")
.unwrap()
).is_err()
);
// Correct domain + port should be ok all other combinations should err
assert!(perms.check_net("github.com:3000").is_ok());
assert!(
perms
.check_net_url(
url::Url::parse("https://github.com:3000/denoland/deno").unwrap()
).is_ok()
);
assert!(perms.check_net("github.com").is_err());
assert!(
perms
.check_net_url(
url::Url::parse("https://github.com/denoland/deno").unwrap()
).is_err()
);
assert!(perms.check_net("github.com:2000").is_err());
assert!(
perms
.check_net_url(
url::Url::parse("https://github.com:2000/denoland/deno").unwrap()
).is_err()
);
assert!(perms.check_net("github.net:3000").is_err());
assert!(
perms
.check_net_url(
url::Url::parse("https://github.net:3000/denoland/deno").unwrap()
).is_err()
);
// Correct ipv4 address + any port should be ok others should err
assert!(perms.check_net("127.0.0.1").is_ok());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://127.0.0.1").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("https://127.0.0.1").unwrap())
.is_ok()
);
assert!(perms.check_net("127.0.0.1:3000").is_ok());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://127.0.0.1:3000").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("https://127.0.0.1:3000").unwrap())
.is_ok()
);
assert!(perms.check_net("127.0.0.2").is_err());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://127.0.0.2").unwrap())
.is_err()
);
assert!(
perms
.check_net_url(url::Url::parse("https://127.0.0.2").unwrap())
.is_err()
);
assert!(perms.check_net("127.0.0.2:3000").is_err());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://127.0.0.2:3000").unwrap())
.is_err()
);
assert!(
perms
.check_net_url(url::Url::parse("https://127.0.0.2:3000").unwrap())
.is_err()
);
// Correct address + port should be ok all other combinations should err
assert!(perms.check_net("172.16.0.2:8000").is_ok());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://172.16.0.2:8000").unwrap())
.is_ok()
);
assert!(
perms
.check_net_url(url::Url::parse("https://172.16.0.2:8000").unwrap())
.is_ok()
);
assert!(perms.check_net("172.16.0.2").is_err());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://172.16.0.2").unwrap())
.is_err()
);
assert!(
perms
.check_net_url(url::Url::parse("https://172.16.0.2").unwrap())
.is_err()
);
assert!(perms.check_net("172.16.0.2:6000").is_err());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://172.16.0.2:6000").unwrap())
.is_err()
);
assert!(
perms
.check_net_url(url::Url::parse("https://172.16.0.2:6000").unwrap())
.is_err()
);
assert!(perms.check_net("172.16.0.1:8000").is_err());
assert!(
perms
.check_net_url(url::Url::parse("tcp:https://172.16.0.1:8000").unwrap())
.is_err()
);
assert!(
perms
.check_net_url(url::Url::parse("https://172.16.0.1:8000").unwrap())
.is_err()
);
// Just some random hosts that should err
assert!(perms.check_net("somedomain").is_err());
assert!(perms.check_net("192.168.0.1").is_err());
}
}