@eagleoutice/flowr 2.16.0 → 2.16.1

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 (49) 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/extractor.js +14 -5
  20. package/dataflow/fn/frame-reflection.js +14 -2
  21. package/dataflow/internal/control-flow.d.ts +11 -0
  22. package/dataflow/internal/control-flow.js +15 -0
  23. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +4 -10
  24. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +1 -1
  25. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +8 -7
  26. package/dataflow/internal/process/functions/call/deferred.js +6 -1
  27. package/dataflow/internal/process/functions/call/named-call-handling.js +10 -1
  28. package/documentation/doc-capabilities.js +4 -1
  29. package/documentation/wiki-interface.js +4 -0
  30. package/engines.js +11 -3
  31. package/linter/linter-executor.js +19 -1
  32. package/linter/rules/file-path-validity.js +4 -1
  33. package/linter/rules/seeded-randomness.js +3 -1
  34. package/package.json +1 -1
  35. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +14 -5
  36. package/project/plugins/file-plugins/files/flowr-rda-file.js +35 -24
  37. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +2 -1
  38. package/project/sigdb/decompress.js +3 -1
  39. package/project/sigdb/sigdb-download.js +9 -6
  40. package/queries/catalog/config-query/config-query-executor.js +9 -2
  41. package/r-bridge/shell-executor.js +2 -0
  42. package/r-bridge/shell.js +2 -0
  43. package/slicing/static/static-slicer.js +14 -9
  44. package/util/files.d.ts +6 -0
  45. package/util/files.js +12 -0
  46. package/util/parallel.js +2 -0
  47. package/util/secure-mode.d.ts +42 -0
  48. package/util/secure-mode.js +70 -0
  49. package/util/version.js +2 -2
package/config.js CHANGED
@@ -20,6 +20,15 @@ const project_kind_1 = require("./project/context/project-kind");
20
20
  const gas_1 = require("./gas");
21
21
  const input_types_1 = require("./queries/catalog/input-sources-query/input-types");
22
22
  const arrays_1 = require("./util/collections/arrays");
23
+ const secure_mode_1 = require("./util/secure-mode");
24
+ /** Marks an option that decides what flowR executes or loads, it is dropped from untrusted configs (see {@link FlowrConfig.fromFile}). */
25
+ function securitySensitive(schema) {
26
+ return schema.meta({ securitySensitive: true });
27
+ }
28
+ /** Marks an option holding regular expressions, which the {@link SecureMode} drops from every config (ReDoS). */
29
+ function regexOption(schema) {
30
+ return schema.meta({ regex: true });
31
+ }
23
32
  var VariableResolve;
