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.

24.8 KB
Raw Blame
//! The environment read without `os.environ`: the variables that a shell or
//! `os.path.expandvars` expand in a string, and those that standard library functions read for the
//! application when it passes them nothing (`getpass.getuser`, `tempfile`, `expanduser`...).
//!
//! A literal string names its variables; a computed string passed to a shell or to `expandvars`
//! is a site. These are not reads: the shell's parameters (`$1`, `$?`, `$$`), the variables that
//! the command assigns itself, text between single quotes, an argument list run without a shell.

use tree_sitter::Node;

use super::Ctx;
use super::ast::{Args, head, last, literal_string, method_call};
use crate::lang::syntax::{line, named_children};
use crate::obligations::Family;

const SHELL_NOT_LITERAL: &str = "a command run by a shell is not a string literal; the environment variables it expands are not enumerated";
const SHELL_MAYBE: &str = "a command may be run by a shell (shell= is not a literal); the environment variables it expands are not enumerated";
const SHELL_ENV: &str = "a command run by a shell is given an environment that is not a literal; which variables it expands from the environment is not known";
const EXPANDVARS_NOT_LITERAL: &str = "a string whose environment variables are expanded (expandvars) is not a literal; they are not enumerated";
const EXPANDUSER_NOT_LITERAL: &str =
    "a path is expanded with expanduser; whether it reads the home directory variable is not known";

const TMP: &[&str] = &["TMPDIR", "TEMP", "TMP"];
const GETTEXT: &[&str] = &["LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"];

