@eagleoutice/flowr 2.10.5 → 2.10.6

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 (77) hide show
  1. package/README.md +20 -20
  2. package/abstract-interpretation/absint-visitor.d.ts +1 -2
  3. package/abstract-interpretation/domains/state-domain-like.d.ts +2 -2
  4. package/config.d.ts +6 -0
  5. package/config.js +2 -0
  6. package/control-flow/basic-cfg-guided-visitor.d.ts +1 -1
  7. package/control-flow/semantic-cfg-guided-visitor.js +3 -0
  8. package/dataflow/environments/built-in-proc-name.d.ts +7 -1
  9. package/dataflow/environments/built-in-proc-name.js +6 -0
  10. package/dataflow/environments/built-in.d.ts +6 -0
  11. package/dataflow/environments/built-in.js +6 -0
  12. package/dataflow/environments/default-builtin-config.d.ts +53 -1
  13. package/dataflow/environments/default-builtin-config.js +13 -3
  14. package/dataflow/environments/identifier.d.ts +14 -0
  15. package/dataflow/graph/vertex.d.ts +6 -0
  16. package/dataflow/internal/process/functions/call/built-in/built-in-access.js +16 -0
  17. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +6 -0
  18. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +99 -2
  19. package/dataflow/internal/process/functions/call/built-in/built-in-attach.d.ts +13 -0
  20. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +48 -0
  21. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +75 -0
  22. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +196 -0
  23. package/dataflow/internal/process/functions/call/built-in/built-in-get.d.ts +5 -0
  24. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +27 -13
  25. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +14 -4
  26. package/dataflow/internal/process/functions/call/built-in/built-in-new-env.d.ts +27 -0
  27. package/dataflow/internal/process/functions/call/built-in/built-in-new-env.js +97 -0
  28. package/dataflow/internal/process/functions/call/built-in/built-in-with.d.ts +23 -0
  29. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +90 -0
  30. package/documentation/doc-util/doc-types.d.ts +11 -2
  31. package/documentation/doc-util/doc-types.js +31 -9
  32. package/documentation/wiki-absint.d.ts +16 -0
  33. package/documentation/wiki-absint.js +50 -15
  34. package/documentation/wiki-interface.js +1 -0
  35. package/documentation/wiki-mk/doc-context.d.ts +14 -1
  36. package/documentation/wiki-mk/doc-context.js +6 -0
  37. package/documentation/wiki-normalized-ast.d.ts +0 -9
  38. package/documentation/wiki-normalized-ast.js +9 -60
  39. package/linter/linter-rules.d.ts +2 -1
  40. package/linter/rules/problematic-inputs.d.ts +9 -4
  41. package/linter/rules/problematic-inputs.js +108 -58
  42. package/package.json +1 -1
  43. package/queries/catalog/dependencies-query/function-info/read-functions.js +2 -0
  44. package/queries/catalog/dependencies-query/function-info/write-functions.js +1 -0
  45. package/queries/catalog/input-sources-query/input-source-functions.d.ts +1 -0
  46. package/queries/catalog/input-sources-query/input-source-functions.js +7 -1
  47. package/queries/catalog/input-sources-query/input-sources-query-format.js +3 -1
  48. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +3 -1
  49. package/queries/catalog/input-sources-query/simple-input-classifier.js +3 -1
  50. package/r-bridge/data/data.d.ts +28 -2
  51. package/r-bridge/data/data.js +34 -2
  52. package/r-bridge/lang-4.x/ast/model/model.d.ts +1 -2
  53. package/r-bridge/lang-4.x/ast/model/model.js +0 -1
  54. package/r-bridge/lang-4.x/ast/model/nodes/r-access.d.ts +3 -3
  55. package/r-bridge/lang-4.x/ast/model/nodes/r-argument.d.ts +3 -3
  56. package/r-bridge/lang-4.x/ast/model/nodes/r-binary-op.d.ts +3 -3
  57. package/r-bridge/lang-4.x/ast/model/nodes/r-break.d.ts +3 -3
  58. package/r-bridge/lang-4.x/ast/model/nodes/r-comment.d.ts +3 -3
  59. package/r-bridge/lang-4.x/ast/model/nodes/r-expression-list.d.ts +3 -3
  60. package/r-bridge/lang-4.x/ast/model/nodes/r-for-loop.d.ts +3 -3
  61. package/r-bridge/lang-4.x/ast/model/nodes/r-function-call.d.ts +3 -3
  62. package/r-bridge/lang-4.x/ast/model/nodes/r-function-definition.d.ts +3 -3
  63. package/r-bridge/lang-4.x/ast/model/nodes/r-if-then-else.d.ts +3 -3
  64. package/r-bridge/lang-4.x/ast/model/nodes/r-line-directive.d.ts +3 -3
  65. package/r-bridge/lang-4.x/ast/model/nodes/r-logical.d.ts +3 -3
  66. package/r-bridge/lang-4.x/ast/model/nodes/r-next.d.ts +3 -3
  67. package/r-bridge/lang-4.x/ast/model/nodes/r-number.d.ts +3 -3
  68. package/r-bridge/lang-4.x/ast/model/nodes/r-parameter.d.ts +3 -3
  69. package/r-bridge/lang-4.x/ast/model/nodes/r-pipe.d.ts +3 -3
  70. package/r-bridge/lang-4.x/ast/model/nodes/r-repeat-loop.d.ts +3 -3
  71. package/r-bridge/lang-4.x/ast/model/nodes/r-string.d.ts +3 -3
  72. package/r-bridge/lang-4.x/ast/model/nodes/r-symbol.d.ts +3 -3
  73. package/r-bridge/lang-4.x/ast/model/nodes/r-unary-op.d.ts +3 -3
  74. package/r-bridge/lang-4.x/ast/model/nodes/r-while-loop.d.ts +3 -3
  75. package/util/version.js +1 -1
  76. package/abstract-interpretation/normalized-ast-fold.d.ts +0 -119
  77. package/abstract-interpretation/normalized-ast-fold.js +0 -181
