@eagleoutice/flowr 2.16.0 → 2.16.2

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 (80) hide show
  1. package/README.md +9 -9
  2. package/cli/flowr-main-options.d.ts +15 -0
  3. package/cli/flowr-main-options.js +18 -0
  4. package/cli/flowr.d.ts +18 -0
  5. package/cli/flowr.js +13 -2
  6. package/cli/repl/commands/repl-clipboard.js +2 -1
  7. package/cli/repl/commands/repl-commands.js +2 -0
  8. package/cli/repl/commands/repl-main.d.ts +5 -0
  9. package/cli/repl/commands/repl-signature.js +2 -0
  10. package/cli/repl/core.d.ts +7 -1
  11. package/cli/repl/core.js +17 -8
  12. package/cli/repl/execute.js +2 -0
  13. package/cli/repl/server/connection.js +2 -1
  14. package/cli/repl/server/net.d.ts +10 -0
  15. package/cli/repl/server/net.js +34 -1
  16. package/cli/slicer-app.js +2 -1
  17. package/config.d.ts +12 -2
  18. package/config.js +91 -14
  19. package/dataflow/environments/built-in-props.d.ts +5 -2
  20. package/dataflow/environments/built-in-props.js +6 -3
  21. package/dataflow/environments/default-builtin-config.d.ts +197 -11
  22. package/dataflow/environments/default-builtin-config.js +62 -42
  23. package/dataflow/environments/identifier.d.ts +1 -0
  24. package/dataflow/environments/query-fn-props.d.ts +3 -0
  25. package/dataflow/environments/query-fn-props.js +8 -0
  26. package/dataflow/environments/resolve-by-name.js +11 -4
  27. package/dataflow/eval/resolve/resolve-argument.js +5 -1
  28. package/dataflow/extractor.js +14 -5
  29. package/dataflow/fn/frame-reflection.js +14 -2
  30. package/dataflow/graph/graph.js +12 -0
  31. package/dataflow/internal/control-flow.d.ts +11 -0
  32. package/dataflow/internal/control-flow.js +15 -0
  33. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +4 -10
  34. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +1 -1
  35. package/dataflow/internal/process/functions/call/built-in/built-in-purrr-formula.js +9 -0
  36. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +8 -7
  37. package/dataflow/internal/process/functions/call/deferred.js +6 -1
  38. package/dataflow/internal/process/functions/call/named-call-handling.js +70 -9
  39. package/documentation/doc-capabilities.js +4 -1
  40. package/documentation/wiki-interface.js +4 -0
  41. package/engines.js +11 -3
  42. package/linter/linter-executor.js +19 -1
  43. package/linter/linter-rules.d.ts +8 -3
  44. package/linter/rules/file-path-validity.js +4 -1
  45. package/linter/rules/function-finder-util.d.ts +1 -1
  46. package/linter/rules/function-finder-util.js +1 -3
  47. package/linter/rules/network-functions.d.ts +4 -3
  48. package/linter/rules/network-functions.js +14 -12
  49. package/linter/rules/no-leaked-credentials.d.ts +8 -3
  50. package/linter/rules/no-leaked-credentials.js +133 -35
  51. package/linter/rules/problematic-inputs.d.ts +1 -1
  52. package/linter/rules/problematic-inputs.js +20 -14
  53. package/linter/rules/seeded-randomness.js +3 -1
  54. package/linter/rules/unescaped-arguments.d.ts +13 -2
  55. package/linter/rules/unescaped-arguments.js +100 -12
  56. package/package.json +1 -1
  57. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +14 -5
  58. package/project/plugins/file-plugins/files/flowr-rda-file.js +35 -24
  59. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +2 -1
  60. package/project/sigdb/decompress.js +3 -1
  61. package/project/sigdb/sigdb-download.js +9 -6
  62. package/queries/catalog/call-context-query/call-context-query-executor.js +2 -1
  63. package/queries/catalog/config-query/config-query-executor.js +9 -2
  64. package/queries/catalog/input-sources-query/input-source-functions.d.ts +6 -4
  65. package/queries/catalog/input-sources-query/input-source-functions.js +11 -6
  66. package/queries/catalog/input-sources-query/input-sources-query-executor.js +1 -1
  67. package/queries/catalog/input-sources-query/input-sources-query-format.d.ts +1 -1
  68. package/queries/catalog/input-sources-query/input-sources-query-format.js +9 -2
  69. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +12 -4
  70. package/queries/catalog/input-sources-query/simple-input-classifier.js +227 -29
  71. package/r-bridge/shell-executor.js +2 -0
  72. package/r-bridge/shell.js +2 -0
  73. package/search/search-executor/search-enrichers.js +5 -3
  74. package/slicing/static/static-slicer.js +14 -9
  75. package/util/files.d.ts +6 -0
  76. package/util/files.js +12 -0
  77. package/util/parallel.js +2 -0
  78. package/util/secure-mode.d.ts +42 -0
  79. package/util/secure-mode.js +70 -0
  80. package/util/version.js +2 -2
@@ -405,6 +405,9 @@ class DataflowGraph {
405
405
  const vid = vertex.id;
406
406
  const previous = this.vertexInformation.get(vid);
407
407
  if (previous !== undefined && !overwrite) {
408
+ if (vertex_2.DfgVertex.isFunctionCall(previous) && vertex_2.DfgVertex.isFunctionCall(vertex)) {
409
+ mergeOrigins(previous, vertex);
410
+ }
408
411
  return this;
409
412
  }
410
413
  this.dropQualifications();
@@ -649,8 +652,17 @@ function mergeNodeInfos(current, next) {
649
652
  }
650
653
  }
