Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

22.7 KB
Raw Blame
//! What the file passes as text to an interpreter.
//!
//! - A command launched by a shell (`execSync('pg_dump "$DATABASE_URL"')`, `exec`, `spawn`
//!   with `shell: true`, execa with `shell`, `$` of zx and Bun) reads the environment
//!   variables it expands: a name written in clear is an obligation, a command built at
//!   runtime is a site.
//! - Evaluated code (`eval`, `new Function`, `vm.runInThisContext`, `new Worker(code, { eval:
//!   true })`) can read and declare anything: a site in every surface family.

use std::collections::HashMap;
use std::sync::LazyLock;

use oxc_ast::ast::BindingPattern;
use oxc_ast::ast::{
    Argument, BinaryOperator, CallExpression, Expression, NewExpression, Program,
    TaggedTemplateExpression, TemplateLiteral, VariableDeclarator,
};
use oxc_ast_visit::{Visit, walk};
use oxc_span::Span;
use regex::Regex;

use super::syntax::{as_call, as_member, ident, member_name, method, object_of, prop, text};
use super::{Collector, MAX_DEPTH};
use crate::obligations::Family;

const BUILT_COMMAND: &str =
    "a shell command is built at runtime, so the environment variables it expands cannot be listed";
const MAYBE_SHELL: &str = "a command that names environment variables may run through a shell (its options are not literal), so what it reads cannot be listed";
const INDIRECT: &str =
    "a shell command expands a variable whose name is itself a variable (${!name})";
const EVALUATED: &str = "code is evaluated from a string, so the environment variables, arguments and routes it reads or declares cannot be listed";
const SHELL_DETAIL: &str = "expanded by a shell command";

/// The variables the shell sets itself: not a setting that comes from the environment.
const SHELL_SET: &[&str] = &[
    "BASH",
    "BASHPID",
    "BASH_LINENO",
    "BASH_REMATCH",
    "BASH_SOURCE",
    "BASH_VERSINFO",
    "BASH_VERSION",
    "EPOCHREALTIME",
    "EPOCHSECONDS",
    "EUID",
    "FUNCNAME",
    "GROUPS",
    "HOSTNAME",
    "HOSTTYPE",
    "IFS",
    "LINENO",
    "MACHTYPE",
    "OLDPWD",
    "OPTARG",
    "OPTIND",
    "OSTYPE",
    "PIPESTATUS",
    "PPID",
    "PS1",
    "PS2",
    "PS3",
    "PS4",
    "PWD",
    "RANDOM",
    "REPLY",
    "SECONDS",
    "SHLVL",
    "SRANDOM",
    "UID",
];

/// The functions of `vm` that run code given as text.
const VM_RUNNERS: &[&str] = &[
    "runInThisContext",
    "runInNewContext",
    "runInContext",
    "compileFunction",
];

/// The classes of `vm` built on code given as text.
const VM_CLASSES: &[&str] = &["Script", "SourceTextModule"];

/// How a function launches its command.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Launcher {
    /// Always through a shell: `exec`, `execSync`, `exec` of shelljs.
    Shell,
    /// Through a shell only with the `shell` option: `spawn`, `execFile`, execa, cross-spawn.
    ShellOption,
}

/// The names in a shell text: the variables expanded, and whether it expands one by
/// indirection.
#[derive(Default, Debug, PartialEq, Eq)]
pub(super) struct ShellVars {
    pub names: Vec<String>,
    pub indirect: bool,
}

/// A shell variable name starts at `chars[start]`: its length.
fn name_len(chars: &[char], start: usize) -> usize {
    let mut end = start;
    while end < chars.len()
        && (chars[end] == '_' || chars[end].is_ascii_alphanumeric())
        && !(end == start && chars[end].is_ascii_digit())
    {
        end += 1;
    }
    end - start
}

