9
9
// Rule Definition
10
10
//------------------------------------------------------------------------------
11
11
12
- /*
13
- * Stores variable names pointing to child_process to check (child_process).exec()
14
- */
15
- const names = [ ] ;
16
-
17
12
module . exports = {
18
13
meta : {
19
14
type : 'error' ,
@@ -25,22 +20,44 @@ module.exports = {
25
20
} ,
26
21
} ,
27
22
create : function ( context ) {
23
+ /*
24
+ * Stores variable identifiers pointing to child_process to check (child_process).exec()
25
+ */
26
+ const childProcessIdentifiers = new Set ( ) ;
27
+
28
+ /**
29
+ * Extract identifiers assigned the expression `require("child_process")`.
30
+ * @param {Pattern } node
31
+ */
32
+ function extractChildProcessIdentifiers ( node ) {
33
+ if ( node . type !== 'Identifier' ) {
34
+ return ;
35
+ }
36
+ const variable = context . getScope ( ) . set . get ( node . name ) ;
37
+ if ( ! variable ) {
38
+ return ;
39
+ }
40
+ for ( const reference of variable . references ) {
41
+ childProcessIdentifiers . add ( reference . identifier ) ;
42
+ }
43
+ }
44
+
28
45
return {
29
46
CallExpression : function ( node ) {
30
47
if ( node . callee . name === 'require' ) {
31
48
const args = node . arguments [ 0 ] ;
32
49
if ( args && args . type === 'Literal' && args . value === 'child_process' ) {
33
50
if ( node . parent . type === 'VariableDeclarator' ) {
34
- names . push ( node . parent . id . name ) ;
51
+ extractChildProcessIdentifiers ( node . parent . id ) ;
35
52
} else if ( node . parent . type === 'AssignmentExpression' && node . parent . operator === '=' ) {
36
- names . push ( node . parent . left . name ) ;
53
+ extractChildProcessIdentifiers ( node . parent . left ) ;
37
54
}
38
55
return context . report ( { node : node , message : 'Found require("child_process")' } ) ;
39
56
}
40
57
}
41
58
} ,
42
59
MemberExpression : function ( node ) {
43
- if ( node . property . name === 'exec' && names . indexOf ( node . object . name ) > - 1 ) {
60
+ if ( node . property . name === 'exec' && childProcessIdentifiers . has ( node . object ) ) {
44
61
if ( node . parent && node . parent . arguments && node . parent . arguments . length && node . parent . arguments [ 0 ] . type !== 'Literal' ) {
45
62
return context . report ( { node : node , message : 'Found child_process.exec() with non Literal first argument' } ) ;
46
63
}
0 commit comments