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.
Files changed (155) hide show
  1. package/README.md +88 -19
  2. package/agent/hooks/check-edited-file.mjs +146 -28
  3. package/dist/bin/github-action.js +3 -74
  4. package/dist/bin/loadwise.js +12 -12
  5. package/dist/lib/accessibility/aria-tables.js +10 -6
  6. package/dist/lib/accessibility/document-reference-rules.js +13 -3
  7. package/dist/lib/accessibility/jsx-elements.js +34 -16
  8. package/dist/lib/accessibility/native-interactive.js +51 -13
  9. package/dist/lib/accessibility/rules.js +4 -2
  10. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  11. package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
  12. package/dist/lib/accessibility/template-elements.js +5 -3
  13. package/dist/lib/editor/actions.js +15 -9
  14. package/dist/lib/editor/diagnostics.js +110 -107
  15. package/dist/lib/editor/finding-comparison.js +4 -25
  16. package/dist/lib/editor/hover-markdown.js +104 -0
  17. package/dist/lib/editor/inline-fix.js +50 -0
  18. package/dist/lib/editor/inline-recommendation.js +27 -0
  19. package/dist/lib/editor/language-server.js +94 -18
  20. package/dist/lib/editor/scan-session.js +2 -1
  21. package/dist/lib/editor/standalone-performance-examples.js +48 -0
  22. package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
  23. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  24. package/dist/lib/maintainability/cli/inputs.js +12 -5
  25. package/dist/lib/maintainability/cli/site-fix.js +3 -0
  26. package/dist/lib/maintainability/cli.js +6 -3
  27. package/dist/lib/maintainability/examples.js +48 -0
  28. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  29. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  30. package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
  31. package/dist/lib/maintainability/rule-ids.js +18 -0
  32. package/dist/lib/maintainability/scan-changed.js +33 -2
  33. package/dist/lib/maintainability/scan.js +10 -1
  34. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  35. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  36. package/dist/lib/maintainability/unused/module-usage.js +67 -106
  37. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  38. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  39. package/dist/lib/maintainability/unused/unused-modules.js +4 -0
  40. package/dist/lib/performance/analysis/missing-packages.js +3 -0
  41. package/dist/lib/performance/analysis/source-text.js +2 -2
  42. package/dist/lib/performance/analyze.js +4 -1
  43. package/dist/lib/performance/async/floating-promises.js +25 -4
  44. package/dist/lib/performance/cli/cli-output.js +9 -3
  45. package/dist/lib/performance/cli/cli-policy.js +25 -2
  46. package/dist/lib/performance/cli/cli-scan.js +25 -24
  47. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  48. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  49. package/dist/lib/performance/cli/watch.js +27 -8
  50. package/dist/lib/performance/collections/collection-lookups.js +27 -10
  51. package/dist/lib/performance/collections/collection-reduce.js +32 -2
  52. package/dist/lib/performance/collections/collections.js +28 -0
  53. package/dist/lib/performance/collections/repeated.js +25 -1
  54. package/dist/lib/performance/contracts/cli.js +22 -11
  55. package/dist/lib/performance/contracts/git-files.js +46 -1
  56. package/dist/lib/performance/datastores/pooling.js +1 -17
  57. package/dist/lib/performance/datastores/postgres.js +41 -33
  58. package/dist/lib/performance/engine/native.js +5 -1
  59. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  60. package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
  61. package/dist/lib/performance/frontend/frontend-perf.js +115 -171
  62. package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
  63. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  64. package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
  65. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  66. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  67. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  68. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  69. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  70. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  71. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  72. package/dist/lib/performance/frontend/template-tracking.js +86 -2
  73. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  74. package/dist/lib/performance/orm/prisma.js +1 -25
  75. package/dist/lib/performance/projects.js +3 -2
  76. package/dist/lib/performance/query-loops/service-loops.js +38 -8
  77. package/dist/lib/performance/request/json-stringify-output.js +82 -4
  78. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  79. package/dist/lib/performance/request/request-handlers.js +43 -4
  80. package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
  81. package/dist/lib/performance/rule-ids.js +26 -2
  82. package/dist/lib/performance/site-fix.js +1 -0
  83. package/dist/lib/reliability/react-bugs.js +9 -0
  84. package/dist/lib/reliability/react-state-aliases.js +94 -4
  85. package/dist/lib/reliability/react-state.js +24 -5
  86. package/dist/lib/security/auth-crypto/secrets.js +121 -16
  87. package/dist/lib/security/cli.js +1 -1
  88. package/dist/lib/security/credential-entropy.js +12 -0
  89. package/dist/lib/security/deps/lockfiles.js +3 -1
  90. package/dist/lib/security/examples/files.js +110 -0
  91. package/dist/lib/security/examples/request-forgery.js +1 -1
  92. package/dist/lib/security/exposure/frontend-security.js +11 -2
  93. package/dist/lib/security/exposure/prototype-pollution.js +73 -4
  94. package/dist/lib/security/files/azure-pipelines.js +69 -0
  95. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  96. package/dist/lib/security/files/ci-platforms.js +16 -0
  97. package/dist/lib/security/files/ci-shared.js +260 -0
  98. package/dist/lib/security/files/circleci.js +81 -0
  99. package/dist/lib/security/files/dockerfile.js +188 -3
  100. package/dist/lib/security/files/github-actions.js +490 -0
  101. package/dist/lib/security/files/gitlab-ci.js +90 -0
  102. package/dist/lib/security/files/hcl.js +264 -0
  103. package/dist/lib/security/files/hosting-config.js +159 -0
  104. package/dist/lib/security/files/http-headers.js +65 -0
  105. package/dist/lib/security/files/index.js +62 -7
  106. package/dist/lib/security/files/jenkinsfile.js +482 -0
  107. package/dist/lib/security/files/json-nodes.js +67 -0
  108. package/dist/lib/security/files/nginx.js +501 -0
  109. package/dist/lib/security/files/package-scripts.js +175 -0
  110. package/dist/lib/security/files/rule-ids.js +29 -0
  111. package/dist/lib/security/files/secret-values.js +31 -5
  112. package/dist/lib/security/files/secrets.js +44 -13
  113. package/dist/lib/security/files/terraform.js +345 -0
  114. package/dist/lib/security/injection/nosql.js +2 -1
  115. package/dist/lib/security/injection/sql.js +2 -2
  116. package/dist/lib/security/lexical-declaration.js +28 -0
  117. package/dist/lib/security/pg-identifier-guards.js +90 -1
  118. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  119. package/dist/lib/security/request-forgery/open-redirect.js +45 -8
  120. package/dist/lib/security/request-forgery/shared.js +18 -3
  121. package/dist/lib/security/rule-descriptions.js +29 -0
  122. package/dist/lib/security/rule-ids.js +29 -0
  123. package/dist/lib/security/taint/original-string-validation.js +229 -0
  124. package/dist/lib/security/taint/validators.js +1 -1
  125. package/dist/lib/shared/agent/review-delivery.js +3 -1
  126. package/dist/lib/shared/analysis/ast-semantics.js +17 -1
  127. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  128. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  129. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  130. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  131. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  132. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  133. package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
  134. package/dist/lib/shared/analysis/scan-cache.js +158 -174
  135. package/dist/lib/shared/check-watch.js +3 -3
  136. package/dist/lib/shared/check.js +25 -4
  137. package/dist/lib/shared/config.js +1 -1
  138. package/dist/lib/shared/conventional-projects.js +40 -0
  139. package/dist/lib/shared/fix/fix-command.js +2 -0
  140. package/dist/lib/shared/fix/fix-usage.js +47 -0
  141. package/dist/lib/shared/fix/project-file-access.js +43 -20
  142. package/dist/lib/shared/fix.js +4 -35
  143. package/dist/lib/shared/formats/security-cwe.js +29 -0
  144. package/dist/lib/shared/project-root.js +1 -1
  145. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  146. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  147. package/dist/lib/shared/reporting/check-text.js +7 -5
  148. package/dist/lib/shared/reporting/pillars.js +28 -8
  149. package/dist/lib/shared/reporting/source-report.js +4 -4
  150. package/dist/lib/shared/system/git.js +31 -16
  151. package/dist/lib/shared/system/glob.js +146 -19
  152. package/dist/lib/shared/system/terminal-style.js +2 -2
  153. package/dist/lib/shared/workspaces.js +6 -1
  154. package/package.json +4 -1
  155. package/schema/loadwise.config.schema.json +86 -0