/// `NAME=value` at the head of a word (`X=1; ...`, `export X=1`, `X+=1`).
static ASSIGNED: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?:^|[\s;&|(`{])([A-Za-z_][A-Za-z0-9_]*)\+?=").expect("valid regex")
});

static FOR_LOOP: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\bfor\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\b").expect("valid regex"));

static READ: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\bread\b([^;&|\n]*)").expect("valid regex"));

/// The names assigned in the command itself (`X=1; echo $X`, `for f in ...`, `read a b`):
/// they are not reads of the environment.
fn assigned_names(command: &str) -> Vec<String> {
    let mut names: Vec<String> = ASSIGNED
        .captures_iter(command)
        .chain(FOR_LOOP.captures_iter(command))
        .filter_map(|c| c.get(1).map(|m| m.as_str().to_string()))
        .collect();
    for capture in READ.captures_iter(command) {
        let Some(rest) = capture.get(1) else { continue };
        let mut skip_next = false;
        for token in rest.as_str().split_whitespace() {
            if skip_next {
                skip_next = false;
            } else if let Some(option) = token.strip_prefix('-') {
                // The options of `read` that take a value.
                skip_next = option
                    .chars()
                    .last()
                    .is_some_and(|c| matches!(c, 'p' | 'd' | 'n' | 'N' | 't' | 'u' | 'a' | 'i'));
            } else {
                let name: String = token
                    .chars()
                    .take_while(|c| *c == '_' || c.is_ascii_alphanumeric())
                    .collect();
                if !name.is_empty() {
                    names.push(name);
                }
            }
        }
    }
    names
}

/// The variables a POSIX shell text expands: `$NAME`, `${NAME}`, `${NAME:-default}`,
/// `${#NAME}`, outside single quotes and outside `\$`. The special parameters (`$1`, `$?`,
/// `$$`, `$@`), the `$(...)` substitution itself and the names assigned in the command are not
/// environment variables.
pub(super) fn shell_vars(command: &str) -> ShellVars {
    let chars: Vec<char> = command.chars().collect();
    let assigned = assigned_names(command);
    let mut out = ShellVars::default();
    let push = |name: String, out: &mut ShellVars| {
        if name != "_"
            && !SHELL_SET.contains(&name.as_str())
            && !assigned.contains(&name)
            && !out.names.contains(&name)
        {
            out.names.push(name);
        }
    };
    let (mut single, mut double) = (false, false);
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if single {
            if c == '\'' {
                single = false;
            }
            i += 1;
            continue;
        }
        match c {
            '\\' => i += 2,
            '\'' if !double => {
                single = true;
                i += 1;
            }
            '"' => {
                double = !double;
                i += 1;
            }
            '$' => {
                let next = chars.get(i + 1).copied();
                match next {
                    Some('{') => {
                        let mut j = i + 2;
                        let mut indirect = false;
                        match chars.get(j) {
                            // `${!name}`: the variable read is named by another one.
                            Some('!') => {
                                indirect = true;
                                j += 1;
                            }
                            // `${#name}` is the length of `name`; `${#}` the number of arguments.
                            Some('#') if chars.get(j + 1) != Some(&'}') => j += 1,
                            _ => {}
                        }
                        let len = name_len(&chars, j);
                        if indirect && len > 0 {
                            out.indirect = true;
                        } else if len > 0 {
                            push(chars[j..j + len].iter().collect(), &mut out);
                        }
                        i = j + len;
                    }
                    // `$'...'`: a C-style string, without expansion.
                    Some('\'') if !double => {
                        single = true;
                        i += 2;
                    }
                    // `$NAME`; `$1`, `$?`, `$$`, `$(` are not names.
                    Some(_) => {
                        let len = name_len(&chars, i + 1);
                        if len > 0 {
                            push(chars[i + 1..=i + len].iter().collect(), &mut out);
                        }
                        i += 1 + len;
                    }
                    None => i += 1,
                }
            }
            _ => i += 1,
        }
    }
    out
}

/// The text of a command and whether it depends on computed values. The computed parts are
/// replaced by a control character, which is neither a name nor a quote.
fn command_text(c: &Collector, expr: &Expression<'_>, depth: usize) -> (String, bool) {
    const HOLE: &str = "\u{1}";
    if depth > MAX_DEPTH {
        return (HOLE.to_string(), true);
    }
    if let Some(t) = text(expr) {
        return (t, false);
    }
    match expr.get_inner_expression() {
        Expression::TemplateLiteral(t) => (template_text(t), !t.expressions.is_empty()),
        Expression::BinaryExpression(b) if b.operator == BinaryOperator::Addition => {
            let (left, l) = command_text(c, &b.left, depth + 1);
            let (right, r) = command_text(c, &b.right, depth + 1);
            (format!("{left}{right}"), l || r)
        }
        Expression::Identifier(id) if !c.bindings.is_ambiguous(id.name.as_str()) => {
            match c.constants.string(id.name.as_str()) {
                Some(Some(t)) => (t.to_string(), false),
                _ => (HOLE.to_string(), true),
            }
        }
        _ => (HOLE.to_string(), true),
    }
}

/// The written parts of a template, its expressions replaced by a hole.
fn template_text(t: &TemplateLiteral<'_>) -> String {
    t.quasis
        .iter()
        .map(|q| q.value.raw.as_str())
        .collect::<Vec<_>>()
        .join("\u{1}")
}

/// What a launcher's `shell` option says: `Some(true)` a shell, `Some(false)` none, `None`
/// unknown (options in a variable, spread, computed value).
fn shell_option(arguments: &[Argument<'_>]) -> Option<bool> {
    let rest = arguments.get(1..).unwrap_or_default();
    let Some(options) = rest
        .iter()
        .rev()
        .find_map(|a| a.as_expression().and_then(object_of))
    else {
        // No options object written: a computed argument other than a list can be one.
        let unknown = rest.iter().any(|a| match a.as_expression() {
            Some(e) => !matches!(
                e.get_inner_expression(),
                Expression::ArrayExpression(_)
                    | Expression::StringLiteral(_)
                    | Expression::TemplateLiteral(_)
            ),
            None => true,
        });
        return if unknown { None } else { Some(false) };
    };
    match prop(options, "shell") {
        Some(value) => match value.get_inner_expression() {
            Expression::BooleanLiteral(b) => Some(b.value),
            Expression::StringLiteral(_) => Some(true),
            _ => None,
        },
        None if options.properties.iter().any(|p| p.is_spread()) => None,
        None => Some(false),
    }
}

pub(super) fn find(collector: &mut Collector, program: &Program<'_>) {
    let mut aliases = AliasReader {
        c: collector,
        aliases: HashMap::new(),
    };
    // An alias of an alias can be declared before it: read again until nothing changes.
    for _ in 0..4 {
        let before = aliases.aliases.len();
        aliases.visit_program(program);
        if aliases.aliases.len() == before {
            break;
        }
    }
    let aliases = aliases.aliases;
    let mut finder = Finder {
        c: collector,
        aliases,
    };
    finder.visit_program(program);
}

/// `const run = promisify(exec)`, `const sh = execSync`: other names for a launcher.
struct AliasReader<'c> {
    c: &'c Collector,
    aliases: HashMap<String, Launcher>,
}

impl<'a> Visit<'a> for AliasReader<'_> {
    fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) {
        if let (BindingPattern::BindingIdentifier(id), Some(init)) = (&it.id, &it.init) {
            let name = id.name.as_str();
            let target = match as_call(init) {
                Some(call) if is_promisify(self.c, call) => {
                    call.arguments.first().and_then(|a| a.as_expression())
                }
                Some(_) => None,
                None => Some(init),
            };
            if !self.c.bindings.is_ambiguous(name)
                && let Some(launcher) = target.and_then(|t| launcher(self.c, &self.aliases, t))
            {
                self.aliases.insert(name.to_string(), launcher);
            }
        }
        walk::walk_variable_declarator(self, it);
    }
}