24
33
  (function (VariableResolve) {
25
34
  /** Don't resolve constants at all */
@@ -415,7 +424,7 @@ exports.FlowrConfig = {
415
424
  classification: joi_1.default.object({
416
425
  shinyDescriptionTypes: joi_1.default.array().items(joi_1.default.string()).optional().description('DESCRIPTION Type: values that mark a shiny app.'),
417
426
  shinyEntryFiles: joi_1.default.array().items(joi_1.default.string()).optional().description('File names a shiny app is assembled from.'),
418
- shinyUsagePattern: joi_1.default.string().optional().description('Regex source evidencing shiny usage in an entry file.'),
427
+ shinyUsagePattern: regexOption(joi_1.default.string().optional()).description('Regex source evidencing shiny usage in an entry file.'),
419
428
  notebookExtensions: joi_1.default.array().items(joi_1.default.string()).optional().description('File extensions marking a notebook.')
420
429
  }).optional().description('Overrides for the signals flowR uses to classify the project kind.')
421
430
  }).description('Project specific configuration options.'),
@@ -434,12 +443,12 @@ exports.FlowrConfig = {
434
443
  .description('Overwrite (parts of) the configuration depending on the project kind flowR detects, e.g. to give a shiny app its implicit sources.'),
435
444
  engines: joi_1.default.array().items(joi_1.default.alternatives(joi_1.default.object({
436
445
  type: joi_1.default.string().required().valid('tree-sitter').description('Use the tree sitter engine.'),
437
- wasmPath: joi_1.default.string().optional().description('The path to the tree-sitter-r WASM binary to use. If this is undefined, this uses the default path.'),
438
- treeSitterWasmPath: joi_1.default.string().optional().description('The path to the tree-sitter WASM binary to use. If this is undefined, this uses the default path.'),
446
+ wasmPath: securitySensitive(joi_1.default.string().optional()).description('The path to the tree-sitter-r WASM binary to use. If this is undefined, this uses the default path.'),
447
+ treeSitterWasmPath: securitySensitive(joi_1.default.string().optional()).description('The path to the tree-sitter WASM binary to use. If this is undefined, this uses the default path.'),
439
448
  lax: joi_1.default.boolean().optional().description('Whether to use the lax parser for parsing R code (allowing for syntax errors). If this is undefined, the strict parser will be used.')
440
449
  }).description('The configuration for the tree sitter engine.'), joi_1.default.object({
441
450
  type: joi_1.default.string().required().valid('r-shell').description('Use the R shell engine.'),
442
- rPath: joi_1.default.string().optional().description('The path to the R executable to use. If this is undefined, this uses the default path.'),
451
+ rPath: securitySensitive(joi_1.default.string().optional()).description('The path to the R executable to use. If this is undefined, this uses the default path.'),
443
452
  pipeBind: joi_1.default.boolean().optional().description('Whether to enable R\'s experimental pipe-bind operator "=>" by setting _R_USE_PIPEBIND_ for the R session (default false); R itself keeps this off by default, as it is experimental and has never shipped in a release version of R.')
444
453
  }).description('The configuration for the R shell engine.'))).description('The engine or set of engines to use for interacting with R code. An empty array means all available engines will be used.'),
445
454
  defaultEngine: joi_1.default.string().optional().valid('tree-sitter', 'r-shell').description('The default engine to use for interacting with R code. If this is undefined, an arbitrary engine from the specified list will be used.'),
@@ -458,16 +467,16 @@ exports.FlowrConfig = {
458
467
  linkPackageCalls: joi_1.default.boolean().optional().description('Add a lightweight Reads edge from a resolved package call to its signature-database function vertex (default false).'),
459
468
  linkDescriptionDependencies: joi_1.default.boolean().optional().description('Eagerly attach the namespaces of the project\'s declared DESCRIPTION dependencies (Imports/Depends) so their exports resolve without an explicit library() (default false).'),
460
469
  warmInBackground: joi_1.default.boolean().optional().description('Decompress the hot shards (base + most-downloaded) in a background task on startup so the first library() lookup is warm (default false; for long-running servers/REPLs).'),
461
- additionalPaths: joi_1.default.array().items(joi_1.default.string()).optional().description('Extra directories or bundle/manifest files searched for signature databases (alongside the shipped default and $FLOWR_SIGDB_DIR); a downloaded full-history bundle placed here is mounted automatically.'),
462
- downloadRepo: joi_1.default.string().optional().description('GitHub owner/repo the full-history bundle is downloaded from via ":signature download" (default "flowr-analysis/flowr", release tag "sigdb-v<flowR-version>").'),
470
+ additionalPaths: securitySensitive(joi_1.default.array().items(joi_1.default.string()).optional()).description('Extra directories or bundle/manifest files searched for signature databases (alongside the shipped default and $FLOWR_SIGDB_DIR); a downloaded full-history bundle placed here is mounted automatically.'),
471
+ downloadRepo: securitySensitive(joi_1.default.string().optional()).description('GitHub owner/repo the full-history bundle is downloaded from via ":signature download" (default "flowr-analysis/flowr", release tag "sigdb-v<flowR-version>").'),
463
472
  autoSync: joi_1.default.boolean().optional().description('On startup, re-download shards whose committed sigdb.remote.json hash no longer matches the cache, in the background (default false; opt-in network sync after a git pull).'),
464
473
  installedLibrary: joi_1.default.object({
465
474
  enabled: joi_1.default.boolean().required().description('Recover packages no signature database knows from their installed copy (default false).'),
466
- paths: joi_1.default.array().items(joi_1.default.string()).optional().description('Library directories to search; when empty they are discovered from the environment and the project.'),
475
+ paths: securitySensitive(joi_1.default.array().items(joi_1.default.string()).optional()).description('Library directories to search; when empty they are discovered from the environment and the project.'),
467
476
  useEnvironment: joi_1.default.boolean().optional().description('Search the libraries R_LIBS_USER/R_LIBS/R_LIBS_SITE name (default true).'),
468
477
  useProjectLibrary: joi_1.default.boolean().optional().description('Search a project-local renv/packrat library (default true).'),
469
478
  maxDepth: joi_1.default.number().optional().description('How far to descend into the nested layout of a project-local library (default 3).'),
470
- packages: joi_1.default.array().items(joi_1.default.string()).optional().description('Only recover packages whose name matches one of these regular expressions; empty means any.')
479
+ packages: regexOption(joi_1.default.array().items(joi_1.default.string()).optional()).description('Only recover packages whose name matches one of these regular expressions; empty means any.')
471
480
  }).optional().description('Recovering packages no signature database knows from the copy installed on this machine.'),
472
481
  blobCacheBudgetMb: joi_1.default.number().min(0).optional().description('How many MiB of decoded package blobs every open bundle may hold together (default 16).'),
473
482
  versionSelection: joi_1.default.string().valid(...Object.values(VersionSelection)).optional().description('When a project constrains a dependency, resolve to the newest (default), oldest, or system-installed version satisfying it; system needs R and falls back to newest. Base-R packages always resolve against the assumed R version.'),
@@ -488,7 +497,7 @@ exports.FlowrConfig = {
488
497
  inferWorkingDirectory: joi_1.default.string().valid(...Object.values(InferWorkingDirectory)).description('Try to infer the working directory from the main or any script to analyze.'),
489
498
  searchPath: joi_1.default.array().items(joi_1.default.string()).description('Additionally search in these paths.'),
490
499
  repeatedSourceLimit: joi_1.default.number().optional().description('How often the same file can be sourced within a single run? Please be aware: in case of cyclic sources this may not reach a fixpoint so give this a sensible limit.'),
491
- applyReplacements: joi_1.default.array().items(joi_1.default.object()).description('Provide name replacements for loaded files'),
500
+ applyReplacements: regexOption(joi_1.default.array().items(joi_1.default.object())).description('Provide name replacements for loaded files'),
492
501
  assumeFilesExist: joi_1.default.boolean().optional().description('Assume a sourced file is always there, making what it defines certain instead of conditional on the source call.')
493
502
  }).optional().description('If lax source calls are active, flowR searches for sourced files much more freely, based on the configurations you give it. This option is only in effect if `ignoreSourceCalls` is set to false.'),
494
503
  slicer: joi_1.default.object({
@@ -560,9 +569,15 @@ exports.FlowrConfig = {
560
569
  /**
561
570
  * Parses the given JSON string as a flowR config file, returning the resulting config object if the parsing and validation were successful, or `undefined` if there was an error.
562
571
  */
563
- parse(jsonString) {
572
+ parse(jsonString, trusted = true) {
564
573
  try {
565
574
  const parsed = JSON.parse(jsonString);
575
+ const dropped = trusted && !secure_mode_1.SecureMode.isEnabled() ? [] : exports.FlowrConfig.dropUntrusted(parsed);
576
+ if (dropped.length > 0) {
577
+ console.warn(secure_mode_1.SecureMode.isEnabled()
578
+ ? `[flowR] Ignoring ${dropped.join(', ')}, the secure mode does not allow them in any config.`
579
+ : `[flowR] Ignoring ${dropped.join(', ')} from the project config, pass --config-file or --trust-config to use them.`);
580
+ }
566
581
  const validate = exports.FlowrConfig.Schema.validate(parsed);
567
582
  if (!validate.error) {
568
583
  // assign default values to all config options except for the specified ones
@@ -577,6 +592,23 @@ exports.FlowrConfig = {
577
592
  log_1.log.error(`Failed to parse config ${jsonString}: ${e.message}`);
578
593
  }
579
594
  },
595
+ /** Paths (`*` matching any key) of all {@link securitySensitive} options, also within `specializeConfig`. */
596
+ securitySensitivePaths() {
597
+ return taggedPaths('securitySensitive');
598
+ },
599
+ /** Paths of all {@link regexOption} options, see {@link FlowrConfig.securitySensitivePaths}. */
600
+ regexPaths() {
601
+ return taggedPaths('regex');
602
+ },
603
+ /** Removes all {@link FlowrConfig.securitySensitivePaths} from the raw config (in place), returns the removed paths. */
604
+ dropSecuritySensitive(raw) {
605
+ return exports.FlowrConfig.securitySensitivePaths().flatMap(p => dropPath(raw, p, ''));
606
+ },
607
+ /** Like {@link FlowrConfig.dropSecuritySensitive}, but in {@link SecureMode} also drops the {@link FlowrConfig.regexPaths}. */
608
+ dropUntrusted(raw) {
609
+ const dropped = exports.FlowrConfig.dropSecuritySensitive(raw);
610
+ return secure_mode_1.SecureMode.isEnabled() ? [...dropped, ...exports.FlowrConfig.regexPaths().flatMap(p => dropPath(raw, p, ''))] : dropped;
611
+ },
580
612
  /**
581
613
  * Creates a new flowr config that has the updated values.
582
614
  */
@@ -596,11 +628,15 @@ exports.FlowrConfig = {
596
628
  * Please note that you can also use this without a path parameter to
597
629
  * infer the config from flowR's default locations.
598
630
  * This is mostly useful for user-facing features.
631
+ * A relative `configFile` is searched for in the working directory and its parents. That file belongs to the analyzed
632
+ * project, so its {@link securitySensitive} options are dropped unless `trustProjectConfig` is set.
599
633
  */
600
- fromFile(configFile, configWorkingDirectory = process.cwd()) {
634
+ fromFile(configFile, configWorkingDirectory = process.cwd(), trustProjectConfig = false) {
601
635
  let config;
602
636
  try {
603
- config = loadConfigFromFile(configFile, configWorkingDirectory);
637
+ // the secure mode never searches for a project config
638
+ const searched = configFile !== undefined && !path_1.default.isAbsolute(configFile);
639
+ config = loadConfigFromFile(searched && secure_mode_1.SecureMode.isEnabled() ? undefined : configFile, configWorkingDirectory, trustProjectConfig);
604
640
  }
605
641
  catch (e) {
606
642
  log_1.log.error(`Failed to load config: ${e.message}`);
@@ -740,7 +776,48 @@ function persistSigDbPathToGlobalConfig(dbPath) {
740
776
  fs_1.default.writeFileSync(file, JSON.stringify(raw, null, '\t') + '\n');
741
777
  return file;
742
778
  }
743
- function loadConfigFromFile(configFile, workingDirectory) {
779
+ const taggedPathsCache = new Map();
780
+ function taggedPaths(meta) {
781
+ let paths = taggedPathsCache.get(meta);
782
+ if (paths === undefined) {
783
+ const base = collectTaggedPaths(exports.FlowrConfig.Schema.describe(), meta);
784
+ paths = [...base, ...base.map(p => ['specializeConfig', '*', ...p])];
785
+ taggedPathsCache.set(meta, paths);
786
+ }
787
+ return paths;
788
+ }
789
+ function collectTaggedPaths(d, meta, at = []) {
790
+ if (!d) {
791
+ return [];
792
+ }
793
+ else if (d.metas?.some(m => m[meta] === true)) {
794
+ return [[...at]];
795
+ }
796
+ return [
797
+ ...Object.entries(d.keys ?? {}).flatMap(([k, v]) => collectTaggedPaths(v, meta, [...at, k])),
798
+ ...(d.items ?? []).flatMap(i => collectTaggedPaths(i, meta, [...at, '*'])),
799
+ ...(d.matches ?? []).flatMap(m => collectTaggedPaths(m.schema, meta, at))
800
+ ];
801
+ }
802
+ function dropPath(obj, path, at) {
803
+ if (obj === null || typeof obj !== 'object' || path.length === 0) {
804
+ return [];
805
+ }
806
+ const [head, ...rest] = path;
807
+ const record = obj;
808
+ const dropped = [];
809
+ for (const key of head === '*' ? Object.keys(record) : Object.hasOwn(record, head) ? [head] : []) {
810
+ const next = at === '' ? key : `${at}.${key}`;
811
+ if (rest.length > 0) {
812
+ dropped.push(...dropPath(record[key], rest, next));
813
+ }
814
+ else if (Reflect.deleteProperty(record, key)) {
815
+ dropped.push(next);
816
+ }
817
+ }
818
+ return dropped;
819
+ }
820
+ function loadConfigFromFile(configFile, workingDirectory, trustProjectConfig) {
744
821
  if (configFile !== undefined) {
745
822
  if (path_1.default.isAbsolute(configFile) && fs_1.default.existsSync(configFile)) {
746
823
  log_1.log.trace(`Found config at ${configFile} (absolute)`);
@@ -755,7 +832,7 @@ function loadConfigFromFile(configFile, workingDirectory) {
755
832
  const configPath = path_1.default.join(searchPath, configFile);
756
833
  if (fs_1.default.existsSync(configPath)) {
757
834
  log_1.log.trace(`Found config at ${configPath}`);
758
- const ret = exports.FlowrConfig.parse(fs_1.default.readFileSync(configPath, { encoding: 'utf-8' }));
835
+ const ret = exports.FlowrConfig.parse(fs_1.default.readFileSync(configPath, { encoding: 'utf-8' }), trustProjectConfig);
759
836
  if (ret) {
760
837
  log_1.log.info(`Using config ${JSON.stringify(ret)}`);
761
838
  return ret;
@@ -160,17 +160,27 @@ function openReadsOfCalledFunctions(graph) {
160
160
  }
161
161
  /** An active binding (`makeActiveBinding`) runs its function on every assignment to and read of the name, so each becomes a call of it. */
162
162
  function callActiveBindings(graph) {
163
+ /* the definitions that call something are the bindings, and most scripts have none, so nothing else is walked then */
164
+ const active = new Set();
163
165
  const bindings = new Map();
164
166
  for (const [id] of graph.verticesOfType(vertex_1.VertexType.VariableDefinition)) {
165
- const fns = (0, frame_reflection_1.calledDefinitions)(graph, id);
166
- if (fns.length > 0) {
167
- bindings.set(id, fns);
167
+ const called = (0, frame_reflection_1.edgeTargets)(graph, id, edge_1.EdgeType.Calls);
168
+ if (called.length > 0) {
169
+ active.add(id);
170
+ const fns = called.filter(t => vertex_1.DfgVertex.isFunctionDefinition(graph.getVertex(t)));
171
+ if (fns.length > 0) {
172
+ bindings.set(id, fns);
173
+ }
168
174
  }
169
175
  }
176
+ if (active.size === 0) {
177
+ return;
178
+ }
170
179
  for (const [, ids] of bindings.size === 0 ? [] : (0, frame_reflection_1.definitionsByName)(graph).entries()) {
171
180
  const fns = ids.flatMap(id => bindings.get(id) ?? []);
172
181
  for (const id of fns.length === 0 ? [] : ids.filter(id => !bindings.has(id))) {
173
182
  for (const assignment of (0, frame_reflection_1.edgeSources)(graph, id, edge_1.EdgeType.Returns).filter(a => vertex_1.DfgVertex.isFunctionCall(graph.getVertex(a)))) {
183
+ active.add(id);
174
184
  for (const fn of fns) {
175
185
  graph.addEdge(assignment, fn, edge_1.EdgeType.Calls);
176
186
  graph.addEdge(id, fn, edge_1.EdgeType.Calls);
@@ -178,10 +188,9 @@ function callActiveBindings(graph) {
178
188
  }
179
189
  }
180
190
  }
181
- const isActiveBinding = (def) => vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(def)) && (0, frame_reflection_1.edgeTargets)(graph, def, edge_1.EdgeType.Calls).length > 0;
182
191
  for (const id of graph.vertexIdsOfType(vertex_1.VertexType.Use)) {
183
192
  const node = graph.idMap?.get(id);
184
- if (r_symbol_1.RSymbol.is(node) && (0, frame_reflection_1.edgeTargets)(graph, id, edge_1.EdgeType.Reads).some(isActiveBinding)) {
193
+ if (r_symbol_1.RSymbol.is(node) && (0, frame_reflection_1.edgeTargets)(graph, id, edge_1.EdgeType.Reads).some(def => active.has(def))) {
185
194
  graph.updateToFunctionCall({ tag: vertex_1.VertexType.FunctionCall, id, name: node.content, args: [], environment: undefined, onlyBuiltin: false, cds: graph.getVertex(id)?.cds, origin: [built_in_proc_name_1.BuiltInProcName.Function] });
186
195
  }
187
196
  }
@@ -19,7 +19,13 @@ const retriever_1 = require("../../r-bridge/retriever");
19
19
  const defaultmap_1 = require("../../util/collections/defaultmap");
20
20
  /** The nodes at the far end of `node`'s outgoing edges of any of `types`, shared by every walk here and in the sibling analyses that follow specific edge kinds. */
21
21
  function edgeTargets(graph, node, types) {
22
- return [...graph.edgesFrom(node)].filter(([, edge]) => edge_1.DfEdge.includesType(edge, types)).map(([target]) => target);
22
+ const found = [];
23
+ for (const [target, edge] of graph.edgesFrom(node)) {
24
+ if (edge_1.DfEdge.includesType(edge, types)) {
25
+ found.push(target);
26
+ }
27
+ }
28
+ return found;
23
29
  }
24
30
  /** The function-definition vertices a `call` resolves to (via {@link EdgeType.Calls}). */
25
31
  function calledDefinitions(graph, call) {
@@ -27,7 +33,13 @@ function calledDefinitions(graph, call) {
27
33
  }
28
34
  /** The nodes at the near end of `node`'s incoming edges of any of `types`, see {@link edgeTargets}. */
29
35
  function edgeSources(graph, node, types) {
30
- return [...graph.edgesTo(node)].filter(([, edge]) => edge_1.DfEdge.includesType(edge, types)).map(([source]) => source);
36
+ const found = [];
37
+ for (const [source, edge] of graph.edgesTo(node)) {
38
+ if (edge_1.DfEdge.includesType(edge, types)) {
39
+ found.push(source);
40
+ }
41
+ }
42
+ return found;
31
43
  }
32
44
  /** Every variable definition by its unquoted name, in a single pass. */
33
45
  function definitionsByName(graph) {
@@ -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 = [];
@@ -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))) {
@@ -19,6 +19,8 @@ const built_in_library_1 = require("./built-in/built-in-library");
19
19
  const vertex_1 = require("../../../../graph/vertex");
20
20
  const resolve_helper_1 = require("../../../../environments/resolve-helper");
21
21
  const assert_1 = require("../../../../../util/assert");
22
+ const built_in_props_1 = require("../../../../environments/built-in-props");
23
+ const query_fn_props_1 = require("../../../../environments/query-fn-props");
22
24
  function mergeInformation(info, newInfo) {
23
25
  if (info === undefined) {
24
26
  return newInfo;
@@ -69,9 +71,16 @@ function markAsOnlyBuiltIn(graph, rootId, keepEnvironment = false) {
69
71
  }
70
72
  }
71
73
  }
74
+ const HandedFunction = identifier_1.ReferenceType.Function | identifier_1.ReferenceType.Parameter | identifier_1.ReferenceType.Argument;
75
+ /** 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
76
  function handsOverFunction(arg, data) {
73
77
  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);
78
+ if (!r_symbol_1.RSymbol.is(value)) {
79
+ return r_function_definition_1.RFunctionDefinition.is(value);
80
+ }
81
+ const defs = resolve_helper_1.Resolve.byNameAndType(value.content, data.environment, identifier_1.ReferenceType.Function) ?? [];
82
+ return defs.some(d => (0, identifier_1.isReferenceType)(d.type, HandedFunction)) || (defs.some(d => d.type === identifier_1.ReferenceType.BuiltInFunction)
83
+ && 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
84
  }
76
85
  /** Whether a replacement function rewrote the value of `definition`, like `body(f) <- quote(runif(1))`, so its body is unknown. */
77
86
  function rewrittenByReplacement(definition, data) {
@@ -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);
@@ -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));
@@ -80,6 +80,8 @@ exports.SEEDED_RANDOMNESS = {
80
80
  const loops = graph.getVertex(reader)?.cds?.filter(cd => info_1.ControlDependency.isIterated(cd, idMap)) ?? [];
81
81
  return loops.some(loop => writerCds?.some(cd => info_1.ControlDependency.same(cd, loop)));
82
82
  };
83
+ /** a call of a draw by another name, like a parameter `f` bound to `runif` */
84
+ const drawsThrough = (call) => (0, frame_reflection_1.edgeTargets)(graph, call, edge_1.EdgeType.Calls).some(t => node_id_1.NodeId.isBuiltIn(t) && consumers.has(node_id_1.NodeId.fromBuiltIn(t))) ? 'draw' : undefined;
83
85
  /** the writes a draw reads the generator state from: its own, and those of the calls running the function it sits in, which link what was written before them */
84
86
  const statesReadBy = (id) => {
85
87
  const within = idMap === undefined ? undefined : model_1.RNode.findEnclosing(id, idMap, r_function_definition_1.RFunctionDefinition.is);
@@ -95,7 +97,7 @@ exports.SEEDED_RANDOMNESS = {
95
97
  let always = false;
96
98
  for (const target of statesReadBy(id)) {
97
99
  const writer = graph.getVertex(target);
98
- const kind = vertex_1.DfgVertex.isFunctionCall(writer) && !visiting.has(target) ? writerKind(writer) : undefined;
100
+ const kind = vertex_1.DfgVertex.isFunctionCall(writer) && !visiting.has(target) ? writerKind(writer) ?? drawsThrough(target) : undefined;
99
101
  if (kind === undefined) {
100
102
  continue;
101
103
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eagleoutice/flowr",
3
- "version": "2.16.0",
3
+ "version": "2.16.1",
4
4
  "description": "Static Dataflow Analyzer and Program Slicer for the R Programming Language",
5
5
  "engines": {
6
6
  "node": ">=22"