@@ -1,12 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WikiNormalizedAst = exports.MyMathFold = void 0;
3
+ exports.WikiNormalizedAst = void 0;
4
4
  const doc_code_1 = require("./doc-util/doc-code");
5
5
  const doc_normalized_ast_1 = require("./doc-util/doc-normalized-ast");
6
6
  const doc_files_1 = require("./doc-util/doc-files");
7
7
  const doc_cli_option_1 = require("./doc-util/doc-cli-option");
8
8
  const doc_structure_1 = require("./doc-util/doc-structure");
9
- const normalized_ast_fold_1 = require("../abstract-interpretation/normalized-ast-fold");
10
9
  const flowr_analyzer_1 = require("../project/flowr-analyzer");
11
10
  const flowr_analyzer_builder_1 = require("../project/flowr-analyzer-builder");
12
11
  const flowr_file_1 = require("../project/context/flowr-file");
@@ -16,6 +15,7 @@ const r_binary_op_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-binary-op"
16
15
  const model_1 = require("../r-bridge/lang-4.x/ast/model/model");
17
16
  const r_project_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-project");
18
17
  const r_expression_list_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
18
+ const stateful_fold_1 = require("../r-bridge/lang-4.x/ast/model/processing/stateful-fold");
19
19
  async function simpleNormalizedAst(code) {
20
20
  const analyzer = await new flowr_analyzer_builder_1.FlowrAnalyzerBuilder().build();
21
21
  analyzer.addRequest(code);
@@ -33,40 +33,6 @@ async function quickNormalizedAstMultipleFiles() {
33
33
  const n = await analyzer.normalize();
34
34
  return n;
35
35
  }
36
- class MyMathFold extends normalized_ast_fold_1.DefaultNormalizedAstFold {
37
- constructor() {
38
- /* use \`0\` as a placeholder empty for the monoid */
39
- super(0);
40
- }
41
- concat(a, b) {
42
- /* for this example, we ignore cases that we cannot handle */
43
- return b;
44
- }
45
- foldRNumber(node) {
46
- /* return the value of the number */
47
- return node.content.num;
48
- }
49
- foldRBinaryOp(node) {
50
- if (node.operator === '+') {
51
- return this.fold(node.lhs) + this.fold(node.rhs);
52
- }
53
- else if (node.operator === '*') {
54
- return this.fold(node.lhs) * this.fold(node.rhs);
55
- }
56
- else {
57
- /* in case we cannot handle the operator we could throw an error, or just use the default behavior: */
58
- return super.foldRBinaryOp(node);
59
- }
60
- }
61
- }
62
- exports.MyMathFold = MyMathFold;
63
- async function useMyMathFoldExample() {
64
- const analyzer = await new flowr_analyzer_builder_1.FlowrAnalyzerBuilder().build();
65
- analyzer.addRequest('1 + 3 * 2');
66
- const normalize = await analyzer.normalize();
67
- const result = new MyMathFold().fold(normalize.ast);
68
- return result;
69
- }
70
36
  /**
71
37
  * https://github.com/flowr-analysis/flowr/wiki/Normalized-AST
72
38
  */
@@ -134,7 +100,7 @@ ${(0, doc_structure_1.details)('Normalized AST Node Types', ctx.hierarchy(model_
134
100
  The following segments intend to give you an overview of how to work with the normalized AST:
135
101
 
136
102
  * [How to get a Normalized AST](#how-to-get-a-normalized-ast)
137
- * [Visitors and Folds](#visitors-and-folds)
103
+ * [Traversing the Normalized AST](#traversing-the-normalized-ast)
138
104
 
139
105
  > [!TIP]
140
106
  > If you want to get more information on roxygen comments attached to AST nodes,
@@ -169,8 +135,8 @@ ${(0, doc_normalized_ast_1.printNormalizedAst)((await quickNormalizedAstMultiple
169
135
 
170
136
  ## Traversing the Normalized AST
171
137
 
172
- We provide two ways to traverse the normalized AST: [Visitors](#visitors) and [Folds](#folds).
173
- Please note, that they usually operate on the ${ctx.link('RExpressionList')} level, and it is up to
138
+ We provide a visitor to traverse the normalized AST.
139
+ Please note, that it usually operates on the ${ctx.link('RExpressionList')} level, and it is up to
174
140
  you to decide how you want to traverse multiple files with a ${ctx.link('RProject')} in the AST (you can, for example, simplify flat-map over the files).
175
141
  The ${ctx.link('RProject')} node cannot appear nested within other nodes, so you can safely assume that any child of a node is not an ${ctx.link('RProject')}.
176
142
 
@@ -193,29 +159,12 @@ visitAst(nodes, node => {
193
159
  ids.add(node.info.id);
194
160
  });
195
161
  return ids;
196
- `)}
197
-
198
- ### Folds
199
-
200
- We formulate a fold with the base class ${ctx.link(normalized_ast_fold_1.DefaultNormalizedAstFold)} in ${(0, doc_files_1.getFilePathMd)('../abstract-interpretation/normalized-ast-fold.ts')}.
201
- Using this class, you can create your own fold behavior by overwriting the default methods.
202
- By default, the class provides a monoid abstraction using the _empty_ from the constructor and the _concat_ method.
203
-
204
-
205
- ${ctx.hierarchy(normalized_ast_fold_1.DefaultNormalizedAstFold)}
206
-
207
- Now, of course, we could provide hundreds of examples here, but we use tests to verify that the fold behaves as expected
208
- and happily point to them at ${(0, doc_files_1.getFilePathMd)('../../test/functionality/r-bridge/normalize-ast-fold.test.ts')}.
209
-
210
- As a simple showcase, we want to use the fold to evaluate numeric expressions containing numbers, \`+\`, and \`*\` operators.
211
-
212
- ${ctx.code(MyMathFold, { dropLinesStart: 1 })}
162
+ `)}
213
163
 
214
- Now, we can use the ${ctx.link(flowr_analyzer_1.FlowrAnalyzer)} (see the ${ctx.linkPage('wiki/Analyzer')} wiki page) to get the ${ctx.linkPage('wiki/Normalized AST', 'normalized AST')} and apply the fold:
215
-
216
- ${ctx.code(useMyMathFoldExample, { dropLinesStart: 1, dropLinesEnd: 2, hideDefinedAt: true })}
164
+ ### Stateful Fold
217
165
 
218
- Running the code, we retrieve the result: ${(0, doc_code_1.codeInline)(String(await useMyMathFoldExample()))}.
166
+ A stateful fold over the normalized AST can be performed with the ${ctx.link(stateful_fold_1.foldAstStateful)} function.
167
+ It allows you to specify a down function which is called during the down-pass and can pass information to child nodes, and fold functions which are called after the down-pass in conventional fold-fashion.
219
168
  `;
220
169
  }
221
170
  }
@@ -298,11 +298,12 @@ export declare const LintingRules: {
298
298
  };
299
299
  readonly info: {
300
300
  readonly name: "Problematic inputs";
301
- readonly description: "Detects uses of configured dynamic calls (e.g. eval, system) whose inputs are not statically constant. Prints the computed input-sources for the call and flags usages that depend on non-constant/trusted inputs.";
301
+ readonly description: "Detects uses of dynamic calls (e.g. eval, system) with non-constant inputs, and graphics-device calls (pdf, postscript) where a filename starts with '|' indicating a pipe command injection.";
302
302
  readonly tags: readonly [import("./linter-tags").LintingRuleTag.Security, import("./linter-tags").LintingRuleTag.Smell, import("./linter-tags").LintingRuleTag.Readability, import("./linter-tags").LintingRuleTag.Performance];
303
303
  readonly certainty: import("./linter-format").LintingRuleCertainty.BestEffort;
304
304
  readonly defaultConfig: {
305
305
  readonly consider: readonly ["^eval$", "^system$", "^system2$", "^shell$"];
306
+ readonly pipeCommandFunctions: readonly import("./rules/problematic-inputs").PipeCommandFunctionSpec[];
306
307
  };
307
308
  };
308
309
  };
@@ -3,17 +3,21 @@ import type { MergeableRecord } from '../../util/objects';
3
3
  import { SourceLocation } from '../../util/range';
4
4
  import { LintingRuleTag } from '../linter-tags';
5
5
  import type { InputClassifierConfig, InputSources } from '../../queries/catalog/input-sources-query/simple-input-classifier';
6
- /**
7
- * Describes a linting result for a problematic eval usage, including the location of the eval call and the computed input sources that lead to it.
8
- */
6
+ export interface PipeCommandFunctionSpec {
7
+ pattern: string;
8
+ argIdx: number;
9
+ argName: string;
10
+ }
9
11
  export interface ProblematicInputsResult extends LintingResult {
10
12
  name: string;
11
13
  loc: SourceLocation;
12
14
  sources: InputSources;
15
+ pipeCommand?: string;
13
16
  }
14
17
  export interface ProblematicInputsConfig extends MergeableRecord {
15
18
  consider?: string | string[];
16
19
  inputFns?: InputClassifierConfig;
20
+ pipeCommandFunctions?: PipeCommandFunctionSpec | PipeCommandFunctionSpec[];
17
21
  }
18
22
  export type ProblematicInputsMetadata = MergeableRecord;
19
23
  export declare const PROBLEMATIC_INPUTS: {
@@ -33,11 +37,12 @@ export declare const PROBLEMATIC_INPUTS: {
33
37
  };
34
38
  readonly info: {
35
39
  readonly name: "Problematic inputs";
36
- readonly description: "Detects uses of configured dynamic calls (e.g. eval, system) whose inputs are not statically constant. Prints the computed input-sources for the call and flags usages that depend on non-constant/trusted inputs.";
40
+ readonly description: "Detects uses of dynamic calls (e.g. eval, system) with non-constant inputs, and graphics-device calls (pdf, postscript) where a filename starts with '|' indicating a pipe command injection.";
37
41
  readonly tags: readonly [LintingRuleTag.Security, LintingRuleTag.Smell, LintingRuleTag.Readability, LintingRuleTag.Performance];
38
42
  readonly certainty: LintingRuleCertainty.BestEffort;
39
43
  readonly defaultConfig: {
40
44
  readonly consider: readonly ["^eval$", "^system$", "^system2$", "^shell$"];
45
+ readonly pipeCommandFunctions: readonly PipeCommandFunctionSpec[];
41
46
  };
42
47
  };
43
48
  };
@@ -7,103 +7,153 @@ const range_1 = require("../../util/range");
7
7
  const linter_tags_1 = require("../linter-tags");
8
8
  const simple_input_classifier_1 = require("../../queries/catalog/input-sources-query/simple-input-classifier");
9
9
  const parse_1 = require("../../slicing/criterion/parse");
10
+ const graph_1 = require("../../dataflow/graph/graph");
10
11
  const defaultConsider = ['^eval$', '^system$', '^system2$', '^shell$'];
11
- function normalizeConsider(cfg) {
12
- if (cfg?.consider === undefined) {
13
- return Array.from(defaultConsider, s => new RegExp(s));
12
+ const defaultPipeCommandFunctions = [
13
+ { pattern: '^pdf$', argIdx: 0, argName: 'file' },
14
+ { pattern: '^postscript$', argIdx: 0, argName: 'file' }
15
+ ];
16
+ function normalizePatternList(cfg, defaults) {
17
+ if (cfg === undefined) {
18
+ return Array.from(defaults, s => new RegExp(s));
14
19
  }
15
- if (Array.isArray(cfg.consider)) {
16
- const arr = cfg.consider.length === 0 ? Array.from(defaultConsider) : cfg.consider;
17
- // deduplicate while preserving order
20
+ if (Array.isArray(cfg)) {
21
+ const arr = cfg.length === 0 ? Array.from(defaults) : cfg;
18
22
  return Array.from(new Set(arr), s => new RegExp(s));
19
23
  }
20
- return [new RegExp(cfg.consider)];
24
+ return [new RegExp(cfg)];
25
+ }
26
+ function normalizePipeSpecs(cfg) {
27
+ const raw = cfg === undefined ? defaultPipeCommandFunctions
28
+ : Array.isArray(cfg) ? (cfg.length === 0 ? defaultPipeCommandFunctions : cfg)
29
+ : [cfg];
30
+ return raw.map(s => ({ pattern: new RegExp(s.pattern), argIdx: s.argIdx, argName: s.argName }));
21
31
  }
22
- /**
23
- * Format a list of input sources either as a single-line string (inline) or a block.
24
- * - inline: returns a semicolon-separated single-line summary
25
- * - block: returns an array of lines (to be joined with newlines by the caller)
26
- */
27
32
  function formatInputSources(inputs, inline = true) {
28
33
  if (!inputs || inputs.length === 0) {
29
34
  return inline ? '' : [];
30
35
  }
31
- const formatOne = (s, inlineMode) => {
32
- const typeStr = '[' + s.types.join(',') + ']';
33
- const cdsStr = s.cds ? ', cds: [' + s.cds.join(',') + ']' : '';
34
- return inlineMode
35
- ? `${s.id} (type: ${typeStr}, trace: ${s.trace}${cdsStr})`
36
- : `- ${s.id}: type=${typeStr}, trace=${s.trace}${cdsStr}`;
36
+ const fmt = (s) => {
37
+ const t = '[' + s.types.join(',') + ']';
38
+ const c = s.cds ? ', cds: [' + s.cds.join(',') + ']' : '';
39
+ return inline
40
+ ? `${s.id} (type: ${t}, trace: ${s.trace}${c})`
41
+ : `- ${s.id}: type=${t}, trace=${s.trace}${c}`;
37
42
  };
38
- if (inline) {
39
- return inputs.map(s => formatOne(s, true)).join('; ');
40
- }
41
- return inputs.map(s => formatOne(s, false));
43
+ return inline ? inputs.map(fmt).join('; ') : inputs.map(fmt);
42
44
  }
43
- // small helpers to keep checks readable
44
45
  function hasUnknownSource(sources) {
45
46
  return sources.some(s => s.types.includes(simple_input_classifier_1.InputType.Unknown));
46
47
  }
47
48
  function isProblematicForAllowed(sources, allowed) {
48
49
  return sources.some(s => s.types.some(t => !allowed.includes(t)));
49
50
  }
51
+ function getPipeCommandValue(sources) {
52
+ for (const s of sources) {
53
+ if (typeof s.value === 'string' && s.value.startsWith('|')) {
54
+ return s.value;
55
+ }
56
+ }
57
+ return undefined;
58
+ }
59
+ function resolveFileArgId(vertex, argIdx, argName) {
60
+ const args = vertex?.args;
61
+ if (!args) {
62
+ return undefined;
63
+ }
64
+ let idx = args.findIndex(a => graph_1.FunctionArgument.isNamed(a) && a.name === argName);
65
+ if (idx < 0) {
66
+ idx = argIdx;
67
+ }
68
+ if (idx >= args.length) {
69
+ return undefined;
70
+ }
71
+ const arg = args[idx];
72
+ return graph_1.FunctionArgument.isEmpty(arg) ? undefined : graph_1.FunctionArgument.getReference(arg);
73
+ }
74
+ function checkPipeInjection(nid, loc, name, sources) {
75
+ const pipeCmd = getPipeCommandValue(sources);
76
+ if (pipeCmd !== undefined) {
77
+ return { involvedId: nid, certainty: linter_format_1.LintingResultCertainty.Certain, loc, name, sources, pipeCommand: pipeCmd };
78
+ }
79
+ if (hasUnknownSource(sources)) {
80
+ return { involvedId: nid, certainty: linter_format_1.LintingResultCertainty.Uncertain, loc, name, sources };
81
+ }
82
+ return undefined;
83
+ }
50
84
  exports.PROBLEMATIC_INPUTS = {
51
85
  createSearch: config => {
52
- const considerArr = normalizeConsider(config);
53
- const queries = considerArr.map((name, i) => ({
54
- type: 'call-context',
55
- callName: name,
56
- callNameExact: false,
57
- subkind: `fn-${i}`
58
- }));
59
- return flowr_search_builder_1.Q.fromQuery(...queries);
86
+ const toQ = (name, subkind) => ({ type: 'call-context', callName: name, callNameExact: false, subkind });
87
+ return flowr_search_builder_1.Q.fromQuery(...normalizePatternList(config?.consider, defaultConsider).map((n, i) => toQ(n, `fn-${i}`)), ...normalizePipeSpecs(config?.pipeCommandFunctions).map((s, i) => toQ(s.pattern, `pipe-${i}`)));
60
88
  },
61
89
  processSearchResult: async (elements, config, data) => {
62
90
  const results = [];
91
+ const seen = new Set();
63
92
  const defaultAccept = [simple_input_classifier_1.InputType.Constant, simple_input_classifier_1.InputType.DerivedConstant];
93
+ const considerPats = normalizePatternList(config?.consider, defaultConsider);
94
+ const pipePats = normalizePipeSpecs(config?.pipeCommandFunctions);
64
95
  for (const element of elements.getElements()) {
65
96
  const nid = element.node.info.id;
66
- const criterion = parse_1.SlicingCriterion.fromId(nid);
67
- const q = { type: 'input-sources', criterion, config: config.inputFns };
68
- const all = await data.analyzer.query([q]);
69
- const inputSourcesResult = all['input-sources'];
70
- const sources = inputSourcesResult?.results?.[criterion] ?? [];
71
- if (isProblematicForAllowed(sources, defaultAccept)) {
72
- const certainty = hasUnknownSource(sources) ? linter_format_1.LintingResultCertainty.Uncertain : linter_format_1.LintingResultCertainty.Certain;
73
- results.push({
74
- involvedId: nid,
75
- certainty,
76
- loc: range_1.SourceLocation.fromNode(element.node) ?? range_1.SourceLocation.invalid(),
77
- name: element.node.lexeme ?? '',
78
- sources
79
- });
97
+ if (seen.has(nid)) {
98
+ continue;
99
+ }
100
+ const name = element.node.lexeme ?? '';
101
+ const pipeSpec = pipePats.find(s => s.pattern.test(name));
102
+ const isConsider = pipeSpec === undefined && considerPats.some(p => p.test(name));
103
+ if (pipeSpec === undefined && !isConsider) {
104
+ continue;
105
+ }
106
+ const loc = range_1.SourceLocation.fromNode(element.node) ?? range_1.SourceLocation.invalid();
107
+ if (pipeSpec !== undefined) {
108
+ const vertex = data.dataflow.graph.getVertex(nid);
109
+ const fileArgId = resolveFileArgId(vertex, pipeSpec.argIdx, pipeSpec.argName);
110
+ if (fileArgId !== undefined) {
111
+ const criterion = parse_1.SlicingCriterion.fromId(fileArgId);
112
+ const all = await data.analyzer.query([{ type: 'input-sources', criterion, config: config.inputFns }]);
113
+ const sources = all['input-sources']?.results?.[criterion] ?? [];
114
+ const r = checkPipeInjection(nid, loc, name, sources);
115
+ if (r !== undefined) {
116
+ seen.add(nid);
117
+ results.push(r);
118
+ }
119
+ }
120
+ }
121
+ else {
122
+ const criterion = parse_1.SlicingCriterion.fromId(nid);
123
+ const all = await data.analyzer.query([{ type: 'input-sources', criterion, config: config.inputFns }]);
124
+ const sources = all['input-sources']?.results?.[criterion] ?? [];
125
+ if (isProblematicForAllowed(sources, defaultAccept)) {
126
+ seen.add(nid);
127
+ results.push({ involvedId: nid, certainty: hasUnknownSource(sources) ? linter_format_1.LintingResultCertainty.Uncertain : linter_format_1.LintingResultCertainty.Certain, loc, name, sources });
128
+ }
80
129
  }
81
130
  }
82
- return {
83
- results,
84
- '.meta': {}
85
- };
131
+ return { results, '.meta': {} };
86
132
  },
87
- /* helper to format input sources for pretty printing */
88
133
  prettyPrint: {
89
134
  [linter_format_1.LintingPrettyPrintContext.Query]: result => {
90
- const inputs = result.sources ?? [];
91
- const srcStr = formatInputSources(inputs, true);
92
- return 'Use of configured dynamic call at ' + range_1.SourceLocation.format(result.loc) + (srcStr ? '; inputs: ' + srcStr : '');
135
+ if (result.pipeCommand !== undefined) {
136
+ return `Pipe command injection via '${result.pipeCommand}' in call to ${result.name} at ${range_1.SourceLocation.format(result.loc)}`;
137
+ }
138
+ const src = formatInputSources(result.sources ?? [], true);
139
+ return 'Use of configured dynamic call at ' + range_1.SourceLocation.format(result.loc) + (src ? '; inputs: ' + src : '');
93
140
  },
94
141
  [linter_format_1.LintingPrettyPrintContext.Full]: result => {
95
- const inputs = result.sources ?? [];
96
- const srcLines = formatInputSources(inputs, false);
97
- return 'Use of configured dynamic call at ' + range_1.SourceLocation.format(result.loc) + ' is potentially problematic' + (srcLines.length ? '\nInputs:\n' + srcLines.join('\n') : '');
142
+ const lines = formatInputSources(result.sources ?? [], false);
143
+ const tail = lines.length ? '\nInputs:\n' + lines.join('\n') : '';
144
+ return result.pipeCommand !== undefined
145
+ ? `Pipe command injection: '${result.pipeCommand}' passed as filename to ${result.name} at ${range_1.SourceLocation.format(result.loc)}${tail}`
146
+ : 'Use of configured dynamic call at ' + range_1.SourceLocation.format(result.loc) + ' is potentially problematic' + tail;
98
147
  }
99
148
  },
100
149
  info: {
101
150
  name: 'Problematic inputs',
102
- description: 'Detects uses of configured dynamic calls (e.g. eval, system) whose inputs are not statically constant. Prints the computed input-sources for the call and flags usages that depend on non-constant/trusted inputs.',
151
+ description: 'Detects uses of dynamic calls (e.g. eval, system) with non-constant inputs, and graphics-device calls (pdf, postscript) where a filename starts with \'|\' indicating a pipe command injection.',
103
152
  tags: [linter_tags_1.LintingRuleTag.Security, linter_tags_1.LintingRuleTag.Smell, linter_tags_1.LintingRuleTag.Readability, linter_tags_1.LintingRuleTag.Performance],
104
153
  certainty: linter_format_1.LintingRuleCertainty.BestEffort,
105
154
  defaultConfig: {
106
- consider: defaultConsider
155
+ consider: defaultConsider,
156
+ pipeCommandFunctions: defaultPipeCommandFunctions
107
157
  }
108
158
  }
109
159
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eagleoutice/flowr",
3
- "version": "2.10.5",
3
+ "version": "2.10.6",
4
4
  "description": "Static Dataflow Analyzer and Program Slicer for the R Programming Language",
5
5
  "types": "dist/src/index.d.ts",
6
6
  "repository": {
@@ -114,5 +114,7 @@ exports.ReadFunctions = [
114
114
  { package: 'openxlsx', name: 'loadWorkbook', argIdx: 0, argName: 'file', resolveValue: true },
115
115
  { package: 'readODS', name: 'read_ods', argIdx: 0, argName: 'path', resolveValue: true },
116
116
  { package: 'vroom', name: 'vroom', argIdx: 0, argName: 'file', resolveValue: true },
117
+ { package: 'compiler', name: 'loadcmp', argIdx: 0, argName: 'file', resolveValue: true },
118
+ { package: 'compiler', name: 'cmpfile', argIdx: 0, argName: 'infile', resolveValue: true }
117
119
  ];
118
120
  //# sourceMappingURL=read-functions.js.map
@@ -123,5 +123,6 @@ exports.WriteFunctions = [
123
123
  { package: 'rio', name: 'export', argIdx: 1, argName: 'file', resolveValue: true },
124
124
  { package: 'rio', name: 'export_list', argIdx: 1, argName: 'file', resolveValue: true },
125
125
  { package: 'magick', name: 'image_write', argIdx: 1, argName: 'path', resolveValue: true, ignoreIf: 'arg-missing' },
126
+ { package: 'compiler', name: 'cmpfile', argIdx: 1, argName: 'outfile', resolveValue: true }
126
127
  ];
127
128
  //# sourceMappingURL=write-functions.js.map
@@ -4,3 +4,4 @@ export declare const SystemFunctions: Identifier[];
4
4
  export declare const FfiFunctions: Identifier[];
5
5
  export declare const LangFunctions: Identifier[];
6
6
  export declare const OptionsFunctions: Identifier[];
7
+ export declare const UserFunctions: Identifier[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.OptionsFunctions = exports.LangFunctions = exports.FfiFunctions = exports.SystemFunctions = exports.PureFunctions = void 0;
3
+ exports.UserFunctions = exports.OptionsFunctions = exports.LangFunctions = exports.FfiFunctions = exports.SystemFunctions = exports.PureFunctions = void 0;
4
4
  exports.PureFunctions = [
5
5
  'paste', 'paste0', 'parse', '+', '-', '*',
6
6
  '/', '^', '%%', '%/%', '&', '|', '!', '&&', '||',
@@ -47,4 +47,10 @@ exports.LangFunctions = [
47
47
  'sym', 'syms', 'ensym', 'ensyms'
48
48
  ];
49
49
  exports.OptionsFunctions = ['options', 'getOption', 'Sys.getenv'];
50
+ exports.UserFunctions = [
51
+ 'readline', 'scan', 'askYesNo',
52
+ 'file.choose', 'choose.files', 'choose.dir', 'menu', 'select.list', 'winDialogString', 'winDialog',
53
+ 'showPrompt', 'askForPassword', 'selectDirectory', 'selectFile',
54
+ 'dlgInput', 'dlgOpen',
55
+ ];
50
56
  //# sourceMappingURL=input-source-functions.js.map
@@ -22,7 +22,8 @@ exports.DefaultInputClassifierConfig = {
22
22
  [simple_input_classifier_1.InputType.System]: input_source_functions_1.SystemFunctions,
23
23
  [simple_input_classifier_1.InputType.Ffi]: input_source_functions_1.FfiFunctions,
24
24
  [simple_input_classifier_1.InputType.Lang]: input_source_functions_1.LangFunctions,
25
- [simple_input_classifier_1.InputType.Options]: input_source_functions_1.OptionsFunctions
25
+ [simple_input_classifier_1.InputType.Options]: input_source_functions_1.OptionsFunctions,
26
+ [simple_input_classifier_1.InputType.User]: input_source_functions_1.UserFunctions
26
27
  };
27
28
  function inputSourcesQueryLineParser(output, line, _config) {
28
29
  const criterion = (0, slice_query_parser_1.sliceCriteriaParser)(line[0]);
@@ -65,6 +66,7 @@ exports.InputSourcesDefinition = {
65
66
  [simple_input_classifier_1.InputType.Ffi]: joi_1.default.array().items(joi_1.default.string()).optional().description('Functions that call native code via the R FFI (.C, .Call, .Fortran, .External, dyn.load).'),
66
67
  [simple_input_classifier_1.InputType.Lang]: joi_1.default.array().items(joi_1.default.string()).optional().description('Functions that produce language objects (e.g., substitute, quote, bquote, expression).'),
67
68
  [simple_input_classifier_1.InputType.Options]: joi_1.default.array().items(joi_1.default.string()).optional().description('Functions that access or set global options (e.g., options, getOption).'),
69
+ [simple_input_classifier_1.InputType.User]: joi_1.default.array().items(joi_1.default.string()).optional().description('Functions that read interactive user input (e.g., file.choose, readline, menu, askYesNo).'),
68
70
  }).optional()
69
71
  }).description('Input Sources query definition'),
70
72
  flattenInvolvedNodes: (queryResults) => {
@@ -11,7 +11,7 @@ import type { FlowrSearchLike } from '../../../search/flowr-search-builder';
11
11
  *```
12
12
  * [ Unknown ]
13
13
  * |
14
- * [Param] [File] [Net], ...
14
+ * [Param] [File] [Net] [User], ...
15
15
  * |
16
16
  * [ DerivedConstant ]
17
17
  * |
@@ -32,6 +32,8 @@ export declare enum InputType {
32
32
  Lang = "lang",
33
33
  /** Global options / option accessors (options, getOption) */
34
34
  Options = "options",
35
+ /** Interactive user input (file choosers, prompts, dialogs, menu selections) */
36
+ User = "user",
35
37
  Constant = "const",
36
38
  /** Read from environment/call scope */
37
39
  Scope = "scope",
@@ -310,7 +310,7 @@ class InputClassifier {
310
310
  *```
311
311
  * [ Unknown ]
312
312
  * |
313
- * [Param] [File] [Net], ...
313
+ * [Param] [File] [Net] [User], ...
314
314
  * |
315
315
  * [ DerivedConstant ]
316
316
  * |
@@ -332,6 +332,8 @@ var InputType;
332
332
  InputType["Lang"] = "lang";
333
333
  /** Global options / option accessors (options, getOption) */
334
334
  InputType["Options"] = "options";
335
+ /** Interactive user input (file choosers, prompts, dialogs, menu selections) */
336
+ InputType["User"] = "user";
335
337
  InputType["Constant"] = "const";
336
338
  /** Read from environment/call scope */
337
339
  InputType["Scope"] = "scope";
@@ -71,8 +71,34 @@ export declare const flowrCapabilities: {
71
71
  }, {
72
72
  readonly name: "Dynamic Environment Resolution";
73
73
  readonly id: "dynamic-environment-resolution";
74
- readonly supported: "not";
75
- readonly description: "_For example, using `new.env` and friends_";
74
+ readonly supported: "partially";
75
+ readonly description: "_For example, using `new.env` and friends. Supports `new.env`/`new.environment`/`rlang::new_environment`, `assign`/`get`/`local` with `envir=`, dollar-sign access (`e$x`), `attach`, `with`/`within`, and env-variable aliasing (`alias <- e`). Static parent-argument resolution (`parent = e`, `parent = emptyenv()`) is supported._";
76
+ readonly capabilities: readonly [{
77
+ readonly name: "Environment in Conditionals";
78
+ readonly id: "environment-in-conditionals";
79
+ readonly supported: "partially";
80
+ readonly description: "_Tracking environment assignments and reads across if-then-else branches. flowR propagates envState through branch merging, but cross-branch name resolution inside the env is not guaranteed._";
81
+ }, {
82
+ readonly name: "Environment in Loops";
83
+ readonly id: "environment-in-loops";
84
+ readonly supported: "partially";
85
+ readonly description: "_Tracking environment assignments inside loop constructs (for, while, repeat). The env variable is correctly attributed in each iteration body, but dynamic key generation (e.g., `paste0`) prevents static name resolution._";
86
+ }, {
87
+ readonly name: "Environment Parent";
88
+ readonly id: "environment-parent";
89
+ readonly supported: "partially";
90
+ readonly description: "_Specifying a parent for a newly-created environment (`new.env(parent = e)`, `new.env(parent = emptyenv())`). Tracked-env-variable parents and `emptyenv()`/`NULL` are resolved statically; dynamic or unknown parents fall back to the default (`parent.frame()`)._";
91
+ }, {
92
+ readonly name: "Environment Alias";
93
+ readonly id: "environment-alias";
94
+ readonly supported: "partially";
95
+ readonly description: "_Aliasing a tracked environment variable (`alias <- e`). The `envState` snapshot at assignment time is propagated, so assigns made BEFORE the alias are visible through it. Assigns made AFTER the alias to the original variable are not reflected._";
96
+ }, {
97
+ readonly name: "With / Within";
98
+ readonly id: "environment-with";
99
+ readonly supported: "partially";
100
+ readonly description: "_Evaluating an expression inside a named environment with `with(data, expr)` or `within(data, expr)`. When `data` is a tracked env variable, reads of names defined in that env resolve correctly. Writes inside `expr` are ephemeral (not persisted back to the env)._";
101
+ }];
76
102
  }, {
77
103
  readonly name: "Environment Sharing";
78
104
  readonly id: "environment-sharing";
@@ -104,8 +104,40 @@ ${await (0, doc_dfg_1.printDfGraphForCode)(parser, code, { simplified: true })}
104
104
  {
105
105
  name: 'Dynamic Environment Resolution',
106
106
  id: 'dynamic-environment-resolution',
107
- supported: 'not',
108
- description: '_For example, using `new.env` and friends_'
107
+ supported: 'partially',
108
+ description: '_For example, using `new.env` and friends. Supports `new.env`/`new.environment`/`rlang::new_environment`, `assign`/`get`/`local` with `envir=`, dollar-sign access (`e$x`), `attach`, `with`/`within`, and env-variable aliasing (`alias <- e`). Static parent-argument resolution (`parent = e`, `parent = emptyenv()`) is supported._',
109
+ capabilities: [
110
+ {
111
+ name: 'Environment in Conditionals',
112
+ id: 'environment-in-conditionals',
113
+ supported: 'partially',
114
+ description: '_Tracking environment assignments and reads across if-then-else branches. flowR propagates envState through branch merging, but cross-branch name resolution inside the env is not guaranteed._'
115
+ },
116
+ {
117
+ name: 'Environment in Loops',
118
+ id: 'environment-in-loops',
119
+ supported: 'partially',
120
+ description: '_Tracking environment assignments inside loop constructs (for, while, repeat). The env variable is correctly attributed in each iteration body, but dynamic key generation (e.g., `paste0`) prevents static name resolution._'
121
+ },
122
+ {
123
+ name: 'Environment Parent',
124
+ id: 'environment-parent',
125
+ supported: 'partially',
126
+ description: '_Specifying a parent for a newly-created environment (`new.env(parent = e)`, `new.env(parent = emptyenv())`). Tracked-env-variable parents and `emptyenv()`/`NULL` are resolved statically; dynamic or unknown parents fall back to the default (`parent.frame()`)._'
127
+ },
128
+ {
129
+ name: 'Environment Alias',
130
+ id: 'environment-alias',
131
+ supported: 'partially',
132
+ description: '_Aliasing a tracked environment variable (`alias <- e`). The `envState` snapshot at assignment time is propagated, so assigns made BEFORE the alias are visible through it. Assigns made AFTER the alias to the original variable are not reflected._'
133
+ },
134
+ {
135
+ name: 'With / Within',
136
+ id: 'environment-with',
137
+ supported: 'partially',
138
+ description: '_Evaluating an expression inside a named environment with `with(data, expr)` or `within(data, expr)`. When `data` is a tracked env variable, reads of names defined in that env resolve correctly. Writes inside `expr` are ephemeral (not persisted back to the env)._'
139
+ }
140
+ ]
109
141
  },
110
142
  {
111
143
  name: 'Environment Sharing',
@@ -27,8 +27,8 @@ import type { RDelimiter } from './nodes/info/r-delimiter';
27
27
  import type { AstIdMap, ParentInformation } from './processing/decorate';
28
28
  import type { NodeId } from './processing/node-id';
29
29
  import type { OnEnter, OnExit } from './processing/visitor';
30
- import type { SingleOrArrayOrNothing } from '../../../../abstract-interpretation/normalized-ast-fold';
31
30
  import { getDocumentationOf } from '../../../roxygen2/documentation-provider';
31
+ export type SingleOrArrayOrNothing<T> = T | readonly (T | null | undefined)[] | null | undefined;
32
32
  /** Simply an empty type constraint used to say that there are additional decorations (see {@link RAstNodeBase}). */
33
33
  export type NoInfo = object;
34
34
  /**
@@ -222,7 +222,6 @@ export type RNode<Info = NoInfo> = RExpressionList<Info> | RFunctions<Info> | RO
222
222
  * For the individual type checks, please consult the individual vertices, e.g. {@link RPipe.is}.
223
223
  * Some vertices also have a {@link RPipe.availableFromRVersion} property that indicates from which R version they are available,
224
224
  * so you can check for that as well if needed.
225
- * @see {@link DefaultNormalizedAstFold} - for a more powerful way to traverse the normalized AST
226
225
  */
227
226
  export declare const RNode: {
228
227
  readonly name: "RNode";
@@ -123,7 +123,6 @@ exports.ROther = {
123
123
  * For the individual type checks, please consult the individual vertices, e.g. {@link RPipe.is}.
124
124
  * Some vertices also have a {@link RPipe.availableFromRVersion} property that indicates from which R version they are available,
125
125
  * so you can check for that as well if needed.
126
- * @see {@link DefaultNormalizedAstFold} - for a more powerful way to traverse the normalized AST
127
126
  */
128
127
  exports.RNode = {
129
128
  name: 'RNode',
@@ -46,13 +46,13 @@ export declare const RAccess: {
46
46
  readonly getLocation: (this: void, node: RNode) => import("../../../../../util/range").SourceLocation | undefined;
47
47
  readonly getId: (this: void, node: RNode<import("../processing/decorate").ParentInformation>) => import("../processing/node-id").NodeId;
48
48
  readonly getType: (this: void, node: RNode) => RType;
49
- readonly visitAst: <OtherInfo = object>(this: void, nodes: import("../../../../../abstract-interpretation/normalized-ast-fold").SingleOrArrayOrNothing<RNode<OtherInfo>>, onVisit?: import("../processing/visitor").OnEnter<OtherInfo>, onExit?: import("../processing/visitor").OnExit<OtherInfo>) => void;
50
- readonly collectAllIds: <OtherInfo>(this: void, nodes: import("../../../../../abstract-interpretation/normalized-ast-fold").SingleOrArrayOrNothing<RNode<OtherInfo & import("../processing/decorate").ParentInformation>>) => Set<import("../processing/node-id").NodeId>;
49
+ readonly visitAst: <OtherInfo = object>(this: void, nodes: import("../model").SingleOrArrayOrNothing<RNode<OtherInfo>>, onVisit?: import("../processing/visitor").OnEnter<OtherInfo>, onExit?: import("../processing/visitor").OnExit<OtherInfo>) => void;
50
+ readonly collectAllIds: <OtherInfo>(this: void, nodes: import("../model").SingleOrArrayOrNothing<RNode<OtherInfo & import("../processing/decorate").ParentInformation>>) => Set<import("../processing/node-id").NodeId>;
51
51
  readonly directChildren: <OtherInfo>(this: void, node: RNode<OtherInfo>) => readonly (RNode<OtherInfo> | typeof EmptyArgument)[];
52
52
  readonly directParent: <OtherInfo>(this: void, node: RNode<OtherInfo & import("../processing/decorate").ParentInformation>, idMap: import("../processing/decorate").AstIdMap<OtherInfo & import("../processing/decorate").ParentInformation>) => RNode<OtherInfo & import("../processing/decorate").ParentInformation> | undefined;
53
53
  readonly iterateParents: <OtherInfo>(this: void, node: RNode<OtherInfo & import("../processing/decorate").ParentInformation> | undefined, idMap: import("../processing/decorate").AstIdMap<OtherInfo & import("../processing/decorate").ParentInformation>) => Generator<RNode<OtherInfo & import("../processing/decorate").ParentInformation>>;
54
54
  readonly depth: (this: void, node: RNode<import("../processing/decorate").ParentInformation>, idMap: import("../processing/decorate").AstIdMap<import("../processing/decorate").ParentInformation>) => number;
55
- readonly collectAllIdsWithStop: <OtherInfo>(this: void, nodes: import("../../../../../abstract-interpretation/normalized-ast-fold").SingleOrArrayOrNothing<RNode<OtherInfo & import("../processing/decorate").ParentInformation>>, stop: (node: RNode<OtherInfo & import("../processing/decorate").ParentInformation>) => boolean) => Set<import("../processing/node-id").NodeId>;
55
+ readonly collectAllIdsWithStop: <OtherInfo>(this: void, nodes: import("../model").SingleOrArrayOrNothing<RNode<OtherInfo & import("../processing/decorate").ParentInformation>>, stop: (node: RNode<OtherInfo & import("../processing/decorate").ParentInformation>) => boolean) => Set<import("../processing/node-id").NodeId>;
56
56
  readonly lexeme: <R extends RNode<import("../processing/decorate").ParentInformation>>(this: void, node: R | undefined) => R extends {
57
57
  lexeme: string;
58
58
  } ? string : string | undefined;