/// `promisify(f)` or `util.promisify(f)`.
fn is_promisify(c: &Collector, call: &CallExpression<'_>) -> bool {
    match method(call).as_deref() {
        Some("promisify") => call
            .callee
            .as_member_expression()
            .is_some_and(|m| c.is_module(m.object(), "util")),
        Some(_) => false,
        None => ident(&call.callee)
            .is_some_and(|name| c.imports.local(name) == Some(("util", Some("promisify")))),
    }
}

/// How the called function launches its command, if it is a known launcher.
fn launcher(
    c: &Collector,
    aliases: &HashMap<String, Launcher>,
    callee: &Expression<'_>,
) -> Option<Launcher> {
    let callee = callee.get_inner_expression();
    if let Some(name) = ident(callee) {
        if c.bindings.is_ambiguous(name) {
            return None;
        }
        if let Some(launcher) = aliases.get(name) {
            return Some(*launcher);
        }
        let (package, imported) = c.imports.local(name)?;
        return by_name(package, imported);
    }
    let member = as_member(callee)?;
    let name = member_name(member)?;
    let object = member.object();
    ["child_process", "execa", "cross-spawn", "shelljs"]
        .into_iter()
        .find(|package| c.is_module(object, package))
        .and_then(|package| by_name(package, Some(name.as_str())))
        // `execa.sync(...)` of an `execa` imported as default (execa 5).
        .or_else(|| {
            let root = ident(object)?;
            let (package, imported) = c.imports.local(root)?;
            (package == "execa" && matches!(imported, None | Some("execa")))
                .then_some(Launcher::ShellOption)
                .or_else(|| {
                    (package == "cross-spawn" && name == "sync").then_some(Launcher::ShellOption)
                })
        })
}

