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
// Copyright 2020 nest.land core team.

use super::AnalyzeOptions;
use super::Context;
use super::Rule;
use std::sync::Arc;
use swc_common::Span;
use swc_ecma_ast::CallExpr;
use swc_ecma_ast::Expr;
use swc_ecma_ast::ExprOrSuper;
use swc_ecma_visit::Node;
use swc_ecma_visit::Visit;

/// Rule `ban-deno-run` (CheckDenoRun)
pub struct CheckDenoRun;

/// Create rule for `ban-deno-run`
impl Rule for CheckDenoRun {
  /// Creates self reference
  fn new() -> Box<Self> {
    Box::new(CheckDenoRun)
  }
  /// Declare rule code
  fn code(&self) -> &'static str {
    "ban-deno-run"
  }
  /// Main entrypoint for module analysis
  fn check_module(
    &self,
    context: Arc<Context>,
    module: &swc_ecma_ast::Module,
    opt: Option<AnalyzeOptions>,
  ) {
    let mut visitor = CheckDenoRunVisitor::new(context, opt);
    visitor.visit_module(module, module);
  }
}

/// Create new module visitor
struct CheckDenoRunVisitor {
  context: Arc<Context>,
  options: Option<AnalyzeOptions>,
}

impl CheckDenoRunVisitor {
  pub fn new(context: Arc<Context>, options: Option<AnalyzeOptions>) -> Self {
    Self { context, options }
  }
  /// Check for `Deno.run` in a CallExpr
  fn check_callee(&self, callee_name: &Expr, _span: Span) -> Option<bool> {
    if let Expr::Member(expr) = &callee_name {
      // TODO(divy-work): An ugly workaround to prevent panics.
      let callee_name = self
        .get_obj(expr.obj.clone())
        .unwrap_or_else(|| "".to_string());
      if let "Deno" = callee_name.as_str() {
        let prop = self
          .get_prop(expr.prop.clone())
          .unwrap_or_else(|| "".to_string());
        if let "run" = prop.as_str() {
          return Some(true);
        }
      }
    }
    None
  }
  /// Get member prop from a Expr
  fn get_prop(&self, expr: Box<Expr>) -> Option<String> {
    if let Expr::Ident(ident) = *expr {
      return Some(ident.sym.to_string());
    }
    None
  }

  /// Get member obj from a ExprOrSuper
  fn get_obj(&self, expr: ExprOrSuper) -> Option<String> {
    if let ExprOrSuper::Expr(ex) = expr {
      if let Expr::Ident(ident) = *ex {
        return Some(ident.sym.to_string());
      }
    }
    None
  }
}

impl Visit for CheckDenoRunVisitor {
  /// Visit every CallExpr and check for callee
  fn visit_call_expr(&mut self, call_expr: &CallExpr, _parent: &dyn Node) {
    if let ExprOrSuper::Expr(expr) = &call_expr.callee {
      if self.check_callee(expr, call_expr.span).is_some() {
        for args in &call_expr.args {
          if let Expr::Object(obj) = &*args.expr {
            for i in &obj.props {
              if let swc_ecma_ast::PropOrSpread::Prop(s) = &i {
                if let swc_ecma_ast::Prop::KeyValue(prop) = &**s {
                  if let swc_ecma_ast::PropName::Ident(i) = &prop.key {
                    if i.sym.to_string() == "cmd" {
                      if let swc_ecma_ast::Expr::Lit(swc_ecma_ast::Lit::Str(
                        e,
                      )) = &*prop.value
                      {
                        if e.value == self.options.as_ref().unwrap().data {
                          self.context.add_diagnostic(
                            e.span,
                            "check-deno-run",
                            format!(
                              "Executing `{}` from `Deno.run` is not allowed",
                              &e.value.to_string()
                            )
                            .as_ref(),
                          );
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::tests::*;

  #[test]
  fn ban_deno_run_ok() {
    assert_ok::<CheckDenoRun>(
      r#"
      Deno.compile();
      Deno.smthElse();
      Deno.run({ cmd: "echo I AM SAFE" });
    "#,
      Some(crate::analyzer::AnalyzeOptions {
        data: "sh badfile.sh".to_string(),
      }),
    );
  }

  #[test]
  fn ban_deno_run_err() {
    assert_ok_err::<CheckDenoRun>(
      r#"
      Deno.run({ cmd: "sh badfilehaha.sh" });
    "#,
      Some(crate::analyzer::AnalyzeOptions {
        data: "sh badfilehaha.sh".to_string(),
      }),
    );
  }
}