eslint-plugin-sonarjs
Version:
330 lines (329 loc) • 12.6 kB
JavaScript
;
/*
* SonarQube JavaScript Plugin
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
// https://sonarsource.github.io/rspec/#/rspec/S2245/javascript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.rule = void 0;
const ancestor_js_1 = require("../helpers/ancestor.js");
const ast_js_1 = require("../helpers/ast.js");
const generate_meta_js_1 = require("../helpers/generate-meta.js");
const module_js_1 = require("../helpers/module.js");
const meta = __importStar(require("./generated-meta.js"));
const CRYPTO_MODULES = new Set([
'crypto',
'node:crypto',
'jsonwebtoken',
'jose',
'passport',
'express-session',
'cookie-session',
'crypto-js',
'node-forge',
'tweetnacl',
'sjcl',
'jsrsasign',
'elliptic',
'bcrypt',
'bcryptjs',
'argon2',
'scrypt',
'pbkdf2',
'jws',
'jwt-simple',
'express-jwt',
'otplib',
'speakeasy',
'next-auth',
]);
const CRYPTO_PREFIXES = ['@noble/', '@aws-crypto/', '@auth/'];
const SECURITY_KEYWORDS = new Set([
'aes',
'asymmetric',
'auth',
'certificate',
'chacha20',
'cipher',
'crypto',
'cryptography',
'decrypt',
'ecc',
'encrypt',
'encryption',
'hmac',
'insecurerandom', // not in the ticket's list: class/function names like `InsecureRandomService`
'iv',
'nonce',
'password',
'pbkdf2',
'poly1305',
'randombytes',
'rsa',
'salt',
'scrypt',
'secret',
'secure',
'security',
'sessionid',
'signature',
'token',
'verify',
]);
// Wrappers and expression nodes that may sit between a function and the variable/property receiving its
// result, e.g. `const token = Array.from({ length: 16 }, () => Math.random())` or `(() => ...) as T`
const PASS_THROUGH = new Set([
'CallExpression',
'NewExpression',
'MemberExpression',
'ChainExpression',
'ArrayExpression',
'SpreadElement',
'AwaitExpression',
'ConditionalExpression',
'LogicalExpression',
'BinaryExpression',
'UnaryExpression',
'TemplateLiteral',
'SequenceExpression',
'TSAsExpression',
'TSSatisfiesExpression',
'TSNonNullExpression',
'TSTypeAssertion',
]);
// `import x from 'crypto-js/aes'` counts as 'crypto-js'; `@scope/pkg/sub` as '@scope/pkg'
function packageName(moduleName) {
const parts = moduleName.split('/');
return moduleName.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
}
function isCryptoModule(moduleName) {
return (CRYPTO_MODULES.has(moduleName) ||
CRYPTO_MODULES.has(packageName(moduleName)) ||
CRYPTO_PREFIXES.some(prefix => moduleName.startsWith(prefix)));
}
// Splits camelCase/snake_case names into lowercase words. A word matches a keyword when the word itself,
// its letters-only parts (`aes256` -> `aes`, but `pbkdf2` still matches whole), or the word joined with the
// previous one match, so that `sessionId` matches `sessionid` and `randomBytes` matches `randombytes`.
function hasKeyword(identifier) {
const words = identifier
.replaceAll(/(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g, ' ')
.toLowerCase()
.split(/[^a-z\d]+/)
.filter(Boolean);
return words.some((word, i) => SECURITY_KEYWORDS.has(word) ||
word.split(/\d+/).some(part => SECURITY_KEYWORDS.has(part)) ||
(i > 0 && SECURITY_KEYWORDS.has(words[i - 1] + word)));
}
function isIdentifier(token) {
return token.type === 'Identifier' || token.type === 'PrivateIdentifier';
}
function isNode(value) {
return typeof value?.type === 'string';
}
function childNodes(sourceCode, node) {
return (sourceCode.visitorKeys[node.type] ?? []).flatMap(key => {
const child = node[key];
return (Array.isArray(child) ? child : [child]).filter(isNode);
});
}
const TS_WRAPPERS = new Set([
'TSAsExpression',
'TSSatisfiesExpression',
'TSNonNullExpression',
'TSTypeAssertion',
]);
// the name a function is directly bound to (`const f = () => {}`, `{ f: () => {} }`), as opposed to the
// name receiving the result of a call that takes the function as an argument
function directBinding(fn) {
let child = fn;
let parent = fn.parent;
while (parent && TS_WRAPPERS.has(parent.type)) {
child = parent;
parent = parent.parent;
}
switch (parent?.type) {
case 'VariableDeclarator':
return parent.init === child ? parent.id : undefined;
case 'AssignmentExpression':
return parent.right === child ? parent.left : undefined;
case 'Property':
case 'PropertyDefinition':
return parent.value === child ? parent.key : undefined;
default:
return undefined;
}
}
// ranges of the outermost functions inside the scope, including the name they are bound to, sorted by position
function nestedFunctionRanges(sourceCode, scope) {
const ranges = [];
const pending = [scope];
for (let node = pending.pop(); node; node = pending.pop()) {
for (const child of childNodes(sourceCode, node)) {
if (ast_js_1.functionLike.has(child.type)) {
const [start, end] = sourceCode.getRange(child);
const binding = directBinding(child);
const bindingStart = binding ? sourceCode.getRange(binding)[0] : start;
ranges.push([Math.min(bindingStart, start), end]);
}
else {
pending.push(child);
}
}
}
return ranges.sort((a, b) => a[0] - b[0]);
}
exports.rule = {
meta: (0, generate_meta_js_1.generateMeta)(meta, {
messages: {
safeGenerator: 'Make sure that using this pseudorandom number generator is safe here.',
},
}),
create(context) {
const sourceCode = context.sourceCode;
let hasCryptoImport;
function importsCrypto() {
hasCryptoImport ??= [...(0, module_js_1.getCurrentFileModuleReferences)(sourceCode)].some(isCryptoModule);
return hasCryptoImport;
}
// identifiers in the range, nested functions included (used for headers and naming targets)
function scanRange(range) {
return sourceCode
.getTokens({ range })
.some(token => isIdentifier(token) && hasKeyword(token.value));
}
// identifiers of the scope itself; nested functions are other scopes and are skipped
function scanLocal(scope) {
const skipped = nestedFunctionRanges(sourceCode, scope);
let next = 0;
return sourceCode.getTokens(scope).some(token => {
const start = token.range[0];
while (next < skipped.length && skipped[next][1] <= start) {
next++;
}
const inNestedFunction = next < skipped.length && skipped[next][0] <= start;
return !inNestedFunction && isIdentifier(token) && hasKeyword(token.value);
});
}
// one scan per scope: Math.random() is often called many times in the same scope
const localCache = new Map();
const headerCache = new Map();
const namingCache = new Map();
function cached(cache, key, scan) {
let result = cache.get(key);
if (result === undefined) {
result = scan();
cache.set(key, result);
}
return result;
}
// the name receiving the function or its result: `const generateToken = () => ...`,
// `{ makeSecret() {} }`, `const token = Array.from(..., () => Math.random())`, `(() => ...) as T`
function namingTarget(fn) {
let parent = fn.parent;
while (parent && PASS_THROUGH.has(parent.type)) {
parent = parent.parent;
}
switch (parent?.type) {
case 'VariableDeclarator':
return parent.id;
case 'AssignmentExpression':
return parent.left;
case 'Property':
case 'MethodDefinition':
case 'PropertyDefinition':
return parent.key;
default:
return undefined;
}
}
function nameHasKeyword(fn) {
const target = namingTarget(fn);
return (target !== undefined &&
cached(namingCache, target, () => scanRange(sourceCode.getRange(target))));
}
// name and parameters only, so that an anonymous module wrapper (IIFE/AMD) does not drag the whole file in
function headerHasKeyword(fn) {
const body = fn.body;
return cached(headerCache, fn, () => scanRange([sourceCode.getRange(fn)[0], sourceCode.getRange(body)[0]]));
}
// names of enclosing classes, e.g. `InsecureRandomService` around its methods
function classNameHasKeyword(node) {
return (0, ancestor_js_1.ancestorsChain)(node, new Set())
.filter(n => n.type === 'ClassDeclaration' || n.type === 'ClassExpression')
.some(cls => {
const target = cls.id ?? namingTarget(cls);
return (target !== undefined &&
cached(namingCache, target, () => scanRange(sourceCode.getRange(target))));
});
}
function isSecurityContext(node) {
if (importsCrypto()) {
return true;
}
// innermost function first; callbacks inside `generatePassword` are still reported via its header
const [inner, ...outer] = (0, ancestor_js_1.ancestorsChain)(node, new Set()).filter(n => ast_js_1.functionLike.has(n.type) && n.type !== 'MethodDefinition');
const inScope = inner === undefined
? cached(localCache, sourceCode.ast, () => scanLocal(sourceCode.ast))
: cached(localCache, inner, () => scanLocal(inner)) ||
nameHasKeyword(inner) ||
outer.some(fn => headerHasKeyword(fn) || nameHasKeyword(fn));
return inScope || classNameHasKeyword(node);
}
return {
CallExpression(node) {
const fqn = (0, module_js_1.getFullyQualifiedName)(context, node);
if (fqn === 'Math.random' && isSecurityContext(node)) {
context.report({
messageId: 'safeGenerator',
node,
});
}
},
};
},
};