651
654
  }
655
+ else if (vertex_2.DfgVertex.isFunctionCall(current) && vertex_2.DfgVertex.isFunctionCall(next)) {
656
+ mergeOrigins(current, next);
657
+ }
652
658
  return current;
653
659
  }
660
+ /** a call resolving to several callees is processed once per callee, each adding its origin */
661
+ function mergeOrigins(current, next) {
662
+ if (Array.isArray(current.origin) && Array.isArray(next.origin)) {
663
+ current.origin = (0, arrays_1.uniqueArrayMerge)(current.origin, next.origin);
664
+ }
665
+ }
654
666
  function envFromJson(json) {
655
667
  const parent = json.parent ? envFromJson(json.parent) : undefined;
656
668
  const env = new environment_1.Environment(parent, json.builtInEnv);
@@ -100,6 +100,17 @@ export declare const ControlFlow: {
100
100
  readonly withinPromise: <Data extends {
101
101
  readonly cds?: readonly ControlDependency[];
102
102
  }>(this: void, data: Data, holder: NodeId) => Data;
103
+ /**
104
+ * A function defined within a promise: forcing the promise only creates it, its body runs once it is called,
105
+ * so neither the definition nor its body depend on the call holding the promise.
106
+ * @example
107
+ * ```r
108
+ * f(function() print(1)) # the print runs when `f` calls its argument, which `f(...)` itself does not decide
109
+ * ```
110
+ */
111
+ readonly outsidePromises: <Data extends {
112
+ readonly cds?: readonly ControlDependency[];
113
+ }>(this: void, data: Data) => Data;
103
114
  /**
104
115
  * The jumps within a promise, an argument or default R evaluates only if `holder` forces it. A jump
105
116
  * - never runs if the promise is {@link Ternary#Never|never} forced, so control resumes at `holder`,
@@ -153,6 +153,21 @@ exports.ControlFlow = {
153
153
  withinPromise(data, holder) {
154
154
  return { ...data, cds: (0, info_1.withCds)(data.cds, [{ id: holder, when: true, byPromise: true }]) };
155
155
  },
156
+ /**
157
+ * A function defined within a promise: forcing the promise only creates it, its body runs once it is called,
158
+ * so neither the definition nor its body depend on the call holding the promise.
159
+ * @example
160
+ * ```r
161
+ * f(function() print(1)) # the print runs when `f` calls its argument, which `f(...)` itself does not decide
162
+ * ```
163
+ */
164
+ outsidePromises(data) {
165
+ if (!data.cds?.some(cd => cd.byPromise)) {
166
+ return data;
167
+ }
168
+ const kept = data.cds.filter(cd => !cd.byPromise);
169
+ return { ...data, cds: kept.length > 0 ? kept : undefined };
170
+ },
156
171
  /**
157
172
  * The jumps within a promise, an argument or default R evaluates only if `holder` forces it. A jump
158
173
  * - never runs if the promise is {@link Ternary#Never|never} forced, so control resumes at `holder`,
@@ -103,7 +103,7 @@ const Accumulating = new Set([
103
103
  ...DeviceStates, exports.AmbientStateName.palette, exports.AmbientStateName.allOptions, exports.AmbientStateName.unknownOption,
104
104
  exports.AmbientStateName.warnsAsErrors, exports.AmbientStateName.files, exports.AmbientStateName.rngKind, exports.AmbientStateName.finalizers
105
105
  ]);
106
- /** a write that keeps what was there, as the call may not happen to write */
106
+ /** a write that may not happen: it reads what was there, so it can still replace the state and keep everything before reachable */
107
107
  function maybe(name) {
108
108
  return { name, mode: 'maybe' };
109
109
  }
@@ -129,7 +129,8 @@ function withAccess(res, rootId, data, reads, writes = []) {
129
129
  return res;
130
130
  }
131
131
  const cds = data.cds ? [...data.cds] : undefined;
132
- const readRefs = reads.map(name => ({ nodeId: rootId, name, type: identifier_1.ReferenceType.Variable, cds }));
132
+ const maybeWritten = writes.flatMap(w => typeof w === 'object' && w.mode === 'maybe' ? [w.name] : []);
133
+ const readRefs = [...new Set([...reads, ...maybeWritten])].map(name => ({ nodeId: rootId, name, type: identifier_1.ReferenceType.Variable, cds }));
133
134
  /* the writes stay out of `out`: an assignment reads whatever else its source writes (`x <- y <- 3`) */
134
135
  return {
135
136
  ...res,
@@ -142,7 +143,7 @@ function defineAmbient(environment, rootId, cds, writes) {
142
143
  for (const write of writes) {
143
144
  const { name, mode } = typeof write === 'string' ? { name: write, mode: undefined } : write;
144
145
  const accumulates = Accumulating.has(name) || name.startsWith(exports.AmbientStateName.file(''));
145
- const keep = mode === 'maybe' || (accumulates && mode === undefined);
146
+ const keep = accumulates && (mode === undefined || mode === 'maybe');
146
147
  /* an accumulating state only ever grows, its definitions are maybe so merging environments keeps them all; a reset is definite */
147
148
  const isMaybe = keep || (accumulates && mode !== 'reset');
148
149
  const def = {
@@ -152,13 +153,6 @@ function defineAmbient(environment, rootId, cds, writes) {
152
153
  definedAt: rootId,
153
154
  cds: isMaybe ? cds ?? [] : cds
154
155
  };
155
- if (mode === 'maybe') {
156
- /* a call that may write reads what was there, so the maybe-writes before it stay reachable through it alone */
157
- def.maybeWrite = true;
158
- const kept = (resolve_helper_1.Resolve.byName(name, environment) ?? []).filter(d => !d.maybeWrite);
159
- environment = setAmbient(environment, name, [...kept, def]);
160
- continue;
161
- }
162
156
  /* the state is global, wherever the call happens, unless the call scopes it to the current frame */
163
157
  environment = (0, define_1.define)(def, mode !== 'local', environment, keep);
164
158
  }
@@ -59,7 +59,7 @@ function processFunctionDefinition(name, args, rootId, data) {
59
59
  const originalEnvironment = data.environment;
60
60
  const idMap = data.completeAst.idMap;
61
61
  // within a function def we do not pass on the outer binds as they could be overwritten when called
62
- data = prepareFunctionEnvironment(data, rootId);
62
+ data = prepareFunctionEnvironment(control_flow_1.ControlFlow.outsidePromises(data), rootId);
63
63
  const subgraph = new graph_1.DataflowGraph(idMap);
64
64
  let readInParameters = [];
65
65
  const allParameterReads = [];
@@ -18,6 +18,7 @@ const logger_1 = require("../../../../../logger");
18
18
  const graph_1 = require("../../../../../graph/graph");
19
19
  const vertex_1 = require("../../../../../graph/vertex");
20
20
  const resolve_helper_1 = require("../../../../../environments/resolve-helper");
21
+ const assert_1 = require("../../../../../../util/assert");
21
22
  function linkOnSymbol(rootId, filteredArgs, node, graph, data) {
22
23
  // If the formula is a symbol naming a function, try to resolve it in the call environment.
23
24
  try {
@@ -100,6 +101,14 @@ function processPurrrFormula(name, args, rootId, data, config) {
100
101
  }
101
102
  else if (r_symbol_1.RSymbol.is(formulaNode)) {
102
103
  linkOnSymbol(rootId, filteredCallArgs, formulaNode, information.graph, data);
104
+ /* like `lapply`, a named function handed over is called with the remaining arguments */
105
+ if (resolve_helper_1.Resolve.byNameAndType(formulaNode.content, data.environment, identifier_1.ReferenceType.Function)?.length) {
106
+ const id = formulaNode.info.id;
107
+ information.graph.updateToFunctionCall({ tag: vertex_1.VertexType.FunctionCall, id, name: formulaNode.content, args: filteredCallArgs, environment: data.environment, onlyBuiltin: false, cds: data.cds, origin: [built_in_proc_name_1.BuiltInProcName.Function] });
108
+ for (const arg of filteredCallArgs.map(graph_1.FunctionArgument.getId).filter(assert_1.isNotUndefined)) {
109
+ information.graph.addEdge(id, arg, edge_1.EdgeType.Argument);
110
+ }
111
+ }
103
112
  }
104
113
  else {
105
114
  try {
@@ -141,8 +141,7 @@ function escapedDefinitions(hidden) {
141
141
  };
142
142
  }
143
143
  /** Emits {@link EdgeType.SideEffectOnCall} edges for definitions that escape a function transitively. */
144
- function propagateTransitiveDefinitions(graph, environment, ctx, hidden) {
145
- const summary = computeCallGraphSummaries(graph, escapedDefinitions(hidden));
144
+ function propagateTransitiveDefinitions(graph, environment, ctx, summary) {
146
145
  for (const [id, vertex] of graph.vertices(true)) {
147
146
  if (!vertex_1.DfgVertex.isFunctionCall(vertex)) {
148
147
  continue;
@@ -276,8 +275,7 @@ function escapedDefinitionMap(graph, hidden) {
276
275
  * `f <- function() x <<- 1; g <- function() f(); g(); print(x)` makes `x` resolvable.
277
276
  * @returns the enriched environment and whether it grew (so the extractor can re-resolve open reads and re-run).
278
277
  */
279
- function propagateTransitiveEscapedDefinitions(graph, environment, defined, hidden, open) {
280
- const summary = computeCallGraphSummaries(graph, escapedDefinitions(hidden));
278
+ function propagateTransitiveEscapedDefinitions(graph, environment, defined, hidden, summary, open) {
281
279
  const defs = escapedDefinitionMap(graph, hidden);
282
280
  const names = new Set();
283
281
  let byName;
@@ -320,7 +318,8 @@ function linkReadsAfter(graph, call, def, open, definitionsNamed) {
320
318
  const replaced = new Set([...visible, ...(0, frame_reflection_1.edgeSources)(graph, call, edge_1.EdgeType.SideEffectOnCall)]);
321
319
  const readers = new Set(open.filter(r => r.name === def.name).map(r => r.nodeId));
322
320
  for (const [id] of graph.vertices(true)) {
323
- if ((readers.has(id) || graph.edgesFrom(id).entries().some(([target, edge]) => edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Reads) && replaced.has(target)))
321
+ /* an argument reads the value of a call, not a name the call may define (an ambient state is defined at its call) */
322
+ if ((readers.has(id) || graph.edgesFrom(id).entries().some(([target, edge]) => edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Reads) && edge_1.DfEdge.doesNotIncludeType(edge, edge_1.EdgeType.Argument) && replaced.has(target)))
324
323
  && !program_order_1.ProgramOrder.definedLater(call, program_order_1.ProgramOrder.runsOnceAt(id, graph), graph)) {
325
324
  graph.addEdge(id, def.nodeId, edge_1.EdgeType.Reads);
326
325
  }
@@ -346,9 +345,11 @@ function reResolveOpenReferences(graph, environment, references, escapedNames) {
346
345
  */
347
346
  function propagateTransitiveSideEffects(graph, environment, ctx, defined = new Set(), open = []) {
348
347
  const hidden = hiddenBuiltInWrites(graph, environment);
349
- propagateTransitiveDefinitions(graph, environment, ctx, hidden);
348
+ /* both passes ask what escapes each function, and neither changes a body or a call target in between */
349
+ const escapes = computeCallGraphSummaries(graph, escapedDefinitions(hidden));
350
+ propagateTransitiveDefinitions(graph, environment, ctx, escapes);
350
351
  const packages = propagateTransitivePackages(graph, environment, ctx);
351
- const escaped = propagateTransitiveEscapedDefinitions(graph, packages.environment, defined, hidden, open);
352
+ const escaped = propagateTransitiveEscapedDefinitions(graph, packages.environment, defined, hidden, escapes, open);
352
353
  return { environment: escaped.environment, grew: packages.grew || escaped.grew, escapedNames: escaped.names };
353
354
  }
354
355
  //# sourceMappingURL=transitive-side-effects.js.map
@@ -13,6 +13,7 @@ const happens_before_1 = require("../../../../../control-flow/happens-before");
13
13
  const r_symbol_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
14
14
  const linker_1 = require("../../../linker");
15
15
  const frame_reflection_1 = require("../../../../fn/frame-reflection");
16
+ const r_function_definition_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
16
17
  const built_in_proc_name_1 = require("../../../../environments/built-in-proc-name");
17
18
  /** The vertices of `type` by their unquoted name. */
18
19
  function verticesByName(graph, type, idMap) {
@@ -24,7 +25,11 @@ function namesWithin(expr, graph, idMap) {
24
25
  const names = [];
25
26
  const callees = new Set();
26
27
  model_1.RNode.visitAst(idMap.get(expr), inner => {
27
- if (r_function_call_1.RFunctionCall.isNamed(inner)) {
28
+ /* a definition only creates its closure, the body runs when it is called and that call carries its effects */
29
+ if (r_function_definition_1.RFunctionDefinition.is(inner)) {
30
+ return true;
31
+ }
32
+ else if (r_function_call_1.RFunctionCall.isNamed(inner)) {
28
33
  callees.add(inner.functionName.info.id);
29
34
  /* a call reads the function it names, so `evalq(f())` needs the definition of `f` */
30
35
  if (vertex_1.DfgVertex.isFunctionCall(graph.getVertex(inner.info.id))) {
@@ -7,6 +7,11 @@ const function_semantics_1 = require("../../../../fn/function-semantics");
7
7
  const info_1 = require("../../../../info");
8
8
  const known_call_handling_1 = require("./known-call-handling");
9
9
  const append_1 = require("../../../../environments/append");
10
+ const r_parameter_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-parameter");
11
+ const r_string_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-string");
12
+ const r_expression_list_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
13
+ const model_1 = require("../../../../../r-bridge/lang-4.x/ast/model/model");
14
+ const operators_1 = require("../../../../../r-bridge/lang-4.x/ast/model/operators");
10
15
  const r_function_call_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
11
16
  const r_binary_op_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op");
12
17
  const r_symbol_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
@@ -19,6 +24,8 @@ const built_in_library_1 = require("./built-in/built-in-library");
19
24
  const vertex_1 = require("../../../../graph/vertex");
20
25
  const resolve_helper_1 = require("../../../../environments/resolve-helper");
21
26
  const assert_1 = require("../../../../../util/assert");
27
+ const built_in_props_1 = require("../../../../environments/built-in-props");
28
+ const query_fn_props_1 = require("../../../../environments/query-fn-props");
22
29
  function mergeInformation(info, newInfo) {
23
30
  if (info === undefined) {
24
31
  return newInfo;
@@ -69,9 +76,16 @@ function markAsOnlyBuiltIn(graph, rootId, keepEnvironment = false) {
69
76
  }
70
77
  }
71
78
  }
79
+ const HandedFunction = identifier_1.ReferenceType.Function | identifier_1.ReferenceType.Parameter | identifier_1.ReferenceType.Argument;
80
+ /** Whether `arg` hands over a function that may draw: a symbol bound to data (`d <- read.csv(f)`, `NA`) does not, nor does a built-in stating it does not (`mean`) */
72
81
  function handsOverFunction(arg, data) {
73
82
  const value = arg === r_function_call_1.EmptyArgument ? undefined : arg.value;
74
- return r_function_definition_1.RFunctionDefinition.is(value) || (r_symbol_1.RSymbol.is(value) && (resolve_helper_1.Resolve.byNameAndType(value.content, data.environment, identifier_1.ReferenceType.Function)?.length ?? 0) > 0);
83
+ if (!r_symbol_1.RSymbol.is(value)) {
84
+ return r_function_definition_1.RFunctionDefinition.is(value);
85
+ }
86
+ const defs = resolve_helper_1.Resolve.byNameAndType(value.content, data.environment, identifier_1.ReferenceType.Function) ?? [];
87
+ return defs.some(d => (0, identifier_1.isReferenceType)(d.type, HandedFunction)) || (defs.some(d => d.type === identifier_1.ReferenceType.BuiltInFunction)
88
+ && built_in_props_1.CallProps.hasAny((0, query_fn_props_1.queryFnProps)(value.content, { environment: data.environment }), [built_in_props_1.CallProp.Configures, built_in_props_1.SemanticCallTag.Random]));
75
89
  }
76
90
  /** Whether a replacement function rewrote the value of `definition`, like `body(f) <- quote(runif(1))`, so its body is unknown. */
77
91
  function rewrittenByReplacement(definition, data) {
@@ -79,6 +93,35 @@ function rewrittenByReplacement(definition, data) {
79
93
  const node = definition.type === identifier_1.ReferenceType.Unknown && at !== undefined ? data.completeAst.idMap.get(at) : undefined;
80
94
  return r_function_call_1.RFunctionCall.is(node) || (r_binary_op_1.RBinaryOp.is(node) && r_function_call_1.RFunctionCall.is(node.lhs));
81
95
  }
96
+ const bindingFrames = new WeakMap();
97
+ /** for each name the program binds, the functions binding it (`undefined` for the global frame or a `<<-`) */
98
+ function framesBinding(idMap) {
99
+ let frames = bindingFrames.get(idMap);
100
+ if (frames === undefined) {
101
+ const found = new Map();
102
+ for (const node of idMap.values()) {
103
+ const target = r_binary_op_1.RBinaryOp.is(node) && operators_1.OperatorDatabase[node.operator]?.usedAs === 'assignment' ? (node.operator.startsWith('-') ? node.rhs : node.lhs)
104
+ : r_parameter_1.RParameter.is(node) ? node.name : undefined;
105
+ const name = r_symbol_1.RSymbol.is(target) ? identifier_1.Identifier.getName(target.content) : r_string_1.RString.is(target) ? target.content.str : undefined;
106
+ if (name !== undefined) {
107
+ const global = r_binary_op_1.RBinaryOp.is(node) && (node.operator === '<<-' || node.operator === '->>');
108
+ const frame = global ? undefined : model_1.RNode.findEnclosing(node.info.id, idMap, r_function_definition_1.RFunctionDefinition.is);
109
+ found.set(name, new Set([...found.get(name) ?? [], frame]));
110
+ }
111
+ }
112
+ bindingFrames.set(idMap, frames = found);
113
+ }
114
+ return frames;
115
+ }
116
+ /** whether the program binds `name` in a frame enclosing the function the call is in, which a built-in found there leaves out */
117
+ function mayBeShadowed(name, call, idMap) {
118
+ const frames = framesBinding(idMap).get(name);
119
+ if (frames === undefined || r_expression_list_1.RExpressionList.isImplicit(idMap.get(call))) {
120
+ return false;
121
+ }
122
+ const own = model_1.RNode.findEnclosing(call, idMap, r_function_definition_1.RFunctionDefinition.is);
123
+ return frames.has(undefined) || [...model_1.RNode.iterateParents(idMap.get(own), idMap)].some(p => frames.has(p.info.id));
124
+ }
82
125
  /**
83
126
  * Processes a named function call within the dataflow analysis.
84
127
  * For example, `myFunction(arg1, arg2)`, resolves against the environment.
@@ -86,7 +129,10 @@ function rewrittenByReplacement(definition, data) {
86
129
  function processNamedCall(name, callArguments, rootId, data) {
87
130
  const args = data.pipedArgument?.rootId === rootId ? [data.pipedArgument.argument, ...callArguments] : callArguments;
88
131
  const resolved = resolve_helper_1.Resolve.byNameAndType(name.content, data.environment, identifier_1.ReferenceType.Function) ?? [];
89
- let defaultProcessor = resolved.length === 0;
132
+ /* a function body sees its enclosing frames only where it is called, so a built-in there may be shadowed by the program */
133
+ const shadowable = resolved.length > 0 && data.environment.level > 0 && resolved.every(r => r.type === identifier_1.ReferenceType.BuiltInFunction)
134
+ && mayBeShadowed(identifier_1.Identifier.getName(name.content), rootId, data.completeAst.idMap);
135
+ let defaultProcessor = resolved.length === 0 || shadowable;
90
136
  /* a call whose meaning a later pass looks up in its environment has to keep it */
91
137
  const keepEnvironment = resolved.some(r => r.type === identifier_1.ReferenceType.BuiltInFunction && r.config?.keepEnvironment === true);
92
138
  /* a call marked as built-in only (see below) needs no environment snapshot */
@@ -117,21 +163,36 @@ function processNamedCall(name, callArguments, rootId, data) {
117
163
  }
118
164
  /* flowR models what a package function does with its arguments, but not which of its options it reads */
119
165
  let packageFn = false;
166
+ const alternatives = [];
167
+ const processDefault = () => {
168
+ /* if we do not know where we land, we force! reuse `resolved`, data.environment did not change above */
169
+ const sig = resolved.length > 0 ? undefined : function_semantics_1.FunctionSemantics.call.signature.every;
170
+ alternatives.push((0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, sig, origin: 'default' }).information);
171
+ };
172
+ /* first, so the arguments keep the promise the shadowing function makes of them, which holds for a forcing built-in, too */
173
+ if (shadowable) {
174
+ processDefault();
175
+ }
120
176
  for (const own of toRun) {
121
- information = mergeInformation(information, own.processor(name, args, rootId, data));
177
+ alternatives.push(own.processor(name, args, rootId, data));
122
178
  const pkg = own.name === undefined ? undefined : identifier_1.Identifier.getNamespace(own.name);
123
179
  /* unless flowR states how it accesses the state, as for `withr::with_options` */
124
180
  packageFn ||= pkg !== undefined && !(own.config !== undefined && ('ambient' in own.config || 'scope' in own.config)) && !(0, r_base_packages_1.isBaseRPackage)(String(pkg));
125
181
  }
126
- if (defaultProcessor) {
127
- /* if we do not know where we land, we force! reuse `resolved`, data.environment did not change above */
128
- const sig = resolved.length > 0 ? undefined : function_semantics_1.FunctionSemantics.call.signature.every;
129
- const call = (0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, sig, origin: 'default' });
130
- information = mergeInformation(information, call.information);
182
+ if (defaultProcessor && !shadowable) {
183
+ processDefault();
184
+ }
185
+ for (const alternative of alternatives) {
186
+ information = mergeInformation(information, alternative);
131
187
  }
132
- else if (information && builtIn) {
188
+ if (!defaultProcessor && information && builtIn) {
133
189
  markAsOnlyBuiltIn(information.graph, rootId, keepEnvironment);
134
190
  }
191
+ /* an exit only some of the possible callees take is not certain */
192
+ if (information !== undefined && alternatives.length > 1) {
193
+ const inAll = (e) => alternatives.every(a => a.exitPoints.some(o => o.nodeId === e.nodeId && o.type === e.type));
194
+ information = { ...information, exitPoints: information.exitPoints.map(e => inAll(e) ? e : { ...e, cds: (0, info_1.withCds)(e.cds, [{ id: rootId, when: true }]) }) };
195
+ }
135
196
  /* a function whose body we do not see may read any option or draw on the device */
136
197
  if (information !== undefined && (unknownBody || packageFn)) {
137
198
  /* a function handed in as a parameter may be anything, `runif` included, and a function handed a function may call it;
@@ -285,7 +285,10 @@ function obtainDetailedInfos() {
285
285
  foundAny = true;
286
286
  const base = JSON.parse(fs_1.default.readFileSync(file).toString());
287
287
  for (const [key, values] of base) {
288
- out.get(key).push(...values.map(v => ({ ...v, capabilities: new Set(v.capabilities), context: new Set(v.context) })));
288
+ const target = out.get(key);
289
+ for (const v of values) {
290
+ target.push({ ...v, capabilities: new Set(v.capabilities), context: new Set(v.context) });
291
+ }
289
292
  }
290
293
  }
291
294
  return foundAny ? out : undefined;
@@ -216,6 +216,10 @@ function explainConfigFile(ctx) {
216
216
  When running _flowR_, you may want to specify some behaviors with a dedicated configuration file.
217
217
  By default, flowR looks for a file named \`${flowr_main_options_1.defaultConfigFile}\` in the current working directory (or any higher directory).
218
218
  You can also specify a different file with ${(0, doc_cli_option_1.getCliLongOptionOf)('flowr', 'config-file')} or pass the configuration inline using ${(0, doc_cli_option_1.getCliLongOptionOf)('flowr', 'config-json')}.
219
+ A \`${flowr_main_options_1.defaultConfigFile}\` found this way belongs to the analyzed project, so flowR ignores its options that decide what flowR executes or loads
220
+ (${config_1.FlowrConfig.securitySensitivePaths().filter(p => p[0] !== 'specializeConfig').map(p => `\`${p.join('.')}\``).join(', ')}),
221
+ unless you pass ${(0, doc_cli_option_1.getCliLongOptionOf)('flowr', 'trust-config')}.
222
+ To analyze code you do not trust, use the secure mode (${(0, doc_cli_option_1.getCliLongOptionOf)('flowr', 'secure')}, see the [security policy](https://github.com/flowr-analysis/flowr/blob/main/.github/SECURITY.md)).
219
223
  To inspect the current configuration, you can run flowr with the ${(0, doc_cli_option_1.getCliLongOptionOf)('flowr', 'verbose')} flag, or use the \`config\` ${ctx.linkPage('wiki/Query API', 'Query')}.
220
224
  Within the REPL this works by running the following:
221
225
 
package/engines.js CHANGED
@@ -6,13 +6,18 @@ const shell_1 = require("./r-bridge/shell");
6
6
  const ansi_1 = require("./util/text/ansi");
7
7
  const tree_sitter_executor_1 = require("./r-bridge/lang-4.x/tree-sitter/tree-sitter-executor");
8
8
  const log_1 = require("./util/log");
9
+ const secure_mode_1 = require("./util/secure-mode");
9
10
  /**
10
11
  * Retrieve all requested engine instance.
11
12
  * Please make sure that if this includes the R engine, that you properly shut it down again!
12
13
  */
13
14
  async function retrieveEngineInstances(config, defaultOnly = false) {
14
15
  const engines = {};
15
- if (config_1.FlowrConfig.getForEngine(config, 'r-shell') && (!defaultOnly || config.defaultEngine === 'r-shell')) {
16
+ const rShellWanted = config_1.FlowrConfig.getForEngine(config, 'r-shell') && (!defaultOnly || config.defaultEngine === 'r-shell');
17
+ if (rShellWanted && secure_mode_1.SecureMode.isEnabled()) {
18
+ log_1.log.warn('The secure mode forbids starting R, so the r-shell engine is not available');
19
+ }
20
+ else if (rShellWanted) {
16
21
  // we keep an active shell session to allow other parse investigations :)
17
22
  engines['r-shell'] = new shell_1.RShell(config_1.FlowrConfig.getForEngine(config, 'r-shell'), {
18
23
  revive: 2 /* RShellReviveOptions.Always */,
@@ -23,8 +28,11 @@ async function retrieveEngineInstances(config, defaultOnly = false) {
23
28
  }
24
29
  });
25
30
  }
26
- if (config_1.FlowrConfig.getForEngine(config, 'tree-sitter') && (!defaultOnly || config.defaultEngine === 'tree-sitter')) {
27
- await tree_sitter_executor_1.TreeSitterExecutor.initTreeSitter(config_1.FlowrConfig.getForEngine(config, 'tree-sitter'));
31
+ // in secure mode, tree-sitter is the only engine, so we start it whenever r-shell was refused
32
+ const treeSitterForced = secure_mode_1.SecureMode.isEnabled() && rShellWanted;
33
+ const treeSitter = config_1.FlowrConfig.getForEngine(config, 'tree-sitter') ?? (treeSitterForced ? { type: 'tree-sitter' } : undefined);
34
+ if (treeSitter && (!defaultOnly || config.defaultEngine === 'tree-sitter' || treeSitterForced)) {
35
+ await tree_sitter_executor_1.TreeSitterExecutor.initTreeSitter(treeSitter);
28
36
  engines['tree-sitter'] = new tree_sitter_executor_1.TreeSitterExecutor();
29
37
  }
30
38
  let defaultEngine = config.defaultEngine;
@@ -4,13 +4,31 @@ exports.executeLintingRule = executeLintingRule;
4
4
  const linter_rules_1 = require("./linter-rules");
5
5
  const flowr_search_executor_1 = require("../search/flowr-search-executor");
6
6
  const objects_1 = require("../util/objects");
7
+ const secure_mode_1 = require("../util/secure-mode");
8
+ /**
9
+ * Rule options that are compiled to regular expressions. As a crafted regex can take exponential time to match (ReDoS),
10
+ * the {@link SecureMode} ignores them in a given rule config, keeping the rule's defaults. Add every new option of this kind.
11
+ */
12
+ const RegexRuleOptions = {
13
+ 'absolute-file-paths': ['absolutePathRegex'],
14
+ 'problematic-inputs': ['consider', 'pipeCommandFunctions'],
15
+ 'no-leaked-credentials': ['credentialNamePattern', 'credentialValuePattern']
16
+ };
17
+ /** The given rule config without the {@link RegexRuleOptions} if the secure mode is enabled. */
18
+ function withoutUntrustedRegexes(ruleName, config) {
19
+ const keys = RegexRuleOptions[ruleName];
20
+ if (!config || !keys || !secure_mode_1.SecureMode.isEnabled()) {
21
+ return config;
22
+ }
23
+ return Object.fromEntries(Object.entries(config).filter(([k]) => !keys.includes(k)));
24
+ }
7
25
  /**
8
26
  * Executes a specific linting rule on the given analysis provider input.
9
27
  */
10
28
  async function executeLintingRule(ruleName, input, lintingRuleConfig) {
11
29
  try {
12
30
  const rule = linter_rules_1.LintingRules[ruleName];
13
- const fullConfig = (0, objects_1.deepMergeObject)(rule.info.defaultConfig(input.inspectContext()), lintingRuleConfig);
31
+ const fullConfig = (0, objects_1.deepMergeObject)(rule.info.defaultConfig(input.inspectContext()), withoutUntrustedRegexes(ruleName, lintingRuleConfig));
14
32
  const ruleSearch = rule.createSearch(fullConfig, input);
15
33
  const searchStart = Date.now();
16
34
  const searchResult = await (0, flowr_search_executor_1.runSearch)(ruleSearch, input);
@@ -241,7 +241,7 @@ export declare const LintingRules: {
241
241
  };
242
242
  };
243
243
  readonly 'problematic-inputs': {
244
- readonly createSearch: (config: import("./rules/problematic-inputs").ProblematicInputsConfig) => import("../search/flowr-search-builder").FlowrSearchBuilder<"from-query", [], import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElements<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElement<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>>;
244
+ readonly createSearch: () => import("../search/flowr-search-builder").FlowrSearchBuilder<"all", ["filter", "with"], import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, Promise<import("../search/flowr-search").FlowrSearchElements<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElement<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>>>;
245
245
  readonly processSearchResult: (elements: import("../search/flowr-search").FlowrSearchElements<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElement<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>, config: import("./rules/problematic-inputs").ProblematicInputsConfig, data: import("..").ReadonlyFlowrAnalysisProvider<import("..").KnownParser>) => Promise<{
246
246
  results: import("./rules/problematic-inputs").ProblematicInputsResult[];
247
247
  }>;
@@ -357,12 +357,13 @@ export declare const LintingRules: {
357
357
  };
358
358
  readonly info: {
359
359
  readonly name: "No Leaked Credentials";
360
- readonly description: "Detects hardcoded credentials assigned to variables whose names suggest they hold passwords, tokens, or API keys, or whose values match known credential formats (AWS, GitHub, Slack, Stripe, SSH).";
360
+ readonly description: "Detects hardcoded credentials assigned to variables or passed as arguments whose names suggest they hold passwords, tokens, or API keys, handed to authentication functions, or whose values match known credential formats (AWS, GitHub, Slack, Stripe, Google, JWT, SSH, URLs with passwords).";
361
361
  readonly tags: readonly [import("./linter-tags").LintingRuleTag.Security, import("./linter-tags").LintingRuleTag.Experimental, import("./linter-tags").LintingRuleTag.Smell];
362
362
  readonly certainty: import("./linter-format").LintingRuleCertainty.BestEffort;
363
363
  readonly defaultConfig: () => {
364
364
  credentialNamePattern: string;
365
365
  credentialValuePattern: string;
366
+ credentialCallPattern: string;
366
367
  };
367
368
  };
368
369
  };
@@ -490,7 +491,7 @@ export declare const LintingRules: {
490
491
  };
491
492
  };
492
493
  eval: {
493
- criticalCalls: import("..").SemanticCallTag.Eval;
494
+ criticalCalls: (import("..").SemanticCallTag.Eval | import("..").CallProp)[];
494
495
  criticalArgs: import("..").ArgProp;
495
496
  sanitizers: import("..").Identifier[];
496
497
  };
@@ -520,6 +521,10 @@ export declare const LintingRules: {
520
521
  call: import("..").Identifier;
521
522
  partsOnly: true;
522
523
  };
524
+ methods: {
525
+ receiver: import("..").Identifier;
526
+ method: string;
527
+ }[];
523
528
  };
524
529
  };
525
530
  disabledCategories: never[];
@@ -29,11 +29,13 @@ const query_fn_props_1 = require("../../dataflow/environments/query-fn-props");
29
29
  const built_in_props_1 = require("../../dataflow/environments/built-in-props");
30
30
  const resolve_argument_1 = require("../../dataflow/eval/resolve/resolve-argument");
31
31
  const r_base_packages_1 = require("../../util/r-base-packages");
32
+ const secure_mode_1 = require("../../util/secure-mode");
32
33
  const DataSetExtensions = ['R', 'r', 'RData', 'rdata', 'rda', 'tab', 'txt', 'TXT', 'tab.gz', 'tab.bz2', 'tab.xz', 'txt.gz', 'txt.bz2', 'txt.xz', 'csv', 'CSV'];
33
34
  function namesPackage(node) {
34
35
  return r_function_call_1.RFunctionCall.is(node) && node.arguments.some(a => a !== r_function_call_1.EmptyArgument && a.name !== undefined && ['package', 'lib.loc'].includes(identifier_1.Identifier.getName(a.name.content)));
35
36
  }
36
37
  async function urlExists(url) {
38
+ secure_mode_1.SecureMode.guard('network access', url);
37
39
  try {
38
40
  return (await fetch(url, { method: 'HEAD' })).ok;
39
41
  }
@@ -116,7 +118,8 @@ exports.FILE_PATH_VALIDITY = {
116
118
  }
117
119
  // handle remote URLs separately from file paths
118
120
  if ((0, strings_1.isUrl)(path)) {
119
- return config.checkUrls ? verdict(await urlExists(path), path, linter_format_1.LintingResultCertainty.Uncertain) : [];
121
+ // the secure mode forbids network access, so the URL stays unchecked as if checkUrls was off
122
+ return config.checkUrls && !secure_mode_1.SecureMode.isEnabled() ? verdict(await urlExists(path), path, linter_format_1.LintingResultCertainty.Uncertain) : [];
120
123
  }
121
124
  // check if any write to the same file happens before the read, and exclude this case if so
122
125
  const writesToFile = results.write.filter((r) => r.nodeId !== undefined && samePath(r.value, path, resolveSource?.ignoreCapitalization));
@@ -31,7 +31,7 @@ export declare const functionFinderUtil: {
31
31
  query: (result: FunctionsResult) => string;
32
32
  full: (result: FunctionsResult) => string;
33
33
  };
34
- requireArgumentValue(element: FlowrSearchElement<ParentInformation>, pool: ReadonlyMap<string, FunctionInfo>, analyzer: ReadonlyFlowrAnalysisProvider, requireValue: RegExp | string | undefined): Promise<Ternary>;
34
+ requireArgumentValue(element: FlowrSearchElement<ParentInformation>, pool: ReadonlyMap<string, FunctionInfo>, analyzer: ReadonlyFlowrAnalysisProvider, requireValue: RegExp | string | undefined, identifier: Identifier | undefined): Promise<Ternary>;
35
35
  };
36
36
  /**
37
37
  * Test if a function call has an argument with a specific value
@@ -14,7 +14,6 @@ const vertex_1 = require("../../dataflow/graph/vertex");
14
14
  const dependencies_query_format_1 = require("../../queries/catalog/dependencies-query/dependencies-query-format");
15
15
  const identifier_1 = require("../../dataflow/environments/identifier");
16
16
  const logic_1 = require("../../util/logic");
17
- const df_helper_1 = require("../../dataflow/graph/df-helper");
18
17
  /**
19
18
  * This helper object collects utility functions used to create linting rules that search for specific functions.
20
19
  */
@@ -66,9 +65,8 @@ exports.functionFinderUtil = {
66
65
  [linter_format_1.LintingPrettyPrintContext.Full]: (result) => `Function \`${result.function}\` called at ${range_1.SourceLocation.format(result.loc)} is related to ${functionType}`
67
66
  };
68
67
  },
69
- async requireArgumentValue(element, pool, analyzer, requireValue) {
68
+ async requireArgumentValue(element, pool, analyzer, requireValue, identifier) {
70
69
  const dataflow = await analyzer.dataflow();
71
- const identifier = df_helper_1.Dataflow.qualify(element.node.info.id, dataflow.graph, true) ?? (element.node.lexeme !== undefined ? identifier_1.Identifier.parse(element.node.lexeme) : undefined);
72
70
  /* if we have no additional info, we assume they always access the network */
73
71
  if (identifier === undefined || requireValue === undefined) {
74
72
  return logic_1.Ternary.Always;
@@ -31,9 +31,10 @@ export interface NetworkFunction extends MergeableRecord {
31
31
  }
32
32
  /**
33
33
  * Every built-in that may reach the network, read back from the {@link DefaultBuiltinConfig}: the ones labeled
34
- * {@link SemanticCallTag.Network} always do, and any call naming an {@link ArgProp.Resource} does whenever that
35
- * resource is a url rather than a path -- which is what {@link UrlPattern} decides per call site. Label a
36
- * built-in `Network` or give it a resource parameter and it shows up here; nothing is listed twice.
34
+ * {@link SemanticCallTag.Network} always do unless they may open a local {@link SemanticCallTag.File} instead,
35
+ * and any call naming an {@link ArgProp.Resource} does whenever that resource is a url rather than a path --
36
+ * which is what {@link UrlPattern} decides per call site. Label a built-in `Network` or give it a resource
37
+ * parameter and it shows up here; nothing is listed twice.
37
38
  */
38
39
  export declare function networkFunctions(index: BuiltInIndex): NetworkFunction[];
39
40
  export declare const NETWORK_FUNCTIONS: {