loadwise 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +88 -19
- package/agent/hooks/check-edited-file.mjs +146 -28
- package/dist/bin/github-action.js +3 -74
- package/dist/bin/loadwise.js +12 -12
- package/dist/lib/accessibility/aria-tables.js +10 -6
- package/dist/lib/accessibility/document-reference-rules.js +13 -3
- package/dist/lib/accessibility/jsx-elements.js +34 -16
- package/dist/lib/accessibility/native-interactive.js +51 -13
- package/dist/lib/accessibility/rules.js +4 -2
- package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
- package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
- package/dist/lib/accessibility/template-elements.js +5 -3
- package/dist/lib/editor/actions.js +15 -9
- package/dist/lib/editor/diagnostics.js +110 -107
- package/dist/lib/editor/finding-comparison.js +4 -25
- package/dist/lib/editor/hover-markdown.js +104 -0
- package/dist/lib/editor/inline-fix.js +50 -0
- package/dist/lib/editor/inline-recommendation.js +27 -0
- package/dist/lib/editor/language-server.js +94 -18
- package/dist/lib/editor/scan-session.js +2 -1
- package/dist/lib/editor/standalone-performance-examples.js +48 -0
- package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
- package/dist/lib/maintainability/architecture/architecture.js +50 -2
- package/dist/lib/maintainability/cli/inputs.js +12 -5
- package/dist/lib/maintainability/cli/site-fix.js +3 -0
- package/dist/lib/maintainability/cli.js +6 -3
- package/dist/lib/maintainability/examples.js +48 -0
- package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
- package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
- package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
- package/dist/lib/maintainability/rule-ids.js +18 -0
- package/dist/lib/maintainability/scan-changed.js +33 -2
- package/dist/lib/maintainability/scan.js +10 -1
- package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
- package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
- package/dist/lib/maintainability/unused/module-usage.js +67 -106
- package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
- package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
- package/dist/lib/maintainability/unused/unused-modules.js +4 -0
- package/dist/lib/performance/analysis/missing-packages.js +3 -0
- package/dist/lib/performance/analysis/source-text.js +2 -2
- package/dist/lib/performance/analyze.js +4 -1
- package/dist/lib/performance/async/floating-promises.js +25 -4
- package/dist/lib/performance/cli/cli-output.js +9 -3
- package/dist/lib/performance/cli/cli-policy.js +25 -2
- package/dist/lib/performance/cli/cli-scan.js +25 -24
- package/dist/lib/performance/cli/scan-outcome.js +19 -1
- package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
- package/dist/lib/performance/cli/watch.js +27 -8
- package/dist/lib/performance/collections/collection-lookups.js +27 -10
- package/dist/lib/performance/collections/collection-reduce.js +32 -2
- package/dist/lib/performance/collections/collections.js +28 -0
- package/dist/lib/performance/collections/repeated.js +25 -1
- package/dist/lib/performance/contracts/cli.js +22 -11
- package/dist/lib/performance/contracts/git-files.js +46 -1
- package/dist/lib/performance/datastores/pooling.js +1 -17
- package/dist/lib/performance/datastores/postgres.js +41 -33
- package/dist/lib/performance/engine/native.js +5 -1
- package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
- package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
- package/dist/lib/performance/frontend/frontend-perf.js +115 -171
- package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
- package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
- package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
- package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
- package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
- package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
- package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
- package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
- package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
- package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
- package/dist/lib/performance/frontend/template-tracking.js +86 -2
- package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
- package/dist/lib/performance/orm/prisma.js +1 -25
- package/dist/lib/performance/projects.js +3 -2
- package/dist/lib/performance/query-loops/service-loops.js +38 -8
- package/dist/lib/performance/request/json-stringify-output.js +82 -4
- package/dist/lib/performance/request/promise-schedulers.js +180 -0
- package/dist/lib/performance/request/request-handlers.js +43 -4
- package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
- package/dist/lib/performance/rule-ids.js +26 -2
- package/dist/lib/performance/site-fix.js +1 -0
- package/dist/lib/reliability/react-bugs.js +9 -0
- package/dist/lib/reliability/react-state-aliases.js +94 -4
- package/dist/lib/reliability/react-state.js +24 -5
- package/dist/lib/security/auth-crypto/secrets.js +121 -16
- package/dist/lib/security/cli.js +1 -1
- package/dist/lib/security/credential-entropy.js +12 -0
- package/dist/lib/security/deps/lockfiles.js +3 -1
- package/dist/lib/security/examples/files.js +110 -0
- package/dist/lib/security/examples/request-forgery.js +1 -1
- package/dist/lib/security/exposure/frontend-security.js +11 -2
- package/dist/lib/security/exposure/prototype-pollution.js +73 -4
- package/dist/lib/security/files/azure-pipelines.js +69 -0
- package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
- package/dist/lib/security/files/ci-platforms.js +16 -0
- package/dist/lib/security/files/ci-shared.js +260 -0
- package/dist/lib/security/files/circleci.js +81 -0
- package/dist/lib/security/files/dockerfile.js +188 -3
- package/dist/lib/security/files/github-actions.js +490 -0
- package/dist/lib/security/files/gitlab-ci.js +90 -0
- package/dist/lib/security/files/hcl.js +264 -0
- package/dist/lib/security/files/hosting-config.js +159 -0
- package/dist/lib/security/files/http-headers.js +65 -0
- package/dist/lib/security/files/index.js +62 -7
- package/dist/lib/security/files/jenkinsfile.js +482 -0
- package/dist/lib/security/files/json-nodes.js +67 -0
- package/dist/lib/security/files/nginx.js +501 -0
- package/dist/lib/security/files/package-scripts.js +175 -0
- package/dist/lib/security/files/rule-ids.js +29 -0
- package/dist/lib/security/files/secret-values.js +31 -5
- package/dist/lib/security/files/secrets.js +44 -13
- package/dist/lib/security/files/terraform.js +345 -0
- package/dist/lib/security/injection/nosql.js +2 -1
- package/dist/lib/security/injection/sql.js +2 -2
- package/dist/lib/security/lexical-declaration.js +28 -0
- package/dist/lib/security/pg-identifier-guards.js +90 -1
- package/dist/lib/security/request-forgery/member-chain.js +41 -0
- package/dist/lib/security/request-forgery/open-redirect.js +45 -8
- package/dist/lib/security/request-forgery/shared.js +18 -3
- package/dist/lib/security/rule-descriptions.js +29 -0
- package/dist/lib/security/rule-ids.js +29 -0
- package/dist/lib/security/taint/original-string-validation.js +229 -0
- package/dist/lib/security/taint/validators.js +1 -1
- package/dist/lib/shared/agent/review-delivery.js +3 -1
- package/dist/lib/shared/analysis/ast-semantics.js +17 -1
- package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
- package/dist/lib/shared/analysis/next-env-config.js +232 -0
- package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
- package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
- package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
- package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
- package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
- package/dist/lib/shared/analysis/scan-cache.js +158 -174
- package/dist/lib/shared/check-watch.js +3 -3
- package/dist/lib/shared/check.js +25 -4
- package/dist/lib/shared/config.js +1 -1
- package/dist/lib/shared/conventional-projects.js +40 -0
- package/dist/lib/shared/fix/fix-command.js +2 -0
- package/dist/lib/shared/fix/fix-usage.js +47 -0
- package/dist/lib/shared/fix/project-file-access.js +43 -20
- package/dist/lib/shared/fix.js +4 -35
- package/dist/lib/shared/formats/security-cwe.js +29 -0
- package/dist/lib/shared/project-root.js +1 -1
- package/dist/lib/shared/reporting/action-comparison.js +78 -0
- package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
- package/dist/lib/shared/reporting/check-text.js +7 -5
- package/dist/lib/shared/reporting/pillars.js +28 -8
- package/dist/lib/shared/reporting/source-report.js +4 -4
- package/dist/lib/shared/system/git.js +31 -16
- package/dist/lib/shared/system/glob.js +146 -19
- package/dist/lib/shared/system/terminal-style.js +2 -2
- package/dist/lib/shared/workspaces.js +6 -1
- package/package.json +4 -1
- package/schema/loadwise.config.schema.json +86 -0
|
@@ -5,6 +5,20 @@ import { mayBeReboundBeforeRunning, stateSetterCalledBy } from './react-state-se
|
|
|
5
5
|
import { walkRunningCode } from './react-state-walker.js';
|
|
6
6
|
import { findingAt } from './source-helpers.js';
|
|
7
7
|
import { walkNodes } from './walk.js';
|
|
8
|
+
// Array methods that change the array in place and return it, so `setTags(tags.sort())` hands the setter its own value.
|
|
9
|
+
const receiverReturningMethods = new Set(['sort', 'reverse', 'fill', 'copyWithin']);
|
|
10
|
+
// The state name a setter argument hands back: `items` itself, or the receiver of `items.sort()`.
|
|
11
|
+
function handedBackName(argument) {
|
|
12
|
+
if (ts.isIdentifier(argument))
|
|
13
|
+
return argument;
|
|
14
|
+
if (!ts.isCallExpression(argument))
|
|
15
|
+
return;
|
|
16
|
+
const callee = unwrapExpression(argument.expression);
|
|
17
|
+
if (!ts.isPropertyAccessExpression(callee) || !receiverReturningMethods.has(callee.name.text))
|
|
18
|
+
return;
|
|
19
|
+
const receiver = unwrapExpression(callee.expression);
|
|
20
|
+
return ts.isIdentifier(receiver) ? receiver : undefined;
|
|
21
|
+
}
|
|
8
22
|
function checkStateMutations(sourceFile, file, checker, findings) {
|
|
9
23
|
// A call sits inside every function that encloses it, so each is reported once.
|
|
10
24
|
const reported = new Set();
|
|
@@ -23,21 +37,26 @@ function checkStateMutations(sourceFile, file, checker, findings) {
|
|
|
23
37
|
return;
|
|
24
38
|
const setter = stateSetterCalledBy(inner, checker);
|
|
25
39
|
const argument = inner.arguments[0] && unwrapExpression(inner.arguments[0]);
|
|
26
|
-
|
|
40
|
+
const name = argument && handedBackName(argument);
|
|
41
|
+
if (!setter?.stateSymbol || !name)
|
|
42
|
+
return;
|
|
43
|
+
if (checker.getSymbolAtLocation(name) !== setter.stateSymbol)
|
|
27
44
|
return;
|
|
28
|
-
|
|
45
|
+
// `tags.sort()` counts only when it is the built-in in-place sort of that state.
|
|
46
|
+
if (name !== argument && mutatedSymbolOf(argument, checker, aliases) !== setter.stateSymbol)
|
|
29
47
|
return;
|
|
30
48
|
// A reassigned state binding hands the setter another value, not the mutated one.
|
|
31
49
|
return passed.get(inner) === setter.stateSymbol ? setter.stateSymbol : undefined;
|
|
32
50
|
}, (operation) => {
|
|
33
51
|
const first = ts.isCallExpression(operation) ? operation.arguments[0] : undefined;
|
|
52
|
+
const name = first && handedBackName(unwrapExpression(first));
|
|
34
53
|
if (first)
|
|
35
|
-
passed.set(operation, stateSymbolOfRoot(first, checker, aliases));
|
|
54
|
+
passed.set(operation, stateSymbolOfRoot(name ?? first, checker, aliases));
|
|
36
55
|
return mutatedSymbolOf(operation, checker, aliases);
|
|
37
56
|
});
|
|
38
57
|
for (const call of changedCalls) {
|
|
39
|
-
const argument = unwrapExpression(call.arguments[0]);
|
|
40
|
-
if (reported.has(call) || !
|
|
58
|
+
const argument = handedBackName(unwrapExpression(call.arguments[0]));
|
|
59
|
+
if (reported.has(call) || !argument)
|
|
41
60
|
continue;
|
|
42
61
|
if (mayBeReboundBeforeRunning(call, argument, checker))
|
|
43
62
|
continue;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
// Credentials written into source: known token shapes, signing keys and named secret values.
|
|
2
2
|
import { ts } from '../../performance/engine/compiler.js';
|
|
3
|
+
import { symbolOf } from '../../shared/analysis/ast-semantics.js';
|
|
3
4
|
import { classifyExecutionContext } from '../../shared/analysis/execution-context.js';
|
|
4
5
|
import { hasProviderCredential } from '../provider-credentials.js';
|
|
6
|
+
import { shannonEntropy } from '../credential-entropy.js';
|
|
5
7
|
import { fileMentions, libraryInfo, libraryFunction, resolveConstant, propertyKeyName, lastSegment, nameWords, } from './shared.js';
|
|
6
8
|
const message = 'A credential is hardcoded here and will be readable by anyone with the repository or the build. Load it from the environment or a secret manager and rotate the exposed value.';
|
|
7
9
|
const lowEntropyReason = 'The value has low entropy; confirm it is a real credential and not a label or sample.';
|
|
@@ -109,6 +111,11 @@ function isEnvironmentVariableName(value) {
|
|
|
109
111
|
function isIdentifierLike(value) {
|
|
110
112
|
return /^\p{L}+(?:[-_. :/]\p{L}+)*$/u.test(value);
|
|
111
113
|
}
|
|
114
|
+
// Words ending in "here", such as `session_cookie_secret_key_here`: an instruction to fill in a value.
|
|
115
|
+
function isFillInPhrase(value) {
|
|
116
|
+
const words = nameWords(value);
|
|
117
|
+
return isIdentifierLike(value) && words.length > 1 && words.at(-1) === 'here';
|
|
118
|
+
}
|
|
112
119
|
function isUrlOrPath(value) {
|
|
113
120
|
return /^(?:[a-z][a-z0-9+.-]*:\/\/|\.{0,2}\/)/i.test(value);
|
|
114
121
|
}
|
|
@@ -130,17 +137,6 @@ function isPlaceholder(value, name) {
|
|
|
130
137
|
function characterClasses(value) {
|
|
131
138
|
return [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/].filter((pattern) => pattern.test(value)).length;
|
|
132
139
|
}
|
|
133
|
-
function shannonEntropy(value) {
|
|
134
|
-
const counts = new Map();
|
|
135
|
-
for (const character of value)
|
|
136
|
-
counts.set(character, (counts.get(character) ?? 0) + 1);
|
|
137
|
-
let entropy = 0;
|
|
138
|
-
for (const count of counts.values()) {
|
|
139
|
-
const probability = count / value.length;
|
|
140
|
-
entropy -= probability * Math.log2(probability);
|
|
141
|
-
}
|
|
142
|
-
return entropy;
|
|
143
|
-
}
|
|
144
140
|
function hasSecretName(name) {
|
|
145
141
|
const normalized = name.toLowerCase().replaceAll(/[^a-z0-9]/g, '');
|
|
146
142
|
return namedSecretSuffixes.some((suffix) => normalized.endsWith(suffix));
|
|
@@ -244,6 +240,71 @@ function isEnvFallback(node) {
|
|
|
244
240
|
}
|
|
245
241
|
return false;
|
|
246
242
|
}
|
|
243
|
+
function isEnvValidationSnippet(literal, context) {
|
|
244
|
+
if (literal.text !== 'Env.schema.secret()')
|
|
245
|
+
return false;
|
|
246
|
+
const field = literal.parent;
|
|
247
|
+
if (!ts.isPropertyAssignment(field) || !ts.isObjectLiteralExpression(field.parent))
|
|
248
|
+
return false;
|
|
249
|
+
const selection = field.parent.parent;
|
|
250
|
+
if (!ts.isElementAccessExpression(selection) || selection.expression !== field.parent)
|
|
251
|
+
return false;
|
|
252
|
+
const variable = selection.parent;
|
|
253
|
+
if (!ts.isVariableDeclaration(variable) || !ts.isIdentifier(variable.name))
|
|
254
|
+
return false;
|
|
255
|
+
const declarations = variable.parent;
|
|
256
|
+
if (!ts.isVariableDeclarationList(declarations) || !(declarations.flags & ts.NodeFlags.Const))
|
|
257
|
+
return false;
|
|
258
|
+
const declaration = declarations.parent;
|
|
259
|
+
if (!ts.isVariableStatement(declaration) || !ts.isBlock(declaration.parent))
|
|
260
|
+
return false;
|
|
261
|
+
const statements = declaration.parent.statements;
|
|
262
|
+
const next = statements[statements.indexOf(declaration) + 1];
|
|
263
|
+
if (!next || !ts.isExpressionStatement(next) || !ts.isAwaitExpression(next.expression))
|
|
264
|
+
return false;
|
|
265
|
+
const call = next.expression.expression;
|
|
266
|
+
if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression))
|
|
267
|
+
return false;
|
|
268
|
+
const { expression: receiver, name } = call.expression;
|
|
269
|
+
if (name.text !== 'defineEnvValidations' || !ts.isIdentifier(receiver))
|
|
270
|
+
return false;
|
|
271
|
+
const binding = context.checker.getSymbolAtLocation(receiver)?.valueDeclaration;
|
|
272
|
+
if (!binding || !ts.isVariableDeclaration(binding) || !(binding.parent.flags & ts.NodeFlags.Const))
|
|
273
|
+
return false;
|
|
274
|
+
const factory = binding.initializer && ts.isAwaitExpression(binding.initializer) && binding.initializer.expression;
|
|
275
|
+
if (!factory || !ts.isCallExpression(factory) || !ts.isPropertyAccessExpression(factory.expression))
|
|
276
|
+
return false;
|
|
277
|
+
if (factory.expression.expression.kind !== ts.SyntaxKind.ThisKeyword ||
|
|
278
|
+
factory.expression.name.text !== 'createCodemods')
|
|
279
|
+
return false;
|
|
280
|
+
const [options] = call.arguments;
|
|
281
|
+
if (!options || !ts.isObjectLiteralExpression(options) || options.properties.length !== 1)
|
|
282
|
+
return false;
|
|
283
|
+
const [variables] = options.properties;
|
|
284
|
+
if (!ts.isPropertyAssignment(variables) || propertyKeyName(variables.name) !== 'variables')
|
|
285
|
+
return false;
|
|
286
|
+
if (!ts.isObjectLiteralExpression(variables.initializer) || variables.initializer.properties.length !== 1)
|
|
287
|
+
return false;
|
|
288
|
+
const [configured] = variables.initializer.properties;
|
|
289
|
+
const validation = context.checker.getSymbolAtLocation(variable.name);
|
|
290
|
+
if (!validation ||
|
|
291
|
+
!ts.isPropertyAssignment(configured) ||
|
|
292
|
+
!ts.isIdentifier(configured.initializer) ||
|
|
293
|
+
context.checker.getSymbolAtLocation(configured.initializer) !== validation)
|
|
294
|
+
return false;
|
|
295
|
+
const selectedValue = configured.initializer;
|
|
296
|
+
const declarationName = variable.name;
|
|
297
|
+
function usedElsewhere(node) {
|
|
298
|
+
if (ts.isIdentifier(node) &&
|
|
299
|
+
node !== declarationName &&
|
|
300
|
+
node !== selectedValue &&
|
|
301
|
+
node.text === selectedValue.text &&
|
|
302
|
+
symbolOf(node, context.checker) === validation)
|
|
303
|
+
return true;
|
|
304
|
+
return ts.forEachChild(node, usedElsewhere) ?? false;
|
|
305
|
+
}
|
|
306
|
+
return !usedElsewhere(declaration.parent);
|
|
307
|
+
}
|
|
247
308
|
function checkNamedSecret(literal, context) {
|
|
248
309
|
const value = literal.text;
|
|
249
310
|
if (value.length < shortestNamedSecret || /\s/.test(value))
|
|
@@ -251,24 +312,62 @@ function checkNamedSecret(literal, context) {
|
|
|
251
312
|
const name = targetNames(literal).find(hasSecretName);
|
|
252
313
|
if (!name)
|
|
253
314
|
return;
|
|
254
|
-
if (isEnvironmentVariableName(value) || isUrlOrPath(value)
|
|
255
|
-
return;
|
|
256
|
-
if (publicKeyShape.test(value))
|
|
315
|
+
if (isEnvironmentVariableName(value) || isUrlOrPath(value))
|
|
257
316
|
return;
|
|
258
317
|
if (hasStrongPlaceholder(value) || selfLabelledPlaceholder.test(value))
|
|
259
318
|
return;
|
|
260
319
|
const deployableFallback = runtimeConfigFile.test(context.sourceFile.fileName) || isEnvFallback(literal);
|
|
320
|
+
// `'session_secret_key_here'` was never filled in, so every deployment shares this known value.
|
|
321
|
+
if (deployableFallback && isFillInPhrase(value))
|
|
322
|
+
return context.report(literal, 'hardcoded-secret', message);
|
|
323
|
+
if (isIdentifierLike(value) || publicKeyShape.test(value))
|
|
324
|
+
return;
|
|
261
325
|
if (!deployableFallback && isPlaceholder(value, name))
|
|
262
326
|
return;
|
|
263
327
|
if (characterClasses(value) < 2)
|
|
264
328
|
return;
|
|
265
329
|
if (isRepeatedCharacters(value))
|
|
266
330
|
return;
|
|
331
|
+
if (isEnvValidationSnippet(literal, context))
|
|
332
|
+
return context.report(literal, 'hardcoded-secret', 'This string is passed to an environment schema generator.', 'Matches an environment-schema code generation pattern.');
|
|
267
333
|
const strong = characterClasses(value) >= highEntropyClasses && shannonEntropy(value) >= highEntropyBits;
|
|
268
334
|
if (strong)
|
|
269
335
|
return context.report(literal, 'hardcoded-secret', message);
|
|
270
336
|
context.report(literal, 'hardcoded-secret', message, lowEntropyReason);
|
|
271
337
|
}
|
|
338
|
+
// `postgres://app:Pa55-word@db.internal/app`: the password in a URL's user information. In a
|
|
339
|
+
// template head such as `postgres://app:Pa55-word@${host}`, the host is interpolated after the `@`.
|
|
340
|
+
const urlPassword = /^[a-z][a-z0-9+.-]*:\/\/[^\s:/?#@]*:([^\s/?#@]+)@[^\s/?#@]/i;
|
|
341
|
+
const templateHeadUrlPassword = /^[a-z][a-z0-9+.-]*:\/\/[^\s:/?#@]*:([^\s/?#@]+)@$/i;
|
|
342
|
+
const shortestUrlPassword = 8;
|
|
343
|
+
// `{{ db_password }}`, `$(DB_PASSWORD)`, `%DB_PASSWORD%` and `__DB_PASSWORD__` are filled in by a template or deploy step.
|
|
344
|
+
const templatePlaceholder = /^(?:\{\{.*\}\}|\$\(.*\)|%[^%]+%|__.+__)$/s;
|
|
345
|
+
function decodedUrlPart(part) {
|
|
346
|
+
try {
|
|
347
|
+
return decodeURIComponent(part);
|
|
348
|
+
}
|
|
349
|
+
catch {
|
|
350
|
+
// Malformed escapes: judge the text as written.
|
|
351
|
+
return part;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
// Only passwords that look generated are reported; `postgres:postgres@localhost` style defaults
|
|
355
|
+
// and placeholders stay quiet.
|
|
356
|
+
function checkUrlPassword(literal, context, pattern = urlPassword) {
|
|
357
|
+
const written = pattern.exec(literal.text)?.[1];
|
|
358
|
+
if (!written)
|
|
359
|
+
return;
|
|
360
|
+
const password = decodedUrlPart(written);
|
|
361
|
+
if (password.length < shortestUrlPassword || isEnvironmentVariableName(password))
|
|
362
|
+
return;
|
|
363
|
+
if (templatePlaceholder.test(password))
|
|
364
|
+
return;
|
|
365
|
+
if (isPlaceholder(password, '') || selfLabelledPlaceholder.test(password) || isRepeatedCharacters(password))
|
|
366
|
+
return;
|
|
367
|
+
if (characterClasses(password) < highEntropyClasses || shannonEntropy(password) < highEntropyBits)
|
|
368
|
+
return;
|
|
369
|
+
context.report(literal, 'hardcoded-secret', message);
|
|
370
|
+
}
|
|
272
371
|
function isSampleName(name) {
|
|
273
372
|
return name !== undefined && nameWords(name).some((word) => sampleNameWords.has(word));
|
|
274
373
|
}
|
|
@@ -302,11 +401,17 @@ function checkStringLiteral(literal, context) {
|
|
|
302
401
|
checkKnownCredential(literal, context);
|
|
303
402
|
if (context.fileContext.isTestSource || context.sourceFile.isDeclarationFile)
|
|
304
403
|
return;
|
|
305
|
-
if (
|
|
306
|
-
|
|
404
|
+
if (isDocumentationSample(literal, context))
|
|
405
|
+
return;
|
|
406
|
+
checkNamedSecret(literal, context);
|
|
407
|
+
checkUrlPassword(literal, context);
|
|
307
408
|
}
|
|
308
409
|
function checkTemplateText(template, context) {
|
|
309
410
|
checkKnownCredential(template, context);
|
|
411
|
+
if (!ts.isTemplateHead(template) || context.fileContext.isTestSource || context.sourceFile.isDeclarationFile)
|
|
412
|
+
return;
|
|
413
|
+
if (!isDocumentationSample(template, context))
|
|
414
|
+
checkUrlPassword(template, context, templateHeadUrlPassword);
|
|
310
415
|
}
|
|
311
416
|
// The literal behind a signing-key argument, through `process.env.X || 'literal'` and a same-file
|
|
312
417
|
// const.
|
package/dist/lib/security/cli.js
CHANGED
|
@@ -369,7 +369,7 @@ async function main(args, dependencyScanOptions) {
|
|
|
369
369
|
}
|
|
370
370
|
return exitCodeWithSkips(result, await runFixMode({ result, project, directory }, values, positionals, format));
|
|
371
371
|
}
|
|
372
|
-
const fixCommand = report.fixAllCommand('sec', project, positionals, values);
|
|
372
|
+
const fixCommand = report.fixAllCommand('sec', project, positionals, { ...values, readOnly: workspace?.readOnly });
|
|
373
373
|
const code = await report.printResult(result, { ...values, project, projectDirectory: directory, baselineOptions, fixCommand, changedLines: scope?.changedLines }, pillar);
|
|
374
374
|
return exitCodeWithSkips(result, code);
|
|
375
375
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
function shannonEntropy(value) {
|
|
2
|
+
const counts = new Map();
|
|
3
|
+
for (const character of value)
|
|
4
|
+
counts.set(character, (counts.get(character) ?? 0) + 1);
|
|
5
|
+
let entropy = 0;
|
|
6
|
+
for (const count of counts.values()) {
|
|
7
|
+
const probability = count / value.length;
|
|
8
|
+
entropy -= probability * Math.log2(probability);
|
|
9
|
+
}
|
|
10
|
+
return entropy;
|
|
11
|
+
}
|
|
12
|
+
export { shannonEntropy };
|
|
@@ -25,6 +25,8 @@ const newerLockfileKinds = [
|
|
|
25
25
|
{ file: 'bun.lock', manager: 'bun', parse: parseBunLock },
|
|
26
26
|
{ file: 'bun.lockb', manager: 'bun', parse: unsupportedBunBinaryLock },
|
|
27
27
|
];
|
|
28
|
+
/** Every lockfile name the lookup probes, in each folder from the project up. */
|
|
29
|
+
const lockfileNames = [...legacyLockfileKinds, ...newerLockfileKinds].map(({ file }) => file);
|
|
28
30
|
const manifestDependencyFields = [
|
|
29
31
|
'dependencies',
|
|
30
32
|
'devDependencies',
|
|
@@ -556,4 +558,4 @@ function manifestLocation(declarations) {
|
|
|
556
558
|
}
|
|
557
559
|
return undefined;
|
|
558
560
|
}
|
|
559
|
-
export { findLockfile, readLockfilePackages, manifestLocation };
|
|
561
|
+
export { findLockfile, lockfileNames, readLockfilePackages, manifestLocation };
|
|
@@ -1,5 +1,29 @@
|
|
|
1
1
|
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
2
2
|
const examples = {
|
|
3
|
+
'azure-pipelines-script-injection': [
|
|
4
|
+
'- bash: echo "$BRANCH"\n env:\n BRANCH: $(Build.SourceBranchName)',
|
|
5
|
+
'Map the value to an environment variable with env: so the shell reads it as data instead of script text.',
|
|
6
|
+
],
|
|
7
|
+
'bitbucket-pipelines-script-injection': [
|
|
8
|
+
'script:\n - ./deploy.sh "$BITBUCKET_BRANCH"',
|
|
9
|
+
'Pass the branch name as an argument instead of building eval or sh -c text from it.',
|
|
10
|
+
],
|
|
11
|
+
'bitbucket-pipelines-unpinned-image': [
|
|
12
|
+
'image: node:22.11-alpine',
|
|
13
|
+
'Pin a version tag, or an image digest for fully reproducible builds.',
|
|
14
|
+
],
|
|
15
|
+
'circleci-script-injection': [
|
|
16
|
+
'- run:\n environment:\n BRANCH: << pipeline.git.branch >>\n command: echo "$BRANCH"',
|
|
17
|
+
'Set the value under environment: and read the variable, so the shell treats it as data.',
|
|
18
|
+
],
|
|
19
|
+
'circleci-unpinned-image': [
|
|
20
|
+
'docker:\n - image: cimg/node:22.11',
|
|
21
|
+
'Pin a version tag, or an image digest for fully reproducible builds.',
|
|
22
|
+
],
|
|
23
|
+
'circleci-unpinned-orb': [
|
|
24
|
+
'orbs:\n slack: example/slack@4.13.3',
|
|
25
|
+
'Pin a full released version; published orb versions do not change.',
|
|
26
|
+
],
|
|
3
27
|
'committed-secret': [
|
|
4
28
|
'# .gitignore\n.env\n# keep .env.example with placeholders only',
|
|
5
29
|
'Remove the file from git, rotate the exposed credential and load the real value from the environment or a secret manager.',
|
|
@@ -8,10 +32,22 @@ const examples = {
|
|
|
8
32
|
'environment:\n - JWT_SECRET=${JWT_SECRET}',
|
|
9
33
|
'Substitute the value from the shell or an env file that is not committed, or use a compose secret.',
|
|
10
34
|
],
|
|
35
|
+
'config-cors-credentials-any-origin': [
|
|
36
|
+
'add_header Access-Control-Allow-Origin https://app.example.com always;\nadd_header Access-Control-Allow-Credentials true always;',
|
|
37
|
+
'Allow credentials only for listed origins; use a map over $http_origin when there are several.',
|
|
38
|
+
],
|
|
39
|
+
'config-unsafe-security-header': [
|
|
40
|
+
'add_header X-Frame-Options DENY always;\nadd_header Content-Security-Policy "script-src \'self\'" always;',
|
|
41
|
+
"Use DENY or SAMEORIGIN for framing and keep 'unsafe-eval' out of script-src.",
|
|
42
|
+
],
|
|
11
43
|
'dockerfile-add-remote-url': [
|
|
12
44
|
'RUN curl -fsSL -o app.tgz https://example.com/app.tgz \\\n && echo "<sha256> app.tgz" | sha256sum -c -',
|
|
13
45
|
'Download with curl and verify a checksum, or COPY a file you vendored.',
|
|
14
46
|
],
|
|
47
|
+
'dockerfile-npm-install': [
|
|
48
|
+
'COPY package.json package-lock.json ./\nRUN npm ci',
|
|
49
|
+
'npm ci installs exactly the lockfile versions and fails when package.json and the lockfile disagree.',
|
|
50
|
+
],
|
|
15
51
|
'dockerfile-runs-as-root': [
|
|
16
52
|
'RUN adduser --system app\nUSER app',
|
|
17
53
|
'Create or reuse a non-root account in the final stage and switch to it with USER.',
|
|
@@ -24,13 +60,87 @@ const examples = {
|
|
|
24
60
|
'FROM node:22.11-alpine',
|
|
25
61
|
'Pin a version tag, or an image digest for fully reproducible builds.',
|
|
26
62
|
],
|
|
63
|
+
'github-actions-pull-request-target-checkout': [
|
|
64
|
+
'on: pull_request\nsteps:\n - uses: actions/checkout@<sha>',
|
|
65
|
+
'Build untrusted pull request code in a pull_request workflow, which gets a read-only token and no secrets.',
|
|
66
|
+
],
|
|
67
|
+
'github-actions-script-injection': [
|
|
68
|
+
'env:\n TITLE: ${{ github.event.issue.title }}\nrun: echo "$TITLE"',
|
|
69
|
+
'Pass event text through env: so the shell reads it as data instead of expanding it into the script.',
|
|
70
|
+
],
|
|
71
|
+
'github-actions-unpinned-action': [
|
|
72
|
+
'- uses: owner/action@0123456789abcdef0123456789abcdef01234567 # v2.1.0',
|
|
73
|
+
'Pin the full commit SHA and keep the release in a comment so Dependabot or Renovate can update it.',
|
|
74
|
+
],
|
|
75
|
+
'gitlab-ci-script-injection': [
|
|
76
|
+
'script:\n - python3 -c \'import os; print(os.environ["CI_COMMIT_TITLE"])\'',
|
|
77
|
+
'Read the value from the environment inside the code, or pass it as an argument, instead of pasting it into eval or -c text.',
|
|
78
|
+
],
|
|
79
|
+
'gitlab-ci-unpinned-image': [
|
|
80
|
+
'image: node:22.11-alpine',
|
|
81
|
+
'Pin a version tag, or an image digest for fully reproducible builds.',
|
|
82
|
+
],
|
|
83
|
+
'gitlab-ci-unpinned-include': [
|
|
84
|
+
'include:\n - project: my-group/ci-templates\n ref: 0123456789abcdef0123456789abcdef01234567\n file: /build.yml',
|
|
85
|
+
'Pin ref: to a commit SHA or a protected tag, and give remote includes an integrity: hash.',
|
|
86
|
+
],
|
|
87
|
+
'hosting-redirect-external-wildcard': [
|
|
88
|
+
'{ "source": "/docs/:path*", "destination": "https://docs.example.com/:path*" }',
|
|
89
|
+
'Keep the destination host fixed and let only the path come from the request.',
|
|
90
|
+
],
|
|
91
|
+
'jenkinsfile-credential-interpolation': [
|
|
92
|
+
"withCredentials([string(credentialsId: 'api-token', variable: 'TOKEN')]) {\n sh 'curl -H \"Authorization: Bearer $TOKEN\" https://api.example.com'\n}",
|
|
93
|
+
'Single quotes let the shell read the secret from the environment, so it never appears in the step arguments.',
|
|
94
|
+
],
|
|
95
|
+
'jenkinsfile-script-injection': [
|
|
96
|
+
'sh \'git checkout "$BRANCH_NAME"\'',
|
|
97
|
+
'Single quotes pass the value to the shell as an environment variable instead of splicing it into the script.',
|
|
98
|
+
],
|
|
27
99
|
'kubernetes-privileged-container': [
|
|
28
100
|
'securityContext:\n privileged: false',
|
|
29
101
|
'Review the capabilities the workload actually needs before changing its security context.',
|
|
30
102
|
],
|
|
103
|
+
'nginx-proxy-pass-request-host': [
|
|
104
|
+
'location /api/ {\n proxy_pass http://api_upstream;\n proxy_set_header Host $host;\n}',
|
|
105
|
+
'Proxy to a named upstream or a fixed host; pass the client Host as a header if the backend needs it.',
|
|
106
|
+
],
|
|
107
|
+
'package-script-remote-code': [
|
|
108
|
+
'"postinstall": "node scripts/install-binary.js"',
|
|
109
|
+
'Vendor the downloaded file, or download it in a script that verifies a pinned checksum before running it.',
|
|
110
|
+
],
|
|
111
|
+
'package-script-tls-verification-disabled': [
|
|
112
|
+
'"build": "NODE_EXTRA_CA_CERTS=./certs/corp-ca.pem next build"',
|
|
113
|
+
'Trust the extra certificate authority instead of turning verification off.',
|
|
114
|
+
],
|
|
31
115
|
'template-raw-html-binding': [
|
|
32
116
|
'<div>{{ preview }}</div>',
|
|
33
117
|
'Use escaped interpolation for text, with {{ preview }} in Vue or {preview} in Svelte. Review the source and sanitization when rich content is required.',
|
|
34
118
|
],
|
|
119
|
+
'terraform-admin-port-open-to-world': [
|
|
120
|
+
'ingress {\n from_port = 22\n to_port = 22\n protocol = "tcp"\n cidr_blocks = [var.admin_cidr]\n}',
|
|
121
|
+
'Limit the source to known networks, or reach the host through a bastion, VPN or session manager.',
|
|
122
|
+
],
|
|
123
|
+
'terraform-database-publicly-accessible': [
|
|
124
|
+
'resource "aws_db_instance" "main" {\n publicly_accessible = false\n db_subnet_group_name = aws_db_subnet_group.private.name\n}',
|
|
125
|
+
'Keep the database on private subnets and connect from the application network.',
|
|
126
|
+
],
|
|
127
|
+
'terraform-hardcoded-credential': [
|
|
128
|
+
'resource "aws_db_instance" "main" {\n password = var.db_password\n}',
|
|
129
|
+
'Pass the value in through a sensitive variable, the environment or a secret manager, and rotate the committed one.',
|
|
130
|
+
],
|
|
131
|
+
'terraform-storage-bucket-public': [
|
|
132
|
+
'resource "aws_s3_bucket_public_access_block" "assets" {\n block_public_acls = true\n block_public_policy = true\n ignore_public_acls = true\n restrict_public_buckets = true\n}',
|
|
133
|
+
'Keep the bucket private and serve public files through a CDN origin access control or signed URLs.',
|
|
134
|
+
],
|
|
135
|
+
'terraform-storage-encryption-disabled': [
|
|
136
|
+
'resource "aws_ebs_volume" "data" {\n encrypted = true\n}',
|
|
137
|
+
'Turn encryption on; a customer-managed KMS key adds key rotation and access control.',
|
|
138
|
+
],
|
|
139
|
+
'web-server-directory-listing': [
|
|
140
|
+
'location /files/ {\n autoindex off;\n}',
|
|
141
|
+
'Serve an index page or return 403 for folders that are not meant to be browsed.',
|
|
142
|
+
],
|
|
143
|
+
'web-server-legacy-tls': ['ssl_protocols TLSv1.2 TLSv1.3;', 'Allow only TLS 1.2 and 1.3.'],
|
|
144
|
+
'web-server-version-exposed': ['server_tokens off;', 'Hide the version; in Apache use ServerTokens Prod.'],
|
|
35
145
|
};
|
|
36
146
|
export default examples;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
2
2
|
const examples = {
|
|
3
3
|
'open-redirect': [
|
|
4
|
-
"const next = String(req.query.next ?? '/');\nconst target = next.startsWith('/') && !next.startsWith('//') ? next : '/';\nres.redirect(target);",
|
|
4
|
+
"const next = String(req.query.next ?? '/');\nconst target = next.startsWith('/') && !next.startsWith('//') && !/[\\\\\\t\\r\\n]/.test(next) ? next : '/';\nres.redirect(target);",
|
|
5
5
|
'Redirect only to paths on this site, or compare `new URL(next).host` with an allowlist before redirecting.',
|
|
6
6
|
],
|
|
7
7
|
'path-traversal': [
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { ts, isDefaultLibrary } from '../../performance/engine/compiler.js';
|
|
12
12
|
import { staticMemberName } from '../../shared/analysis/ast-semantics.js';
|
|
13
13
|
import { hasDomPurifyAt, isJsonScript } from './react-html.js';
|
|
14
|
+
import { projectDeclares } from './package-manifest.js';
|
|
14
15
|
import { assessMessageListener } from './message-effects.js';
|
|
15
16
|
import { moduleName } from '../bindings.js';
|
|
16
17
|
import { calleeName } from '../../performance/schema/ts-helpers.js';
|
|
@@ -107,8 +108,10 @@ function declaredInDomInterface(declarations, context, interfaces) {
|
|
|
107
108
|
}
|
|
108
109
|
function declaredInitializer(identifier, context) {
|
|
109
110
|
const declaration = declarationsOf(identifier, context)[0];
|
|
111
|
+
// A destructured parameter, as in `const View = ({ html }) => ...`, has no initializer of its own;
|
|
112
|
+
// the enclosing variable holds the function, not the value.
|
|
110
113
|
const variable = declaration && ts.isBindingElement(declaration)
|
|
111
|
-
? ts.findAncestor(declaration, ts.isVariableDeclaration)
|
|
114
|
+
? ts.findAncestor(declaration, (node) => ts.isVariableDeclaration(node) || (ts.isParameter(node) && 'quit'))
|
|
112
115
|
: declaration;
|
|
113
116
|
return variable && ts.isVariableDeclaration(variable) ? variable.initializer : undefined;
|
|
114
117
|
}
|
|
@@ -484,7 +487,13 @@ function importsPackage(sourceFile, packages) {
|
|
|
484
487
|
function isReactAttribute(attribute, context) {
|
|
485
488
|
const declarations = declarationsOf(attribute.name, context);
|
|
486
489
|
const typedByReact = declarations.some((declaration) => REACT_TYPES_PATH.test(normalizeSlashes(declaration.getSourceFile().fileName)));
|
|
487
|
-
|
|
490
|
+
if (typedByReact || importsPackage(attribute.getSourceFile(), REACT_PACKAGES))
|
|
491
|
+
return true;
|
|
492
|
+
// The automatic JSX runtime needs no React import. An attribute without resolved types declares
|
|
493
|
+
// only itself; then the project's manifest tells React apart from other JSX.
|
|
494
|
+
const sourceFile = attribute.getSourceFile();
|
|
495
|
+
const untyped = declarations.every((declaration) => declaration.getSourceFile() === sourceFile);
|
|
496
|
+
return untyped && REACT_PACKAGES.some((name) => projectDeclares(sourceFile.fileName, name));
|
|
488
497
|
}
|
|
489
498
|
function htmlProperty(object) {
|
|
490
499
|
return object.properties.find((property) => (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) &&
|
|
@@ -28,6 +28,58 @@ function isNullPrototypeRoot(expression, checker) {
|
|
|
28
28
|
initializer.arguments.length >= 1 &&
|
|
29
29
|
unwrap(initializer.arguments[0]).kind === ts.SyntaxKind.NullKeyword);
|
|
30
30
|
}
|
|
31
|
+
// The string literals of `['a', 'b'].includes(key)`, or of `BLOCKED.has(key)` where `BLOCKED` is a
|
|
32
|
+
// const `new Set([...literals])` that is never added to.
|
|
33
|
+
function literalKeyList(receiver, method, checker) {
|
|
34
|
+
let list = unwrap(receiver);
|
|
35
|
+
if (method === 'has') {
|
|
36
|
+
const declaration = ts.isIdentifier(list) ? checker.getSymbolAtLocation(list)?.valueDeclaration : undefined;
|
|
37
|
+
if (!declaration || !ts.isVariableDeclaration(declaration) || !(declaration.parent.flags & ts.NodeFlags.Const))
|
|
38
|
+
return;
|
|
39
|
+
const created = unwrap(declaration.initializer);
|
|
40
|
+
if (!created || !ts.isNewExpression(created) || created.expression.getText() !== 'Set')
|
|
41
|
+
return;
|
|
42
|
+
if (isSetMutated(declaration, checker))
|
|
43
|
+
return;
|
|
44
|
+
list = created.arguments?.[0] && unwrap(created.arguments[0]);
|
|
45
|
+
}
|
|
46
|
+
if (!list || !ts.isArrayLiteralExpression(list) || !list.elements.every(ts.isStringLiteralLike))
|
|
47
|
+
return;
|
|
48
|
+
return list.elements.flatMap((element) => (ts.isStringLiteralLike(element) ? [element.text] : []));
|
|
49
|
+
}
|
|
50
|
+
const setMutationCache = new WeakMap();
|
|
51
|
+
function isExported(declaration) {
|
|
52
|
+
const statement = declaration.parent.parent;
|
|
53
|
+
return (ts.isVariableStatement(statement) &&
|
|
54
|
+
!!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword));
|
|
55
|
+
}
|
|
56
|
+
// `BLOCKED.has(key)` and `BLOCKED.size` read the set; any other reference (an alias, a computed
|
|
57
|
+
// method, an argument, an export) could reach `add` or `delete`.
|
|
58
|
+
function isSetRead(reference) {
|
|
59
|
+
const access = reference.parent;
|
|
60
|
+
if (!ts.isPropertyAccessExpression(access) || access.expression !== reference)
|
|
61
|
+
return false;
|
|
62
|
+
if (access.name.text === 'size')
|
|
63
|
+
return !ts.isAssignmentTarget(access);
|
|
64
|
+
return access.name.text === 'has' && ts.isCallExpression(access.parent) && access.parent.expression === access;
|
|
65
|
+
}
|
|
66
|
+
function isSetMutated(declaration, checker) {
|
|
67
|
+
const cached = setMutationCache.get(declaration);
|
|
68
|
+
if (cached !== undefined)
|
|
69
|
+
return cached;
|
|
70
|
+
const symbol = checker.getSymbolAtLocation(declaration.name);
|
|
71
|
+
const mutated = isExported(declaration) ||
|
|
72
|
+
!!(function visit(node) {
|
|
73
|
+
if (ts.isIdentifier(node) &&
|
|
74
|
+
node !== declaration.name &&
|
|
75
|
+
checker.getSymbolAtLocation(node) === symbol &&
|
|
76
|
+
!isSetRead(node))
|
|
77
|
+
return true;
|
|
78
|
+
return ts.forEachChild(node, visit);
|
|
79
|
+
})(declaration.getSourceFile());
|
|
80
|
+
setMutationCache.set(declaration, mutated);
|
|
81
|
+
return mutated;
|
|
82
|
+
}
|
|
31
83
|
// Every sensitive name must be excluded on the control-flow path that reaches this use.
|
|
32
84
|
function hasPrototypeKeyGuard(key, use, checker) {
|
|
33
85
|
const binding = unwrap(key);
|
|
@@ -43,14 +95,14 @@ function hasPrototypeKeyGuard(key, use, checker) {
|
|
|
43
95
|
return prototypeKeys.every((excluded) => isGuardedByCondition(use, (condition, truth) => {
|
|
44
96
|
if (ts.isCallExpression(condition) && ts.isPropertyAccessExpression(condition.expression)) {
|
|
45
97
|
const method = condition.expression;
|
|
46
|
-
if (method.name.text !== 'includes' ||
|
|
98
|
+
if ((method.name.text !== 'includes' && method.name.text !== 'has') ||
|
|
47
99
|
condition.arguments.length !== 1 ||
|
|
48
100
|
checker.getSymbolAtLocation(unwrap(condition.arguments[0])) !== symbol)
|
|
49
101
|
return false;
|
|
50
|
-
const options =
|
|
51
|
-
if (!
|
|
102
|
+
const options = literalKeyList(method.expression, method.name.text, checker);
|
|
103
|
+
if (!options)
|
|
52
104
|
return false;
|
|
53
|
-
const contains = options.
|
|
105
|
+
const contains = options.includes(excluded);
|
|
54
106
|
return truth ? !contains : contains;
|
|
55
107
|
}
|
|
56
108
|
if (!ts.isBinaryExpression(condition))
|
|
@@ -113,6 +165,21 @@ function isSyntacticPrimitive(expression) {
|
|
|
113
165
|
(node.operator === ts.SyntaxKind.PlusToken || node.operator === ts.SyntaxKind.MinusToken) &&
|
|
114
166
|
ts.isNumericLiteral(unwrap(node.operand)));
|
|
115
167
|
}
|
|
168
|
+
// `target[key] = target[key] ?? {}`: for `__proto__` this stores the existing prototype back, for
|
|
169
|
+
// `constructor` an own copy of the inherited function, so the write reaches no other object. A
|
|
170
|
+
// nested write through the result is checked on its own.
|
|
171
|
+
function isDefaultingWrite(target, value) {
|
|
172
|
+
const fallback = unwrap(value);
|
|
173
|
+
if (!ts.isBinaryExpression(fallback))
|
|
174
|
+
return false;
|
|
175
|
+
const operator = fallback.operatorToken.kind;
|
|
176
|
+
if (operator !== ts.SyntaxKind.QuestionQuestionToken && operator !== ts.SyntaxKind.BarBarToken)
|
|
177
|
+
return false;
|
|
178
|
+
const empty = unwrap(fallback.right);
|
|
179
|
+
const isEmptyLiteral = (ts.isObjectLiteralExpression(empty) && !empty.properties.length) ||
|
|
180
|
+
(ts.isArrayLiteralExpression(empty) && !empty.elements.length);
|
|
181
|
+
return isEmptyLiteral && unwrap(fallback.left).getText() === target.getText();
|
|
182
|
+
}
|
|
116
183
|
// `target[a][b] = value`, `target[a].x = value`: the first dynamic key may name `__proto__`.
|
|
117
184
|
function checkAssignment(node, context) {
|
|
118
185
|
if (node.operatorToken.kind !== ts.SyntaxKind.EqualsToken)
|
|
@@ -139,6 +206,8 @@ function checkAssignment(node, context) {
|
|
|
139
206
|
return;
|
|
140
207
|
if (isSyntacticPrimitive(node.right) || isPrimitiveValue(node.right, context.checker))
|
|
141
208
|
return;
|
|
209
|
+
if (isDefaultingWrite(target, node.right))
|
|
210
|
+
return;
|
|
142
211
|
const traced = context.taint.trace(target.argumentExpression, 'proto-key');
|
|
143
212
|
if (!traced)
|
|
144
213
|
return checkParameterPathWrite(node, context);
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { normalizeSlashes } from '../../shared/system/posix-path.js';
|
|
2
|
+
import { listItemMaps, mapNode, parseCiDocuments, sortFindings, stringNode } from './ci-shared.js';
|
|
3
|
+
const azurePipelinesPath = /(?:^|\/)(?:azure-pipelines\.ya?ml|\.azure-pipelines\/[^/]+\.ya?ml)$/i;
|
|
4
|
+
// Macros are replaced in the script text before the task starts, so the value becomes code.
|
|
5
|
+
const untrustedMacro = /\$\((Build\.SourceVersion(?:Message|Author)|Build\.SourceBranch(?:Name)?|System\.PullRequest\.SourceBranch(?:Name)?)\)/gi;
|
|
6
|
+
// Stops at the next `${{`, so an unterminated expression cannot make the scan quadratic.
|
|
7
|
+
const expression = /\$\{\{((?:[^}$]|\}(?!\})|\$(?!\{\{))*)\}\}/g;
|
|
8
|
+
// Only the branch variables exist when templates are expanded; a function call such as eq()
|
|
9
|
+
// expands to a boolean instead of the branch name.
|
|
10
|
+
const untrustedTemplateVariable = /^\s*variables\[\s*'(Build\.SourceBranch(?:Name)?)'\s*\]\s*$/i;
|
|
11
|
+
const scriptStepKeys = ['script', 'bash', 'powershell', 'pwsh'];
|
|
12
|
+
// Shell and inline-script tasks, with the input that holds the script.
|
|
13
|
+
const scriptTaskInputs = {
|
|
14
|
+
azurecli: ['inlinescript'],
|
|
15
|
+
azurepowershell: ['inline'],
|
|
16
|
+
bash: ['script'],
|
|
17
|
+
cmdline: ['script'],
|
|
18
|
+
powershell: ['script'],
|
|
19
|
+
pythonscript: ['script'],
|
|
20
|
+
};
|
|
21
|
+
function isAzurePipelinesFile(file) {
|
|
22
|
+
return azurePipelinesPath.test(normalizeSlashes(file));
|
|
23
|
+
}
|
|
24
|
+
function taskScripts(step) {
|
|
25
|
+
const task = stringNode(step.get('task', true))?.value.split('@')[0].trim().toLowerCase();
|
|
26
|
+
const inputNames = task ? scriptTaskInputs[task] : undefined;
|
|
27
|
+
const inputs = mapNode(step.get('inputs', true));
|
|
28
|
+
if (!inputNames || !inputs)
|
|
29
|
+
return [];
|
|
30
|
+
return inputs.items
|
|
31
|
+
.filter(({ key }) => inputNames.includes(String(stringNode(key)?.value).toLowerCase()))
|
|
32
|
+
.map(({ value }) => value);
|
|
33
|
+
}
|
|
34
|
+
function scriptsOf(step) {
|
|
35
|
+
if (step.has('task'))
|
|
36
|
+
return taskScripts(step);
|
|
37
|
+
return scriptStepKeys.map((key) => step.get(key, true));
|
|
38
|
+
}
|
|
39
|
+
function report(reportAt, offset, variable, form) {
|
|
40
|
+
reportAt('azure-pipelines-script-injection', offset, `\`${form}\` pastes ${variable}, text the commit or branch author controls, into the script before it runs, so the author can inject commands. Map it to an environment variable with \`env:\` and read that variable instead.`);
|
|
41
|
+
}
|
|
42
|
+
function reportScript(node, text, reportAt) {
|
|
43
|
+
const script = stringNode(node);
|
|
44
|
+
if (!script?.range)
|
|
45
|
+
return;
|
|
46
|
+
// Macros and expressions sit on one source line, so the raw scalar text keeps their positions.
|
|
47
|
+
const [start, end] = script.range;
|
|
48
|
+
const source = text.slice(start, end);
|
|
49
|
+
for (const match of source.matchAll(untrustedMacro))
|
|
50
|
+
report(reportAt, start + match.index, match[1], match[0]);
|
|
51
|
+
for (const match of source.matchAll(expression)) {
|
|
52
|
+
const variable = untrustedTemplateVariable.exec(match[1]);
|
|
53
|
+
if (variable)
|
|
54
|
+
report(reportAt, start + match.index, variable[1], match[0]);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function checkAzurePipelines(file, text) {
|
|
58
|
+
if (!isAzurePipelinesFile(file))
|
|
59
|
+
return [];
|
|
60
|
+
const parsed = parseCiDocuments(text);
|
|
61
|
+
if (!parsed)
|
|
62
|
+
return [];
|
|
63
|
+
for (const step of parsed.roots.flatMap(listItemMaps)) {
|
|
64
|
+
for (const script of scriptsOf(step))
|
|
65
|
+
reportScript(script, text, parsed.report);
|
|
66
|
+
}
|
|
67
|
+
return sortFindings(parsed.findings);
|
|
68
|
+
}
|
|
69
|
+
export { checkAzurePipelines, isAzurePipelinesFile };
|