/// A launcher by its package and the imported name (`None`: default export).
fn by_name(package: &str, imported: Option<&str>) -> Option<Launcher> {
    match (package, imported) {
        ("child_process", Some("exec" | "execSync")) | ("shelljs", Some("exec")) => {
            Some(Launcher::Shell)
        }
        ("child_process", Some("spawn" | "spawnSync" | "execFile" | "execFileSync"))
        | ("cross-spawn", _) => Some(Launcher::ShellOption),
        (
            "execa",
            None
            | Some(
                "execa" | "execaSync" | "execaCommand" | "execaCommandSync" | "sync" | "command"
                | "commandSync",
            ),
        ) => Some(Launcher::ShellOption),
        _ => None,
    }
}

struct Finder<'c> {
    c: &'c mut Collector,
    aliases: HashMap<String, Launcher>,
}

impl Finder<'_> {
    /// The names of a command launched by a shell; a site if it is built at runtime.
    fn shell_command(&mut self, text: &str, computed: bool, span: Span) {
        let vars = shell_vars(text);
        for name in vars.names {
            self.c.add(
                Family::Env,
                name,
                span,
                None,
                Some(SHELL_DETAIL.to_string()),
            );
        }
        if vars.indirect {
            self.c.unresolved(Family::Env, span, INDIRECT);
        }
        if computed {
            self.c.unresolved(Family::Env, span, BUILT_COMMAND);
        }
    }

    fn launch(&mut self, it: &CallExpression<'_>) {
        let Some(kind) = launcher(self.c, &self.aliases, &it.callee) else {
            return;
        };
        let Some(first) = it.arguments.first() else {
            return;
        };
        let shell = match kind {
            Launcher::Shell => Some(true),
            Launcher::ShellOption => shell_option(&it.arguments),
        };
        if shell == Some(false) {
            return;
        }
        // The command, then the argument list the shell receives joined to it.
        let (mut command, mut computed) = match first.as_expression() {
            Some(e) => command_text(self.c, e, 0),
            None => ("\u{1}".to_string(), true),
        };
        if kind == Launcher::ShellOption
            && let Some(Expression::ArrayExpression(array)) = it
                .arguments
                .get(1)
                .and_then(|a| a.as_expression())
                .map(Expression::get_inner_expression)
        {
            for element in &array.elements {
                let (part, c) = match element.as_expression() {
                    Some(e) => command_text(self.c, e, 0),
                    None => ("\u{1}".to_string(), true),
                };
                command = format!("{command} {part}");
                computed |= c;
            }
        }
        if shell.is_none() {
            // Maybe a shell: a site if the written command names variables.
            let vars = shell_vars(&command);
            if !vars.names.is_empty() || vars.indirect {
                self.c.unresolved(Family::Env, it.span, MAYBE_SHELL);
            }
            return;
        }
        self.shell_command(&command, computed, it.span);
    }

    /// `$\`...\`` of zx or Bun: a shell whose inserted values are escaped, so only the written
    /// parts expand variables.
    fn tagged(&mut self, it: &TaggedTemplateExpression<'_>) {
        if self.is_shell_tag(&it.tag) {
            self.shell_command(&template_text(&it.quasi), false, it.span);
        }
    }

    fn is_shell_tag(&self, tag: &Expression<'_>) -> bool {
        let tag = tag.get_inner_expression();
        if let Some(name) = ident(tag) {
            if name != "$" || self.c.bindings.is_ambiguous(name) {
                return false;
            }
            return match self.c.imports.local(name) {
                Some(("zx" | "bun", _)) => true,
                Some(_) => false,
                // The global `$` of `zx/globals` (or of a script launched by zx).
                None => !self.c.bindings.is_bound(name) && self.c.imports.has(&["zx"]),
            };
        }
        // `Bun.$`, `$.sync` of zx.
        if let Some(member) = as_member(tag) {
            return (ident(member.object()) == Some("Bun")
                && member_name(member).as_deref() == Some("$"))
                || self.is_shell_tag(member.object());
        }
        // `$({ cwd })` of zx; `$({ shell: true })` of execa.
        as_call(tag).is_some_and(|call| {
            if self.is_shell_tag(&call.callee) {
                return true;
            }
            ident(&call.callee).is_some_and(|name| {
                self.c.imports.local(name) == Some(("execa", Some("$")))
                    && shell_option_at(&call.arguments, 0) == Some(true)
            })
        })
    }

    /// `eval(...)`, `Function(...)`, `vm.runInThisContext(...)`.
    fn evaluated_call(&mut self, it: &CallExpression<'_>) {
        let mut callee = it.callee.get_inner_expression();
        // `(0, eval)(code)`: an indirect call, evaluated just the same.
        if let Expression::SequenceExpression(sequence) = callee
            && let Some(last) = sequence.expressions.last()
        {
            callee = last.get_inner_expression();
        }
        let evaluated = match ident(callee) {
            Some(name @ ("eval" | "Function")) => !self.c.bindings.is_bound(name),
            Some(name) => {
                !self.c.bindings.is_ambiguous(name)
                    && self.c.imports.local(name).is_some_and(|(p, i)| {
                        p == "vm" && i.is_some_and(|i| VM_RUNNERS.contains(&i))
                    })
            }
            None => as_member(callee).is_some_and(|m| {
                let name = member_name(m);
                match name.as_deref() {
                    Some("eval") => matches!(
                        ident(m.object()),
                        Some("globalThis" | "global" | "window" | "self")
                    ),
                    Some(n) if VM_RUNNERS.contains(&n) => self.c.is_module(m.object(), "vm"),
                    _ => false,
                }
            }),
        };
        if evaluated && !it.arguments.is_empty() {
            self.evaluated(it.span);
        }
    }

    /// `new Function(code)`, `new vm.Script(code)`, `new Worker(code, { eval: true })`.
    fn evaluated_new(&mut self, it: &NewExpression<'_>) {
        let callee = it.callee.get_inner_expression();
        let class = match ident(callee) {
            Some("Function") if !self.c.bindings.is_bound("Function") => true,
            Some(name) if !self.c.bindings.is_ambiguous(name) => self
                .c
                .imports
                .local(name)
                .is_some_and(|(p, i)| p == "vm" && i.is_some_and(|i| VM_CLASSES.contains(&i))),
            _ => as_member(callee).is_some_and(|m| {
                member_name(m).is_some_and(|n| VM_CLASSES.contains(&n.as_str()))
                    && self.c.is_module(m.object(), "vm")
            }),
        };
        let worker_eval = last_name_is(callee, "Worker")
            && it
                .arguments
                .get(1)
                .and_then(|a| a.as_expression())
                .and_then(object_of)
                .and_then(|o| prop(o, "eval"))
                .is_some_and(|v| !matches!(v.get_inner_expression(), Expression::BooleanLiteral(b) if !b.value));
        if (class && !it.arguments.is_empty()) || worker_eval {
            self.evaluated(it.span);
        }
    }

    fn evaluated(&mut self, span: Span) {
        for family in [Family::Env, Family::Command, Family::Flag, Family::Route] {
            self.c.unresolved(family, span, EVALUATED);
        }
    }
}

fn last_name_is(expr: &Expression<'_>, name: &str) -> bool {
    match ident(expr) {
        Some(n) => n == name,
        None => as_member(expr).and_then(member_name).as_deref() == Some(name),
    }
}

/// The `shell` option of the object at index `index`.
fn shell_option_at(arguments: &[Argument<'_>], index: usize) -> Option<bool> {
    let options = arguments.get(index)?.as_expression().and_then(object_of)?;
    match prop(options, "shell")?.get_inner_expression() {
        Expression::BooleanLiteral(b) => Some(b.value),
        Expression::StringLiteral(_) => Some(true),
        _ => None,
    }
}

impl<'a> Visit<'a> for Finder<'_> {
    fn visit_call_expression(&mut self, it: &CallExpression<'a>) {
        self.launch(it);
        self.evaluated_call(it);
        walk::walk_call_expression(self, it);
    }

    fn visit_new_expression(&mut self, it: &NewExpression<'a>) {
        self.evaluated_new(it);
        walk::walk_new_expression(self, it);
    }

    fn visit_tagged_template_expression(&mut self, it: &TaggedTemplateExpression<'a>) {
        self.tagged(it);
        walk::walk_tagged_template_expression(self, it);
    }
}