feat(linter): add eslint(no-eval) (#417)

This commit is contained in:
Carter Snook 2023-06-08 21:36:12 -05:00 committed by GitHub
parent 664ff0cc17
commit eca8541032
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 108 additions and 0 deletions

View file

@ -15,6 +15,7 @@ oxc_macros::declare_all_lint_rules! {
no_dupe_class_members,
no_empty,
no_empty_pattern,
no_eval,
no_new_symbol,
no_self_compare,
no_shadow_restricted_names,

View file

@ -0,0 +1,67 @@
use oxc_ast::AstKind;
use oxc_diagnostics::{
miette::{self, Diagnostic},
thiserror::Error,
};
use oxc_macros::declare_oxc_lint;
use oxc_semantic::AstNode;
use oxc_span::Span;
use crate::{context::LintContext, rule::Rule};
#[derive(Debug, Error, Diagnostic)]
#[error("eslint(no-eval): eval can be harmful.")]
#[diagnostic(severity(warning))]
struct NoEvalDiagnostic(#[label("eval can be harmful")] pub Span);
#[derive(Debug, Default, Clone)]
pub struct NoEval;
declare_oxc_lint!(
/// ### What it does
/// Disallows referencing the 'eval' function.
///
/// ### Why is this bad?
/// Calling 'eval' is not supported in some secure contexts and can lead to
/// vulnerabilities.
///
/// ### Example
/// ```javascript
/// const someString = "console.log('pwned')"
/// eval(someString);
/// ```
NoEval,
nursery
);
impl Rule for NoEval {
fn run<'a>(&self, node: &AstNode<'a>, ctx: &LintContext<'a>) {
if let AstKind::IdentifierReference(ident) = node.get().kind()
&& ident.name == "eval"
{
ctx.diagnostic(NoEvalDiagnostic(ident.span));
}
}
}
#[test]
fn test() {
use crate::tester::Tester;
let pass = vec![
("this.eval();", None),
("globalThis.eval();", None),
("asdf.eval();", None),
("const asdf = { eval: true };", None),
];
let fail = vec![
("eval();", None),
("eval('...');", None),
("eval('...');", None),
("let a = eval;", None),
("const foo = { asdf: eval };", None),
];
Tester::new(NoEval::NAME, pass, fail).test_and_snapshot();
}

View file

@ -0,0 +1,40 @@
---
source: crates/oxc_linter/src/tester.rs
expression: no_eval
---
⚠ eslint(no-eval): eval can be harmful.
╭─[no_eval.tsx:1:1]
1 │ eval();
· ──┬─
· ╰── eval can be harmful
╰────
⚠ eslint(no-eval): eval can be harmful.
╭─[no_eval.tsx:1:1]
1 │ eval('...');
· ──┬─
· ╰── eval can be harmful
╰────
⚠ eslint(no-eval): eval can be harmful.
╭─[no_eval.tsx:1:1]
1 │ eval('...');
· ──┬─
· ╰── eval can be harmful
╰────
⚠ eslint(no-eval): eval can be harmful.
╭─[no_eval.tsx:1:1]
1 │ let a = eval;
· ──┬─
· ╰── eval can be harmful
╰────
⚠ eslint(no-eval): eval can be harmful.
╭─[no_eval.tsx:1:1]
1 │ const foo = { asdf: eval };
· ──┬─
· ╰── eval can be harmful
╰────