/// The argument that replaces the variables read: its position and its keyword.
type Overridden = Option<(usize, &'static str)>;

/// The standard library functions (Python 3.13) that read named variables when the given argument
/// (position, keyword) is missing or is `None`.
const STDLIB_READS: &[(&str, &[&str], Overridden)] = &[
    (
        "getpass.getuser",
        &["LOGNAME", "USER", "LNAME", "USERNAME"],
        None,
    ),
    ("tempfile.gettempdir", TMP, None),
    ("tempfile.gettempdirb", TMP, None),
    ("tempfile.mkstemp", TMP, Some((2, "dir"))),
    ("tempfile.mkdtemp", TMP, Some((2, "dir"))),
    ("tempfile.mktemp", TMP, Some((2, "dir"))),
    ("tempfile.TemporaryDirectory", TMP, Some((2, "dir"))),
    ("tempfile.TemporaryFile", TMP, Some((6, "dir"))),
    ("tempfile.NamedTemporaryFile", TMP, Some((6, "dir"))),
    ("tempfile.SpooledTemporaryFile", TMP, Some((7, "dir"))),
    ("webbrowser.open", &["BROWSER"], None),
    ("webbrowser.open_new", &["BROWSER"], None),
    ("webbrowser.open_new_tab", &["BROWSER"], None),
    ("webbrowser.get", &["BROWSER"], None),
    ("shutil.get_terminal_size", &["COLUMNS", "LINES"], None),
    (
        "locale.getdefaultlocale",
        &["LC_ALL", "LC_CTYPE", "LANG", "LANGUAGE"],
        Some((0, "envvars")),
    ),
    ("gettext.find", GETTEXT, Some((2, "languages"))),
    ("gettext.translation", GETTEXT, Some((2, "languages"))),
    ("gettext.install", GETTEXT, None),
    ("time.tzset", &["TZ"], None),
    // `shutil.which(cmd, mode, path=None)` searches `PATH` (and reads `PATHEXT` on Windows);
    // `os.get_exec_path(env=None)` reads `PATH`. The application asks for the search path
    // itself: an obligation. A process started by its bare name (`subprocess.run(["git"])`,
    // `os.execvp`, `os.spawnlp`) also searches `PATH`, but it is the system that does it to
    // find a program, as it reads `LD_LIBRARY_PATH` or `HOME` for its own needs: the system's
    // surface, not the application's, so nothing is named.
    ("shutil.which", &["PATH", "PATHEXT"], Some((2, "path"))),
    ("os.get_exec_path", &["PATH"], Some((0, "env"))),
];

/// The shells whose `-c` runs the next string.
const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh"];

impl<'t> Ctx<'t> {
    /// The calls that read the environment by expansion or on behalf of the application.
    pub(super) fn expansion_call(&mut self, call: Node<'t>) {
        let Some(function) = call.child_by_field_name("function") else {
            return;
        };
        let args = Args::read(call, self.source);
        let at = line(call);
        if let Some(q) = self.qualify(function) {
            self.qualified_expansion(&q, &args, at);
            return;
        }
        let Some((receiver, method)) = method_call(call, self.source) else {
            return;
        };
        match method.as_str() {
            // `loop.subprocess_shell(factory, cmd)`.
            "subprocess_shell" => {
                let command = args.get(1, "cmd");
                self.shell_command(command, &args, at, "loop.subprocess_shell");
            }
            // `Path("~/x").expanduser()`, `p.expanduser()` in a file that imports pathlib.
            "expanduser" if args.positional.is_empty() && self.imports.has("pathlib") => {
                let literal = (receiver.kind() == "call")
                    .then(|| {
                        receiver
                            .child_by_field_name("function")
                            .and_then(|f| self.qualify(f))
                            .filter(|q| head(q) == "pathlib")
                    })
                    .flatten()
                    .and_then(|_| {
                        Args::read(receiver, self.source)
                            .positional
                            .first()
                            .copied()
                    });
                let names: &[&str] = &["HOME", "USERPROFILE"];
                self.expanduser(literal, names, at, "Path.expanduser", literal.is_none());
            }
            _ => {}
        }
    }

    fn qualified_expansion(&mut self, q: &str, args: &Args<'t>, at: u32) {
        match q {
            "os.path.expandvars" | "posixpath.expandvars" | "ntpath.expandvars" => {
                let windows = q.starts_with("ntpath");
                match args
                    .get(0, "path")
                    .map(|n| (n, literal_string(n, self.source)))
                {
                    Some((_, Some(text))) => {
                        let detail = format!("expanded by {q}");
                        for name in expandvars_names(&text, windows) {
                            self.found(Family::Env, name, at, None, Some(detail.clone()));
                        }
                    }
                    Some((_, None)) => self.unresolved(Family::Env, at, EXPANDVARS_NOT_LITERAL),
                    None => {}
                }
            }
            "os.system" | "os.popen" | "posix.system" | "nt.system" => {
                self.shell_command(
                    args.get(0, "command").or_else(|| args.keyword("cmd")),
                    args,
                    at,
                    q,
                );
            }
            "subprocess.getoutput" | "subprocess.getstatusoutput" => {
                self.shell_command(args.get(0, "cmd"), args, at, q);
            }
            "asyncio.create_subprocess_shell" => {
                self.shell_command(args.get(0, "cmd"), args, at, q);
            }
            "subprocess.run"
            | "subprocess.call"
            | "subprocess.check_call"
            | "subprocess.check_output"
            | "subprocess.Popen" => self.subprocess(args, at, q),
            "asyncio.create_subprocess_exec" => {
                self.shell_list(&args.positional, args, at, q);
            }
            "os.path.expanduser"
            | "pathlib.Path.home"
            | "pathlib.PosixPath.home"
            | "pathlib.WindowsPath.home" => {
                let home = last(q) == "home";
                let path = if home { None } else { args.get(0, "path") };
                self.expanduser(
                    path,
                    &["HOME", "USERPROFILE"],
                    at,
                    q,
                    !home && path.is_none(),
                );
            }
            "posixpath.expanduser" => {
                self.expanduser(args.get(0, "path"), &["HOME"], at, q, false);
            }
            "ntpath.expanduser" => {
                self.expanduser(args.get(0, "path"), &["USERPROFILE"], at, q, false);
            }
            "locale.setlocale" => {
                let empty = args
                    .get(1, "locale")
                    .and_then(|n| literal_string(n, self.source))
                    .is_some_and(|l| l.is_empty());
                if empty {
                    self.unresolved(
                        Family::Env,
                        at,
                        "the locale is taken from the environment (setlocale with \"\"): LC_ALL, the category's LC_* variable and LANG",
                    );
                }
            }
            _ => self.stdlib_read(q, args, at),
        }
    }

    /// A function of `STDLIB_READS`: its variables, unless the argument that replaces them is
    /// given.
    fn stdlib_read(&mut self, q: &str, args: &Args<'t>, at: u32) {
        let Some((_, names, overridden)) = STDLIB_READS.iter().find(|(f, _, _)| *f == q) else {
            return;
        };
        if let Some((index, keyword)) = overridden
            && args
                .get(*index, keyword)
                .is_some_and(|n| self.text(n) != "None")
        {
            return;
        }
        // `which("/usr/bin/git")`: a path with a folder is tried as it is.
        if q == "shutil.which"
            && args
                .get(0, "cmd")
                .and_then(|n| literal_string(n, self.source))
                .is_some_and(|c| c.contains(['/', '\\']))
        {
            return;
        }
        self.recognise(Family::Env, head(q));
        for name in *names {
            let detail = if *name == "PATHEXT" {
                format!("read by {q} on Windows")
            } else {
                format!("read by {q}")
            };
            self.found(Family::Env, (*name).to_string(), at, None, Some(detail));
        }
    }

    /// `expanduser("~/x")` reads the home directory variable; a literal path that does not start
    /// with `~` reads nothing; `~user` goes through the account database.
    fn expanduser(
        &mut self,
        path: Option<Node<'t>>,
        names: &[&str],
        at: u32,
        what: &str,
        unknown: bool,
    ) {
        let tilde = match path {
            None if unknown => {
                self.unresolved(Family::Env, at, EXPANDUSER_NOT_LITERAL);
                return;
            }
            None => true,
            Some(node) => match literal_string(node, self.source) {
                Some(text) => text == "~" || text.starts_with("~/") || text.starts_with("~\\"),
                None => {
                    self.unresolved(Family::Env, at, EXPANDUSER_NOT_LITERAL);
                    return;
                }
            },
        };
        if !tilde {
            return;
        }
        let detail = format!("read by {what}");
        for name in names {
            let detail = if *name == "USERPROFILE" && names.len() > 1 {
                format!("{detail} on Windows")
            } else {
                detail.clone()
            };
            self.found(Family::Env, (*name).to_string(), at, None, Some(detail));
        }
    }

    /// `subprocess.run(...)`: with `shell=True`, the command goes through the shell; without it, a
    /// list `["sh", "-c", "..."]` goes through it too.
    fn subprocess(&mut self, args: &Args<'t>, at: u32, what: &str) {
        let command = args.get(0, "args");
        match args.keyword("shell").map(|s| self.text(s)) {
            Some("True") => self.shell_command(command, args, at, what),
            None | Some("False" | "0" | "None") => {
                if let Some(list) = command.filter(|c| matches!(c.kind(), "list" | "tuple")) {
                    let items: Vec<Node<'t>> = named_children(list)
                        .into_iter()
                        .filter(|n| n.kind() != "comment")
                        .collect();
                    self.shell_list(&items, args, at, what);
                }
            }
            Some(_) => {
                // Computed `shell=`: the string may go through a shell.
                let text = command.and_then(|c| literal_string(c, self.source));
                let expands = match text {
                    Some(t) => {
                        let scan = shell_names(&t);
                        !scan.names.is_empty() || scan.opaque.is_some()
                    }
                    None => command.is_some_and(|c| !matches!(c.kind(), "list" | "tuple")),
                };
                if expands {
                    self.unresolved(Family::Env, at, SHELL_MAYBE);
                }
            }
        }
    }

    /// `["sh", "-c", "cmd"]` (or `create_subprocess_exec("bash", "-c", "cmd")`): the string after
    /// `-c` goes through the shell. Any other list starts a program without a shell.
    fn shell_list(&mut self, items: &[Node<'t>], args: &Args<'t>, at: u32, what: &str) {
        let Some(program) = items.first().and_then(|n| literal_string(*n, self.source)) else {
            return;
        };
        let base = program.rsplit('/').next().unwrap_or(&program);
        if !SHELLS.contains(&base) {
            return;
        }
        let command = items.iter().enumerate().skip(1).find_map(|(i, n)| {
            let option = literal_string(*n, self.source)?;
            (option.starts_with('-') && !option.starts_with("--") && option.contains('c'))
                .then(|| items.get(i + 1).copied())
                .flatten()
        });
        if let Some(command) = command {
            self.shell_command(Some(command), args, at, what);
        }
    }

    /// A command passed to a shell: its variables, or a site.
    fn shell_command(&mut self, command: Option<Node<'t>>, args: &Args<'t>, at: u32, what: &str) {
        let Some(command) = command else {
            return;
        };
        // `shell=True` with a list: the first item is the command, the others are the shell's
        // `$0`, `$1`...
        let command = if matches!(command.kind(), "list" | "tuple") {
            match named_children(command)
                .into_iter()
                .find(|n| n.kind() != "comment")
            {
                Some(first) => first,
                None => return,
            }
        } else {
            command
        };
        let Some(text) = literal_string(command, self.source) else {
            self.unresolved(Family::Env, at, SHELL_NOT_LITERAL);
            return;
        };
        let scan = shell_names(&text);
        if let Some(reason) = scan.opaque {
            self.unresolved(Family::Env, at, reason);
        }
        if scan.names.is_empty() {
            return;
        }
        // `env=` replaces the shell's environment: its literal keys are not read from the
        // application's, and without `**os.environ` none is.
        let mut names = scan.names;
        if let Some(env) = args.keyword("env") {
            if env.kind() != "dictionary" {
                self.unresolved(Family::Env, at, SHELL_ENV);
                return;
            }
            let mut splat = false;
            for pair in named_children(env) {
                match pair.kind() {
                    "pair" => {
                        if let Some(key) = pair
                            .child_by_field_name("key")
                            .and_then(|k| literal_string(k, self.source))
                        {
                            names.retain(|n| *n != key);
                        }
                    }
                    "dictionary_splat" => splat = true,
                    _ => {}
                }
            }
            if !splat {
                return;
            }
        }
        self.recognise(Family::Env, "os");
        let detail = format!("expanded by the shell in {what}");
        for name in names {
            self.found(Family::Env, name, at, None, Some(detail.clone()));
        }
    }
}

/// What a shell command reads from the environment.
#[derive(Debug, Default, PartialEq)]
pub(super) struct Scan {
    /// The variables expanded, in order, without duplicates.
    pub(super) names: Vec<String>,
    /// An expansion that cannot be named: the reason for the site.
    pub(super) opaque: Option<&'static str>,
}

/// The variables that a POSIX shell expands in `command`: `$NAME`, `${NAME}`, `${NAME:-x}`, `~` at
/// the start of a word (`HOME`). Special and positional parameters, text between single quotes,
/// escaped characters and the variables that the command assigns are not reads.
pub(super) fn shell_names(command: &str) -> Scan {
    let chars: Vec<char> = command.chars().collect();
    let assigned = assigned_names(command);
    let mut scan = Scan::default();
    let push = |scan: &mut Scan, name: String| {
        if !assigned.contains(&name) && !scan.names.contains(&name) {
            scan.names.push(name);
        }
    };
    let (mut single, mut double) = (false, false);
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        match c {
            '\\' if !single => {
                i += 2;
                continue;
            }
            '\'' if !double => single = !single,
            '"' if !single => double = !double,
            '~' if !single && !double && word_start(&chars, i) => {
                let next = chars.get(i + 1).copied();
                if next.is_none_or(|n| n == '/' || n.is_whitespace() || ";|&)".contains(n)) {
                    push(&mut scan, "HOME".to_string());
                }
            }
            '%' if !single => {
                let name: String = chars[i + 1..]
                    .iter()
                    .take_while(|c| c.is_ascii_alphanumeric() || **c == '_')
                    .collect();
                let closed = chars.get(i + 1 + name.chars().count()) == Some(&'%');
                if closed
                    && name
                        .chars()
                        .next()
                        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                {
                    scan.opaque.get_or_insert(
                        "a command run by a shell contains %NAME%, which cmd.exe expands on Windows; it is not enumerated",
                    );
                }
            }
            '$' if !single => match chars.get(i + 1) {
                Some('{') => {
                    let inner: String = chars[i + 2..].iter().take_while(|c| **c != '}').collect();
                    let body = inner.strip_prefix('#').unwrap_or(&inner);
                    if body.starts_with('!') {
                        scan.opaque.get_or_insert(
                            "a command run by a shell expands a variable indirectly (${!...}); it is not enumerated",
                        );
                    }
                    let name = identifier(body);
                    if !name.is_empty() {
                        push(&mut scan, name);
                    }
                    i += 2 + inner.chars().count();
                    continue;
                }
                Some('(') if chars.get(i + 2) == Some(&'(') => {
                    scan.opaque.get_or_insert(
                        "a command run by a shell uses arithmetic expansion, which reads variables by bare name; they are not enumerated",
                    );
                }
                Some(n) if n.is_ascii_alphabetic() || *n == '_' => {
                    let rest: String = chars[i + 1..].iter().collect();
                    let name = identifier(&rest);
                    i += 1 + name.chars().count();
                    push(&mut scan, name);
                    continue;
                }
                _ => {}
            },
            _ => {}
        }
        i += 1;
    }
    scan
}

/// The start of `text` that is a shell variable name; empty if it does not start one.
fn identifier(text: &str) -> String {
    let mut chars = text.chars();
    match chars.next() {
        Some(c) if c.is_ascii_alphabetic() || c == '_' => {
            let mut name = c.to_string();
            name.extend(chars.take_while(|c| c.is_ascii_alphanumeric() || *c == '_'));
            name
        }
        _ => String::new(),
    }
}

/// The character `i` starts a shell word (or the value of an assignment).
fn word_start(chars: &[char], i: usize) -> bool {
    i == 0 || chars[i - 1].is_whitespace() || ";|&(=".contains(chars[i - 1])
}

/// The variables that the command assigns itself: `X=1`, `export X=1`, `for X in`, `read X`,
/// `select X in`, `getopts spec X`.
fn assigned_names(command: &str) -> Vec<String> {
    let tokens: Vec<&str> = command
        .split(|c: char| c.is_whitespace() || ";|&()".contains(c))
        .filter(|t| !t.is_empty())
        .collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < tokens.len() {
        let token = tokens[i];
        if let Some((name, _)) = token.split_once('=')
            && !name.is_empty()
            && identifier(name) == name
        {
            out.push(name.to_string());
        }
        match token {
            "for" | "select" => {
                if let Some(next) = tokens.get(i + 1) {
                    out.push(identifier(next));
                }
            }
            "read" => {
                for next in &tokens[i + 1..] {
                    if next.starts_with('-') {
                        continue;
                    }
                    let name = identifier(next);
                    if name.is_empty() || name != *next {
                        break;
                    }
                    out.push(name);
                }
            }
            "getopts" => {
                if let Some(next) = tokens.get(i + 2) {
                    out.push(identifier(next));
                }
            }
            _ => {}
        }
        i += 1;
    }
    out.retain(|n| !n.is_empty());
    out
}

/// The variables that `os.path.expandvars` reads in `text`: `$name` and `${name}` (and `%name%`
/// for `ntpath`), where the name is made of letters, digits and `_` (only those that start with a
/// letter or `_` are kept: `$1` would read a variable named `1`).
pub(super) fn expandvars_names(text: &str, windows: bool) -> Vec<String> {
    let chars: Vec<char> = text.chars().collect();
    let mut out: Vec<String> = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] != '$' && !(windows && chars[i] == '%') {
            i += 1;
            continue;
        }
        let rest: String = chars[i + 1..].iter().collect();
        let name = match chars[i] {
            '$' if rest.starts_with('{') => {
                let inner: String = rest[1..].chars().take_while(|c| *c != '}').collect();
                let closed = rest[1..].chars().nth(inner.chars().count()) == Some('}');
                (closed && identifier(&inner) == inner).then_some(inner)
            }
            '$' => Some(identifier(&rest)),
            '%' if windows => {
                let inner: String = rest.chars().take_while(|c| *c != '%').collect();
                let closed = rest.chars().nth(inner.chars().count()) == Some('%');
                (closed && identifier(&inner) == inner).then_some(inner)
            }
            _ => None,
        };
        if let Some(name) = name.filter(|n| !n.is_empty())
            && !out.contains(&name)
        {
            out.push(name);
        }
        i += 1;
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{expandvars_names, shell_names};

    fn names(command: &str) -> Vec<String> {
        shell_names(command).names
    }

    #[test]
    fn shell_variables_are_named_and_special_parameters_are_not() {
        assert_eq!(names("pg_dump $DATABASE_URL"), ["DATABASE_URL"]);
        assert_eq!(names("echo ${GREETING}"), ["GREETING"]);
        assert_eq!(names("echo ${PORT:-80} ${#NAME}"), ["PORT", "NAME"]);
        assert_eq!(
            names("echo $1 $? $$ $! $# $@ $* $0 $-"),
            Vec::<String>::new()
        );
        assert_eq!(names("echo '$QUOTED' \"$DOUBLE\""), ["DOUBLE"]);
        assert_eq!(names("echo \\$ESCAPED"), Vec::<String>::new());
        assert_eq!(names("X=1; echo $X $Y"), ["Y"]);
        assert_eq!(names("for f in *; do echo $f; done"), Vec::<String>::new());
        assert_eq!(names("read -r line; echo $line"), Vec::<String>::new());
        assert_eq!(names("echo $(date) $(echo $INNER)"), ["INNER"]);
        assert_eq!(names("ls ~/x ~user"), ["HOME"]);
        assert!(shell_names("echo $((COUNT + 1))").opaque.is_some());
        assert!(shell_names("echo %GREETING%").opaque.is_some());
        assert!(shell_names("echo ${!REF}").opaque.is_some());
    }

    #[test]
    fn expandvars_reads_dollar_forms_and_percent_forms_on_windows_only() {
        assert_eq!(
            expandvars_names("$APP_HOME/config.toml", false),
            ["APP_HOME"]
        );
        assert_eq!(expandvars_names("${A}/$B/$1/${C:-x}", false), ["A", "B"]);
        assert_eq!(
            expandvars_names("%USERPROFILE%\\x", false),
            Vec::<String>::new()
        );
        assert_eq!(expandvars_names("%USERPROFILE%\\x", true), ["USERPROFILE"]);
    }
}