@@ -0,0 +1,32 @@
1
+ import { normalizeSlashes } from '../../shared/system/posix-path.js';
2
+ import { listItemMaps, mapNode, parseCiDocuments, reportMutableImage, reportShellInjections, scriptStrings, sortFindings, } from './ci-shared.js';
3
+ const bitbucketPipelinesPath = /(?:^|\/)bitbucket-pipelines\.ya?ml$/i;
4
+ // The branch name reaches the shell as an environment variable; only a second parse makes it code.
5
+ const untrustedVariable = /\$\{?(BITBUCKET_BRANCH)(?!\w)/g;
6
+ const scriptKeys = ['script', 'after-script'];
7
+ function isBitbucketPipelinesFile(file) {
8
+ return bitbucketPipelinesPath.test(normalizeSlashes(file));
9
+ }
10
+ function checkBitbucketPipelines(file, text) {
11
+ if (!isBitbucketPipelinesFile(file))
12
+ return [];
13
+ const parsed = parseCiDocuments(text);
14
+ if (!parsed)
15
+ return [];
16
+ const { roots, report, findings } = parsed;
17
+ for (const root of roots) {
18
+ reportMutableImage(root.get('image', true), 'bitbucket-pipelines-unpinned-image', 'Build', report);
19
+ // Steps are `- step:` list items under default, branches, pull-requests, tags, custom,
20
+ // parallel and stage entries.
21
+ for (const item of listItemMaps(root)) {
22
+ const step = mapNode(item.get('step', true));
23
+ if (!step)
24
+ continue;
25
+ const scripts = scriptKeys.flatMap((key) => scriptStrings(step.get(key, true)));
26
+ reportShellInjections(scripts, text, untrustedVariable, 'bitbucket-pipelines-script-injection', report);
27
+ reportMutableImage(step.get('image', true), 'bitbucket-pipelines-unpinned-image', 'Step', report);
28
+ }
29
+ }
30
+ return sortFindings(findings);
31
+ }
32
+ export { checkBitbucketPipelines, isBitbucketPipelinesFile };
@@ -0,0 +1,16 @@
1
+ import { checkAzurePipelines, isAzurePipelinesFile } from './azure-pipelines.js';
2
+ import { checkBitbucketPipelines, isBitbucketPipelinesFile } from './bitbucket-pipelines.js';
3
+ import { checkCircleci, isCircleciFile } from './circleci.js';
4
+ import { checkGitlabCi, isGitlabCiFile } from './gitlab-ci.js';
5
+ function isCiPlatformFile(file) {
6
+ return isGitlabCiFile(file) || isAzurePipelinesFile(file) || isCircleciFile(file) || isBitbucketPipelinesFile(file);
7
+ }
8
+ function checkCiPlatforms(file, text) {
9
+ return [
10
+ ...checkGitlabCi(file, text),
11
+ ...checkAzurePipelines(file, text),
12
+ ...checkCircleci(file, text),
13
+ ...checkBitbucketPipelines(file, text),
14
+ ];
15
+ }
16
+ export { checkCiPlatforms, isCiPlatformFile };
@@ -0,0 +1,260 @@
1
+ // Helpers shared by the GitLab CI, Azure Pipelines, CircleCI and Bitbucket Pipelines checks: a
2
+ // YAML parse that reads only the tree, script line positions, shell quoting analysis for variables
3
+ // that reach eval or inline code, and image tag checks.
4
+ import { isMap, isScalar, isSeq, LineCounter, parseAllDocuments, Scalar } from 'yaml';
5
+ // Parse errors that still leave a usable document tree.
6
+ const tolerableErrors = new Set(['DUPLICATE_KEY', 'KEY_OVER_1024_CHARS', 'TAG_RESOLVE_FAILED']);
7
+ // Every mapping document of the file; a GitLab `spec:` header is a separate document.
8
+ function parseCiDocuments(text) {
9
+ const lineCounter = new LineCounter();
10
+ // Read only the parse tree; aliases and custom tags such as `!reference` are not expanded.
11
+ const documents = parseAllDocuments(text, { lineCounter, prettyErrors: false });
12
+ if (!Array.isArray(documents))
13
+ return undefined;
14
+ if (documents.some((document) => document.errors.some(({ code }) => !tolerableErrors.has(code))))
15
+ return undefined;
16
+ const roots = documents.flatMap((document) => (isMap(document.contents) ? [document.contents] : []));
17
+ const findings = [];
18
+ function report(ruleId, offset, message) {
19
+ const { line, col } = lineCounter.linePos(offset);
20
+ findings.push({ ruleId, line, column: col, message });
21
+ }
22
+ return { roots, report, findings };
23
+ }
24
+ function sortFindings(findings) {
25
+ return findings.sort((first, second) => first.line - second.line || (first.column ?? 0) - (second.column ?? 0));
26
+ }
27
+ function isStringScalar(node) {
28
+ return isScalar(node) && typeof node.value === 'string';
29
+ }
30
+ function stringNode(node) {
31
+ return isStringScalar(node) && node.range ? node : undefined;
32
+ }
33
+ function mapNode(node) {
34
+ return isMap(node) ? node : undefined;
35
+ }
36
+ // The values of a mapping, such as the jobs under `jobs:`.
37
+ function mapValues(node) {
38
+ return isMap(node) ? node.items.map(({ value }) => value) : [];
39
+ }
40
+ // A script is one string or a list of strings; GitLab also allows one level of nested lists.
41
+ function scriptStrings(node) {
42
+ const single = stringNode(node);
43
+ if (single)
44
+ return [single];
45
+ if (!isSeq(node))
46
+ return [];
47
+ return node.items.flatMap((item) => (isSeq(item) ? item.items : [item])).flatMap((item) => stringNode(item) ?? []);
48
+ }
49
+ // Every mapping that is a list item, such as a step, without recursion so a deeply nested file
50
+ // cannot overflow the stack.
51
+ function listItemMaps(root) {
52
+ const maps = [];
53
+ const pending = [[root, false]];
54
+ for (let entry = pending.pop(); entry; entry = pending.pop()) {
55
+ const [node, isListItem] = entry;
56
+ if (isMap(node)) {
57
+ if (isListItem)
58
+ maps.push(node);
59
+ for (const { value } of node.items)
60
+ pending.push([value, false]);
61
+ }
62
+ else if (isSeq(node))
63
+ for (const item of node.items)
64
+ pending.push([item, true]);
65
+ }
66
+ return maps;
67
+ }
68
+ // A literal block keeps its lines verbatim in the source, so each one is found right after the last.
69
+ // Other scalar styles can fold or escape lines; their findings point at the scalar.
70
+ function scriptLines(node, text) {
71
+ const [start, end] = node.range ?? [0, 0];
72
+ const lines = node.value.split('\n');
73
+ if (node.type !== Scalar.BLOCK_LITERAL && lines.length > 1)
74
+ return lines.map((line) => ({ line, offset: start, placed: false }));
75
+ const source = text.slice(start, end);
76
+ let cursor = 0;
77
+ return lines.map((line) => {
78
+ const found = line ? source.indexOf(line, cursor) : -1;
79
+ if (found < 0)
80
+ return { line, offset: start, placed: false };
81
+ cursor = found + line.length;
82
+ return { line, offset: start + found, placed: true };
83
+ });
84
+ }
85
+ const unquoted = 0;
86
+ const singleQuoted = 1;
87
+ const doubleQuoted = 2;
88
+ // Escaped characters and the text of a command substitution, which neither the shell nor eval
89
+ // re-reads as part of the outer command.
90
+ const masked = 3;
91
+ // Masks the command substitution opening at start, through its closing `)` or backtick or the end
92
+ // of the line, and returns the index of its last character.
93
+ function maskSubstitution(line, states, start, substitutions) {
94
+ const backtick = line[start] === '`';
95
+ const inner = start + (backtick ? 1 : 2);
96
+ const close = line.indexOf(backtick ? '`' : ')', inner);
97
+ const end = close < 0 ? line.length : close;
98
+ states.fill(masked, start, end + 1);
99
+ substitutions?.push({ start: inner, end });
100
+ return end;
101
+ }
102
+ // Quoting state of each character; the inner text of each command substitution is pushed to
103
+ // substitutions when given.
104
+ function quoteStates(line, substitutions) {
105
+ const states = new Uint8Array(line.length);
106
+ let state = unquoted;
107
+ for (let index = 0; index < line.length; index++) {
108
+ const character = line[index];
109
+ if (state === singleQuoted) {
110
+ states[index] = singleQuoted;
111
+ if (character === "'")
112
+ state = unquoted;
113
+ }
114
+ else if (character === '\\') {
115
+ states[index] = masked;
116
+ if (index + 1 < line.length)
117
+ states[++index] = masked;
118
+ }
119
+ else if (character === '`' || (character === '$' && line[index + 1] === '(')) {
120
+ index = maskSubstitution(line, states, index, substitutions);
121
+ }
122
+ else if (state === doubleQuoted) {
123
+ states[index] = doubleQuoted;
124
+ if (character === '"')
125
+ state = unquoted;
126
+ }
127
+ else if (character === "'" || character === '"') {
128
+ state = character === "'" ? singleQuoted : doubleQuoted;
129
+ states[index] = state;
130
+ }
131
+ }
132
+ return states;
133
+ }
134
+ // `eval` re-parses all its arguments; `sh -c`, `python -c`, `node -e` and similar parse only the
135
+ // next argument as code, while later arguments are data.
136
+ const codeSink = new RegExp([
137
+ String.raw `(?<![\w.-])(?:(eval)(?=\s)`,
138
+ String.raw `((?:ba|da|k|z|a)?sh\s+-[abd-z]*c[a-z]*|python[\d.]*\s+-c|node(?:js)?\s+(?:-e|--eval|-p|--print)|ruby\s+-e|perl\s+-[a-df-z]*e|php\s+-r|(?:pwsh|powershell)(?:\.exe)?\s+-(?:command|c))(?=\s))`,
139
+ ].join('|'), 'gi');
140
+ const commandPosition = /(?:[;&|({]|\b(?:then|do|else|exec|sudo|time|command|builtin))\s*$/;
141
+ const commandEnd = new Set([';', '&', '|', ')']);
142
+ const wordEnd = new Set([' ', '\t', ';', '&', '|', '<', '>', '(', ')']);
143
+ const lookBehind = 32;
144
+ const printsArguments = /^\s*(?:echo|printf)(?=\s|$)/;
145
+ const quotingPrintf = /^\s*printf\s+(?:-v\b|["']?[^"'\s]*%q)/;
146
+ // The descriptor before `>`: 2> and other numbered streams leave standard output in place.
147
+ const otherStream = /[02-9]/;
148
+ function isUnquoted(states, index) {
149
+ return states[index] === unquoted;
150
+ }
151
+ // True when a substitution's command prints its arguments as they are to its output: echo or
152
+ // printf, but not `printf '%q'`, which quotes them as one word, `printf -v`, which assigns them,
153
+ // or a command that redirects its standard output elsewhere.
154
+ function printsTextOut(command, states) {
155
+ if (!printsArguments.test(command) || quotingPrintf.test(command))
156
+ return false;
157
+ for (let index = 0; index < command.length; index++) {
158
+ if (command[index] === '>' && isUnquoted(states, index) && !otherStream.test(command[index - 1] ?? ''))
159
+ return false;
160
+ }
161
+ return true;
162
+ }
163
+ // `eval` must start a command; inside an echo or a string it is just a word.
164
+ function startsCommand(line, index, firstWord) {
165
+ return index === firstWord || commandPosition.test(line.slice(Math.max(firstWord, index - lookBehind), index));
166
+ }
167
+ function endOfCommand(line, states, from) {
168
+ for (let index = from; index < line.length; index++) {
169
+ if (!isUnquoted(states, index))
170
+ continue;
171
+ if (commandEnd.has(line[index]) || (line[index] === '#' && /\s/.test(line[index - 1])))
172
+ return index;
173
+ }
174
+ return line.length;
175
+ }
176
+ function nextWord(line, states, from) {
177
+ let start = from;
178
+ while (start < line.length && /\s/.test(line[start]))
179
+ start++;
180
+ let end = start;
181
+ while (end < line.length && !(isUnquoted(states, end) && wordEnd.has(line[end])))
182
+ end++;
183
+ return [start, end];
184
+ }
185
+ // Untrusted variables in text whose quoting leaves them expanded, offset by the text's position.
186
+ function expandedVariables(text, offset, untrustedVariable, states = quoteStates(text)) {
187
+ return [...text.matchAll(untrustedVariable)].flatMap((variable) => {
188
+ const state = states[variable.index];
189
+ return state === unquoted || state === doubleQuoted ? [{ index: offset + variable.index, name: variable[1] }] : [];
190
+ });
191
+ }
192
+ // Untrusted variables the shell expands into text that eval or an interpreter then parses as code.
193
+ // A reference in single quotes or escaped with a backslash stays literal and is not reported.
194
+ function shellInjections(line, untrustedVariable) {
195
+ const substitutions = [];
196
+ const states = quoteStates(line, substitutions);
197
+ const firstWord = line.length - line.trimStart().length;
198
+ const injections = [];
199
+ const sinks = new RegExp(codeSink.source, codeSink.flags);
200
+ let nextSubstitution = 0;
201
+ for (let match = sinks.exec(line); match; match = sinks.exec(line)) {
202
+ if (!isUnquoted(states, match.index) || (match[1] && !startsCommand(line, match.index, firstWord)))
203
+ continue;
204
+ const afterSink = match.index + match[0].length;
205
+ const [start, end] = match[1]
206
+ ? [afterSink, endOfCommand(line, states, afterSink)]
207
+ : nextWord(line, states, afterSink);
208
+ const sink = match[0].replaceAll(/\s+/g, ' ');
209
+ const add = ({ index, name }) => injections.push({ index, variable: name, sink });
210
+ expandedVariables(line.slice(start, end), start, untrustedVariable, states.subarray(start, end)).forEach(add);
211
+ // `eval "$(printf '%s' "$VAR")"` hands the variable's text to eval through the substitution's
212
+ // output. Other commands print their own output, so only echo and printf are followed.
213
+ while (nextSubstitution < substitutions.length && substitutions[nextSubstitution].start < start)
214
+ nextSubstitution++;
215
+ for (; nextSubstitution < substitutions.length && substitutions[nextSubstitution].end <= end; nextSubstitution++) {
216
+ const { start: innerStart, end: innerEnd } = substitutions[nextSubstitution];
217
+ const inner = line.slice(innerStart, innerEnd);
218
+ const innerStates = quoteStates(inner);
219
+ if (printsTextOut(inner, innerStates))
220
+ expandedVariables(inner, innerStart, untrustedVariable, innerStates).forEach(add);
221
+ }
222
+ // Later sinks inside the same command are already covered, which keeps the scan linear.
223
+ sinks.lastIndex = Math.max(sinks.lastIndex, end);
224
+ }
225
+ return injections;
226
+ }
227
+ function shellInjectionMessage({ variable, sink }) {
228
+ return `\`$${variable}\` holds text the commit or branch author controls, and \`${sink}\` parses it as code, so the author can inject commands. Pass it as a separate argument or read it from the environment inside the script.`;
229
+ }
230
+ // Reports each untrusted variable that a script line hands to eval or inline code.
231
+ function reportShellInjections(scripts, text, untrustedVariable, ruleId, report) {
232
+ for (const script of scripts) {
233
+ for (const { line, offset, placed } of scriptLines(script, text)) {
234
+ for (const injection of shellInjections(line, untrustedVariable))
235
+ report(ruleId, placed ? offset + injection.index : offset, shellInjectionMessage(injection));
236
+ }
237
+ }
238
+ }
239
+ // "has no tag" or "uses the :latest tag" for a mutable image reference; undefined when it is
240
+ // pinned, built from a variable or names a digest.
241
+ function mutableImageProblem(image) {
242
+ if (!image || image.includes('$') || image.includes('@'))
243
+ return undefined;
244
+ const tag = image.slice(image.lastIndexOf('/') + 1).split(':')[1];
245
+ if (tag && tag.toLowerCase() !== 'latest')
246
+ return undefined;
247
+ return tag ? 'uses the :latest tag' : 'has no tag';
248
+ }
249
+ // An `image:` value is a string or a map with `name:`.
250
+ function imageNode(node) {
251
+ return stringNode(node) ?? (isMap(node) ? stringNode(node.get('name', true)) : undefined);
252
+ }
253
+ function reportMutableImage(node, ruleId, platform, report) {
254
+ const image = imageNode(node);
255
+ const problem = image && mutableImageProblem(image.value.trim());
256
+ if (!image?.range || !problem)
257
+ return;
258
+ report(ruleId, image.range[0], `${platform} image "${image.value.trim()}" ${problem}, so the job can run different code with this pipeline's secrets on a later run. Pin a version tag, or a digest for reproducible builds.`);
259
+ }
260
+ export { isUnquoted, listItemMaps, mapNode, mapValues, parseCiDocuments, printsArguments, quoteStates, reportMutableImage, reportShellInjections, scriptStrings, sortFindings, stringNode, };
@@ -0,0 +1,81 @@
1
+ // CircleCI checks for `.circleci/config.yml`: branch names and commit text that a `<< pipeline.* >>`
2
+ // value pastes into a run command or that the command hands to eval, orbs on a moving version, and
3
+ // Docker executor images without a version tag.
4
+ import { isSeq } from 'yaml';
5
+ import { normalizeSlashes } from '../../shared/system/posix-path.js';
6
+ import { mapNode, mapValues, parseCiDocuments, reportMutableImage, reportShellInjections, sortFindings, stringNode, } from './ci-shared.js';
7
+ const circleciPath = /(?:^|\/)\.circleci\/config\.ya?ml$/i;
8
+ // Pipeline values are replaced in the config text before the job starts, so they become code.
9
+ const untrustedPipelineValue = /<<\s*(pipeline\.(?:git\.(?:branch|commit\.(?:subject|body|author\.(?:name|email)))|trigger_parameters\.(?:github_app|gitlab)\.(?:branch|commit_message|commit_title|commit_author_name|commit_author_email)))\s*>>/g;
10
+ // The branch name reaches the shell as an environment variable; only a second parse makes it code.
11
+ const untrustedVariable = /\$\{?(CIRCLE_BRANCH)(?!\w)/g;
12
+ const firstPartyNamespace = 'circleci';
13
+ function isCircleciFile(file) {
14
+ return circleciPath.test(normalizeSlashes(file));
15
+ }
16
+ // Run commands of every job and reusable command, including steps nested under `when:` or `unless:`.
17
+ function runCommands(root) {
18
+ const pending = [...mapValues(root.get('jobs', true)), ...mapValues(root.get('commands', true))].map((owner) => mapNode(owner)?.get('steps', true));
19
+ const commands = [];
20
+ while (pending.length) {
21
+ const steps = pending.pop();
22
+ for (const item of isSeq(steps) ? steps.items : []) {
23
+ const step = mapNode(item);
24
+ if (!step)
25
+ continue;
26
+ const run = step.get('run', true);
27
+ const command = stringNode(run) ?? stringNode(mapNode(run)?.get('command', true));
28
+ if (command)
29
+ commands.push(command);
30
+ for (const condition of ['when', 'unless'])
31
+ pending.push(mapNode(step.get(condition, true))?.get('steps', true));
32
+ }
33
+ }
34
+ return commands;
35
+ }
36
+ function reportPipelineValues(command, text, report) {
37
+ if (!command.range)
38
+ return;
39
+ // Pipeline values sit on one source line, so the raw scalar text keeps their positions.
40
+ const [start, end] = command.range;
41
+ for (const match of text.slice(start, end).matchAll(untrustedPipelineValue)) {
42
+ report('circleci-script-injection', start + match.index, `\`${match[0]}\` pastes ${match[1]}, text the commit or branch author controls, into the command before it runs, so the author can inject commands. Set it under \`environment:\` and read the variable instead.`);
43
+ }
44
+ }
45
+ function reportOrbs(node, report) {
46
+ for (const value of mapValues(node)) {
47
+ const orb = stringNode(value);
48
+ if (!orb?.range)
49
+ continue;
50
+ const [name, version = ''] = orb.value.trim().split('@');
51
+ const namespace = name.split('/')[0].toLowerCase();
52
+ if (namespace === firstPartyNamespace || (version !== 'volatile' && !version.startsWith('dev:')))
53
+ continue;
54
+ report('circleci-unpinned-orb', orb.range[0], `Orb "${orb.value.trim()}" uses the moving version "${version}", so whoever publishes ${namespace} orbs can change the steps that run with this project's secrets. Pin a full released version such as @1.2.3.`);
55
+ }
56
+ }
57
+ function reportImages(root, report) {
58
+ for (const owner of [...mapValues(root.get('jobs', true)), ...mapValues(root.get('executors', true))]) {
59
+ const docker = mapNode(owner)?.get('docker', true);
60
+ for (const item of isSeq(docker) ? docker.items : [])
61
+ reportMutableImage(mapNode(item)?.get('image', true), 'circleci-unpinned-image', 'Docker executor', report);
62
+ }
63
+ }
64
+ function checkCircleci(file, text) {
65
+ if (!isCircleciFile(file))
66
+ return [];
67
+ const parsed = parseCiDocuments(text);
68
+ if (!parsed)
69
+ return [];
70
+ const { roots, report, findings } = parsed;
71
+ for (const root of roots) {
72
+ const commands = runCommands(root);
73
+ for (const command of commands)
74
+ reportPipelineValues(command, text, report);
75
+ reportShellInjections(commands, text, untrustedVariable, 'circleci-script-injection', report);
76
+ reportOrbs(root.get('orbs', true), report);
77
+ reportImages(root, report);
78
+ }
79
+ return sortFindings(findings);
80
+ }
81
+ export { checkCircleci, isCircleciFile };
@@ -1,5 +1,7 @@
1
1
  // Dockerfile checks. Instructions are read as logical lines, so a backslash continuation is one
2
2
  // instruction.
3
+ import { existsSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
3
5
  import { isSecretKey, isPlaceholderValue } from './secret-values.js';
4
6
  const dockerfileName = /^(?:.+\.)?Dockerfile(?:\..+)?$/i;
5
7
  const developmentName = /(?:^|[._-])(?:dev|development|test|ci|local|toolchain)(?:[._-]|$)/i;
@@ -67,6 +69,8 @@ function logicalInstructions(text) {
67
69
  if (delimiter) {
68
70
  if ((delimiter.stripTabs ? rawLine.replace(/^\t+/, '') : rawLine) === delimiter.name)
69
71
  nextDelimiter++;
72
+ else
73
+ instructions.at(-1)?.heredocLines?.push({ line: index + 1, text: rawLine.trim() });
70
74
  return;
71
75
  }
72
76
  const trimmed = rawLine.trim();
@@ -90,8 +94,10 @@ function logicalInstructions(text) {
90
94
  const match = /^(\w+)\s*(.*)$/.exec(pending.text);
91
95
  if (match) {
92
96
  const instruction = { line: pending.line, name: match[1].toUpperCase(), args: match[2] };
93
- instructions.push(instruction);
94
97
  delimiters = heredocDelimiters(instruction);
98
+ if (delimiters.length && instruction.name === 'RUN')
99
+ instruction.heredocLines = [];
100
+ instructions.push(instruction);
95
101
  nextDelimiter = 0;
96
102
  }
97
103
  pending = undefined;
@@ -228,13 +234,192 @@ function remoteAddFindings({ name, args, line }) {
228
234
  },
229
235
  ];
230
236
  }
231
- function checkDockerfile(file, text) {
237
+ // A COPY or bind mount that names the npm lockfile.
238
+ const lockfileSource = /(?:^|[\s/"=,[])(?:package-lock\.json|npm-shrinkwrap\.json)(?=[\s",\]]|$)/;
239
+ // The usual `package*.json` glob, which copies package-lock.json only when one exists (it never
240
+ // matches npm-shrinkwrap.json).
241
+ const lockfileGlob = /(?:^|[\s/"=,[])package\*(?:\.json)?(?=[\s",\]]|$)/;
242
+ // The npm install pattern runs on one simple command at a time (see `simpleCommands`), in which
243
+ // quoted text has become the placeholder word `_`, so it needs no separators or quotes.
244
+ // `NAME=value` before the command (`FOO="a b" npm install` reads as `FOO=_ npm install`).
245
+ const assignment = String.raw `[A-Za-z_]\w*=\S*\s+`;
246
+ // npm options before the subcommand, each with an optional value (`npm --prefix /app install`).
247
+ const globalOption = String.raw `\s+-\S+(?:\s+(?!(?:install|i)(?:\s|$))[^\s-]\S*)?`;
248
+ // Options after the subcommand whose value is a separate word (`--registry https://...`), which
249
+ // would otherwise look like a package name.
250
+ const valueOption = String.raw `\s+--(?:registry|omit|include|cache|prefix|userconfig|loglevel|install-strategy|workspace|tag|before)\s+[^\s-]\S*`;
251
+ // An output or input redirection (`> /dev/null`, `2>&1`, `&> log`).
252
+ const redirection = String.raw `\s+(?:&|\d*)[<>]{1,2}&?\s*[^\s<>]\S*`;
253
+ // `npm install` or `npm i` as the whole command, also after a shell keyword, a `!` negation or
254
+ // assignments, with only options and redirections after it: installing named packages
255
+ // (`npm install -g pnpm`) is a different operation that `npm ci` cannot replace. The group holds
256
+ // the npm command without the assignments before it.
257
+ const bareNpmInstall = new RegExp(String.raw `^\s*(?:(?:if|elif|while|until|then|do|else)\s+)?(?:!\s+)?(?:${assignment})*(npm(?:${globalOption})*\s+(?:install|i)(?:${valueOption}|${redirection}|\s+-\S+)*)\s*$`);
258
+ // Without a lockfile `npm ci` has nothing to install from, and a lockfile-only update installs
259
+ // nothing. The options may come before or after the subcommand, but not in an assignment value.
260
+ const ciCannotReplace = /(?:^|\s)(?:--no-package-lock|--package-lock=false|--package-lock-only)(?=\s|$)/;
261
+ // A shell and its script flag, possibly combined with others (`-c`, `-lc`, `-ec`).
262
+ const shellName = /^(?:\/(?:usr\/)?bin\/)?(?:ba|da|a|z)?sh$/;
263
+ const shellScriptFlag = /^-[A-Za-z]*c$/;
264
+ // A command whose next quoted word is a script that shell runs: `sh -c "..."`, `bash -lc '...'`.
265
+ const shellScriptCommand = /^\s*(?:(?:if|elif|while|until|then|do|else)\s+)?(?:[\w./-]*\/)?(?:ba|da|a|z)?sh\s+-[A-Za-z]*c\s*$/;
266
+ // Only a short command head is checked for `sh -c`, so a long command with many quoted words stays linear.
267
+ const commandHeadLimit = 64;
268
+ // `else npm install` after `[ -f package-lock.json ]`: the install only runs without a lockfile.
269
+ const lockfileTest = /(?:\[\[?|\btest)\s+-[ef]\s+(?:\S*\/)?package-lock\.json\b/;
270
+ const lockfileFallbackReason = 'The install runs only in the else branch of a package-lock.json test, as a fallback when the lockfile is missing.';
271
+ // A RUN whose only argument is a heredoc runs the heredoc body with the default shell.
272
+ const shellHeredocOnly = /^\d*<<-?\S+$/;
273
+ // A quoted string runs to the end of the text when it is never closed, so the pattern cannot
274
+ // fail on a stray quote and retry at every later position.
275
+ const quotedString = String.raw `'[^']*(?:'|$)|"(?:[^"\\]|\\(?:[\s\S]|$))*(?:"|$)`;
276
+ // Quoted strings and single characters, so a `#` inside quotes is not read as a comment.
277
+ const quotedOrCharacter = new RegExp(String.raw `${quotedString}|[\s\S]`, 'g');
278
+ // Quoted strings, command separators and single characters.
279
+ const shellPiece = new RegExp(String.raw `${quotedString}|[;&|()\n]|[\s\S]`, 'g');
280
+ const commandSeparator = /^[;&|()\n]$/;
281
+ // The command up to a `#` that starts a word outside quotes.
282
+ function withoutShellComment(command) {
283
+ let previous = '';
284
+ for (const { 0: part, index } of command.matchAll(quotedOrCharacter)) {
285
+ if (part === '#' && (!previous || /\s/.test(previous)))
286
+ return command.slice(0, index).trimEnd();
287
+ previous = part.at(-1) ?? '';
288
+ }
289
+ return command;
290
+ }
291
+ // The text of a quoted word without its quotes and escapes.
292
+ function unquoted(word) {
293
+ const closed = word.length > 1 && word.endsWith(word[0]);
294
+ const body = word.slice(1, closed ? -1 : undefined);
295
+ return word.startsWith('"') ? body.replaceAll(/\\([\s\S])/g, '$1') : body;
296
+ }
297
+ // The simple commands of a shell line, split at unquoted `;`, `&`, `|`, `(`, `)` and newlines.
298
+ // Quoted text becomes the placeholder word `_`, so `echo "cd app && npm install"` stays one echo,
299
+ // except the script of `sh -c "..."`, which that shell runs and is split the same way.
300
+ function simpleCommands(line, nested = false) {
301
+ const commands = [];
302
+ let current = '';
303
+ for (const { 0: piece, index } of line.matchAll(shellPiece)) {
304
+ // `2>&1` and `&> file` are redirections, not a background `&`.
305
+ const inRedirection = piece === '&' && (/[<>]/.test(current.at(-1) ?? '') || line[index + 1] === '>');
306
+ if (commandSeparator.test(piece) && !inRedirection) {
307
+ commands.push(current);
308
+ current = '';
309
+ }
310
+ else if (!/^['"]/.test(piece)) {
311
+ current += piece;
312
+ }
313
+ else if (!nested && current.length <= commandHeadLimit && shellScriptCommand.test(current)) {
314
+ commands.push(...simpleCommands(unquoted(piece), true));
315
+ current = '';
316
+ }
317
+ else {
318
+ current += '_';
319
+ }
320
+ }
321
+ commands.push(current);
322
+ return commands;
323
+ }
324
+ // Whether an install on this line is one `npm ci` could replace: `normal`, `fallback` when it only
325
+ // runs after a failed lockfile test, or undefined.
326
+ function npmInstallKind(line) {
327
+ let kind;
328
+ for (const command of simpleCommands(line)) {
329
+ const npmCommand = bareNpmInstall.exec(command)?.[1];
330
+ if (npmCommand === undefined || ciCannotReplace.test(npmCommand))
331
+ continue;
332
+ if (!/^\s*else\s/.test(command) || !lockfileTest.test(line))
333
+ return 'normal';
334
+ kind = 'fallback';
335
+ }
336
+ return kind;
337
+ }
338
+ // The RUN command without its flags or a trailing shell comment, with an exec-form array
339
+ // (`["npm", "install"]`) joined into words.
340
+ function runCommand(args) {
341
+ const command = args.replace(/^(?:--\S+\s+)*/, '');
342
+ if (!command.startsWith('['))
343
+ return withoutShellComment(command);
344
+ try {
345
+ const words = JSON.parse(command);
346
+ if (!Array.isArray(words) || !words.every((word) => typeof word === 'string'))
347
+ return command;
348
+ // A shell's `-c` script, with any later words as its positional arguments.
349
+ return words.length >= 3 && shellName.test(words[0]) && shellScriptFlag.test(words[1]) ? words[2] : words.join(' ');
350
+ }
351
+ catch {
352
+ return command;
353
+ }
354
+ }
355
+ // The shell commands a RUN executes, each with the line it is on.
356
+ function runCommands({ args, line, heredocLines }) {
357
+ const command = runCommand(args);
358
+ if (!heredocLines || !shellHeredocOnly.test(command))
359
+ return [{ line, command }];
360
+ // A body line ending in a backslash continues on the next one, as in the shell.
361
+ const commands = [];
362
+ let pending;
363
+ for (const body of heredocLines) {
364
+ const continued = body.text.endsWith('\\');
365
+ const part = continued ? body.text.slice(0, -1) : body.text;
366
+ pending = pending
367
+ ? { line: pending.line, command: `${pending.command} ${part}` }
368
+ : { line: body.line, command: part };
369
+ if (continued)
370
+ continue;
371
+ commands.push({ line: pending.line, command: withoutShellComment(pending.command) });
372
+ pending = undefined;
373
+ }
374
+ if (pending)
375
+ commands.push({ line: pending.line, command: withoutShellComment(pending.command) });
376
+ return commands;
377
+ }
378
+ // `inherited` is true when the stage builds FROM an earlier stage that already has the lockfile.
379
+ function npmInstallFindings(stage, lockfileBeside, inherited) {
380
+ const copiesLockfile = (args) => lockfileSource.test(args) || (lockfileBeside && lockfileGlob.test(args));
381
+ let lockfileCopied = inherited;
382
+ const findings = [];
383
+ for (const instruction of stage.instructions) {
384
+ const { name, args } = instruction;
385
+ if ((name === 'COPY' || name === 'ADD') && copiesLockfile(args))
386
+ lockfileCopied = true;
387
+ if (name !== 'RUN' || (!lockfileCopied && !copiesLockfile(args)))
388
+ continue;
389
+ for (const { line, command } of runCommands(instruction)) {
390
+ // One finding per command line when any install on it is one `npm ci` could replace.
391
+ const kind = npmInstallKind(command);
392
+ if (!kind)
393
+ continue;
394
+ findings.push({
395
+ ruleId: 'dockerfile-npm-install',
396
+ line,
397
+ message: 'RUN uses `npm install` although the stage has the lockfile. When package.json and the lockfile disagree, npm install resolves other versions and rewrites the lockfile instead of failing, and it is slower than `npm ci`. Use `npm ci`.',
398
+ ...(kind === 'fallback' && { contextualReason: lockfileFallbackReason }),
399
+ });
400
+ }
401
+ }
402
+ return { findings, hasLockfile: lockfileCopied };
403
+ }
404
+ // Only package-lock.json counts, because the `package*.json` glob does not copy npm-shrinkwrap.json.
405
+ function hasLockfileBeside(file) {
406
+ return existsSync(join(dirname(file), 'package-lock.json'));
407
+ }
408
+ function checkDockerfile(file, text, lockfileBeside = hasLockfileBeside(file)) {
232
409
  const instructions = logicalInstructions(text);
233
410
  const stages = parseStages(instructions);
234
411
  if (!stages.length)
235
412
  return [];
236
413
  const findings = [rootFinding(stages)];
237
414
  stages.forEach((stage, index) => findings.push(unpinnedFinding(stage, stages.slice(0, index))));
415
+ const stagesWithLockfile = new Set();
416
+ for (const stage of stages) {
417
+ const inherited = stagesWithLockfile.has(stage.image.toLowerCase());
418
+ const install = npmInstallFindings(stage, lockfileBeside, inherited);
419
+ findings.push(...install.findings);
420
+ if (install.hasLockfile && stage.alias)
421
+ stagesWithLockfile.add(stage.alias);
422
+ }
238
423
  for (const instruction of instructions) {
239
424
  findings.push(...secretBuildFindings(instruction), ...remoteAddFindings(instruction));
240
425
  }
@@ -261,4 +446,4 @@ function previousNumericUser(text, rootLine) {
261
446
  const maxId = 2 ** 32 - 2;
262
447
  return user.split(':').every((id) => Number(id) <= maxId) ? user : undefined;
263
448
  }
264
- export { checkDockerfile, isDockerfile, previousNumericUser };
449
+ export { checkDockerfile, hasLockfileBeside, isDockerfile, previousNumericUser };