Skip to content

Run scripts of any file extension in PATHEXT on Windows - #15611

Merged
fdncred merged 4 commits into
nushell:mainfrom
hfrentzel:respect_pathext
Apr 24, 2025
Merged

fdncred merged 4 commits into
nushell:mainfrom
hfrentzel:respect_pathext

Conversation

@hfrentzel

Copy link
Copy Markdown
Contributor

Description

On Windows, I would like to be able to call a script directly in nushell and have that script be found in the PATH and run based on filetype associations and PATHEXT.

There have been previous discussions related to this feature, see #6440 and #15476. The latter issue is only a few weeks old, and after taking a look at it and the resultant PR I found that currently nushell is hardcoded to support only running nushell (.nu) scripts in this way.

This PR seeks to make this functionality more generic. Instead of checking that the file extension is explicitly NU, it instead checks that it is not one of COM, EXE, BAT, CMD, or PS1. The first four of these are extensions that Windows can figure out how to run on its own. This is implied by the output of ftype for any of these extensions, which shows that files are just run without a calling command anyway.

>ftype batfile
batfile="%1" %*

PS1 files are ignored because they are handled as a special in later logic.

In implementing this I initially tried to fetch the value of PATHEXT and confirm that the file extension was indeed in PATHEXT. But I determined that because which() respects PATHEXT, this would be redundant; any executable that is found by which is already going to have an extension in PATHEXT. It is thus only necessary to check that it isn't one of the few extensions that should be called directly, without the use of cmd.exe.

There are some small formatting changes to run_external.rs in the PR as a result of running cargo fmt that are not entirely related to the code I modified. I can back out those changes if that is desired.

User-Facing Changes

Behavior for .nu scripts will not change. Users will still need to ensure they have PATHEXT and filetype associations set correctly for them to work, but this will now also apply to scripts of other types.

The `which()` on line 94 accounts for PATHEXT, so comparing against
PATHEXT again is redundant. We need only check that the file extension
is not one which Windows can run directly.
let paths = nu_engine::env::path_str(engine_state, stack, call.head)?;

// On Windows, the user could have run the cmd.exe built-in "assoc" command
// Example: "assoc .nu=nuscript" and then run the cmd.exe built-in "ftype" command

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to keep these examples because they're not commonly known, even by seasoned windows users.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure thing. My intent was to update the comment to reflect that this behavior is now generic, no longer just limited to nushell scripts. But keeping an explicit example in there makes sense to me.

@fdncred fdncred left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I generally agree with what you're doing here. I just want to change the comments around these changes for clarity. This subject is a little tricky, so I want it to be as clear as possible.

@hfrentzel
hfrentzel requested a review from fdncred April 21, 2025 22:02
@fdncred

fdncred commented Apr 22, 2025

Copy link
Copy Markdown
Contributor

I plan on looking at this closer tomorrow on my windows systems.

@fdncred fdncred left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've looked at this again. The comments are well enough now. I also tested with a nu script, a ps1 script, and a bat file. The nu script and bat file worked well when invoking in the same folder without the extension, but the ps1 file would not execute and I'm not sure why. It's also broken this way before this PR, so I'm not laying this blame on this PR.

To recap:

  1. t.nu should be executable with t or .\t on windows, and it works
  2. b.bat should be executable with b or .\b on windows, and it works
  3. p.ps1 should be executable with p or .\p on windows, and it does not work

We can save 3 for a later PR but it would be nice if it worked. I should be executable without the extension, right?

@fdncred
fdncred dismissed their stale review April 23, 2025 13:04

fixed

@sholderbach

Copy link
Copy Markdown
Member

Just a sanity check from a security perspective:
Are there any likely cases where things could suddenly be executed without the user expecting them to be?
I am not super up-to-date on the resolution rules in the Windows world only that it for CMD.exe it is significantly more relaxed compared to POSIX (no concept of chmod +x, things in the current directory execute directly without the need to explicitly qualifying as a path (POSIX land ./executable if not on $env.PATH))

I assume we can consider the components of PATH and PATHEXT to be trusted to the same level as anything the user intends to run. So my primary concern would be if any invocation in an arbitrary directory could shadow a trusted executable in the PATH with something that the user doesn't expect to be executable?

@hfrentzel

Copy link
Copy Markdown
Contributor Author
  1. p.ps1 should be executable with p or .\p on windows, and it does not work

We can save 3 for a later PR but it would be nice if it worked. I should be executable without the extension, right?

I looked into this. First of all, make sure that .PS1 is in your PATHEXT. I don't think it is by default, at least it was not on my machine.

Even after adding it, I still got an error. I think the error is occurring in the canonicalize_with call at

canonicalize_with(&expanded_name, cwd).map_err(|err| {

This function errors if the passed in file does not exist. It doesn't do anything fancy with PATHEXT, so it is unable to rectify that the script without the file extension is actually present where it is expected to be.

@fdncred

fdncred commented Apr 23, 2025

Copy link
Copy Markdown
Contributor

You're right, .PS1 wasn't in my PATHEXT. So, it seems to be working as expected.

@sholderbach sholderbach added A:external-commands Issues related to external commands platform:windows Issues which are specific to Windows labels Apr 23, 2025
@hfrentzel

hfrentzel commented Apr 23, 2025 •

Copy link
Copy Markdown
Contributor Author

I assume we can consider the components of PATH and PATHEXT to be trusted to the same level as anything the user intends to run. So my primary concern would be if any invocation in an arbitrary directory could shadow a trusted executable in the PATH with something that the user doesn't expect to be executable?

@sholderbach Your concern is valid. I can confirm that a script in the CWD could shadow an executable on the path. For example, I have .PY in my PATHEXT, and if I create a nu.py file, both nu and .\nu will run that instead of the nushell in my PATH.

I checked how this is handled in powershell. Powershell will not run a script in the CWD unless it is started with .\, regardless of whether a file extension is present. This seems to be the ideal behavior, as including or not including .\ can make it clear whether the user it try to run something off the path or in the CWD.

The shadowing behavior is currently how nushell behaves for other file extensions, such as .exe, .cmd or .bat, and even .nu if its in PATHEXT. It looks like this was intentional and is caused by prepending the CWD to PATH when running which on Windows.

let paths = format!("{};{}", cwd.display(), paths);

Looking a little through git history, I think this was done to replicate the behavior of cmd.exe which, unlike powershell, will run a script or executable in the CWD regardless of whether .\ is included or not.

I think there are two ways to proceed:

  1. Leave as is. The shadowing behavior is already present in nushell for all the file extensions it can currently handle. This seems to have been done intentionally to behave like cmd.exe, and therefore it should continue to behave like cmd.exe for any file extension a user has added to PATHEXT.
  2. Remove the logic that prepends CWD to PATH when calling which on windows. This would get rid of the shadowing risk, as users would have to include .\ to run a command in the current directory. This is how powershell behaves, and it is very possible that powershell diverged from the cmd.exe behavior because of this exact shadowing risk.

I think (2) is the better way to go, but ultimately I don't think I should be the one making that decision. The one hang-up with (2) is that it could break existing functionality for users who are used to running scripts or executables from their current directory without .\, although users would be able to opt-in to this old functionality with $env.PATH ++= [".\\"].

Let me know your thoughts. I'm happy to go either way.

@fdncred

fdncred commented Apr 23, 2025

Copy link
Copy Markdown
Contributor

I'd leave it as is. I believe this issue came up when I made these changes last time. It was intended to work as cmd.exe does on Windows.

@sholderbach

Copy link
Copy Markdown
Member

Thanks for the explanation @hfrentzel !

I agree with your assessment that this PR doesn't make anything existing worse. So sign off from me on that front for the PR.

I agree with you that I prefer the choices that PowerShell made or are closer to POSIX. But if we get a majority for that opinion we should do that in a separate PR. I think CMD.exe has bad defaults among several angles, not just those security nightmares in the form of open barn doors.

@fdncred

fdncred commented Apr 24, 2025

Copy link
Copy Markdown
Contributor

Ok, let's run with this update. Thanks!

@fdncred
fdncred merged commit b33f4b7 into nushell:main Apr 24, 2025
@github-actions github-actions Bot added this to the v0.104.0 milestone Apr 24, 2025
fdncred pushed a commit that referenced this pull request Nov 23, 2026
… (#19636)

## Description

Fixes #19584.

On Windows, a script that runs through its file association (for example
a `.nu`, `.py` or `.vbs` file whose extension is in `PATHEXT`) worked as
`.\script.nu` but failed as `./script.nu`:

```
> ./test.nu
'.' is not recognized as an internal or external command,
operable program or batch file.
```

**Cause:** for these scripts `run-external` launches `cmd.exe /D /C
<name>` so Windows applies the file association. The name was passed
exactly as typed, and `cmd.exe` treats `/` as a switch character, so it
read `./test.nu` as the command `.` followed by the switch `/test.nu`.

**Fix:** for file-associated scripts, the name as typed is normalized
before it's handed to `cmd.exe`. The new helper `cmd_script_path`
re-joins the name's path components, which turns every `/` into `\` and
drops redundant `.` components while keeping a leading `.`, e.g.
`./sub/./test.nu` → `.\sub\test.nu`. Only the typed name reaches
cmd.exe, never the cwd or a PATH directory, so spaces or characters like
`&` in those directories can't affect cmd.exe's parsing.

CMD internal commands (`echo`, `assoc`, `start`, …) still receive the
name as typed, so their behaviour is unchanged. `.exe`, `.com`, `.bat`,
`.cmd` and `.ps1` files don't go through this code path.

### Before / after

Tested on Windows 10 Pro 19045 with `.vbs` files, which Windows
associates with WScript by default (`.VBS` is in the default `PATHEXT`).
The test script writes a marker file, so `RAN` means it really executed.

Before (0.116.1 release; `main` at 594dd47 behaves the same):

```
.> .\hello.vbs                     => RAN
.> ./hello.vbs                     => FAILED '.' is not recognized as an internal or external command,
.> ./hello                         => FAILED '.' is not recognized as an internal or external command,
.> ./sub/hello.vbs                 => FAILED '.' is not recognized as an internal or external command,
.> ./sub/./hello.vbs               => FAILED '.' is not recognized as an internal or external command,
.> "./sub dir/hello.vbs"           => RAN
John Doe> .\hello.vbs "a b"        => RAN
John Doe> ./hello.vbs "a b"        => FAILED '.' is not recognized as an internal or external command,
R&D> .\hello.vbs                   => RAN
x&whoami&y> .\hello.vbs            => RAN
^echo cmd-builtin-ok               => cmd-builtin-ok
```

After (this PR):

```
.> .\hello.vbs                     => RAN
.> ./hello.vbs                     => RAN
.> ./hello                         => RAN
.> ./sub/hello.vbs                 => RAN
.> ./sub/./hello.vbs               => RAN
.> "./sub dir/hello.vbs"           => RAN
John Doe> .\hello.vbs "a b"        => RAN
John Doe> ./hello.vbs "a b"        => RAN
R&D> .\hello.vbs                   => RAN
x&whoami&y> .\hello.vbs            => RAN
^echo cmd-builtin-ok               => cmd-builtin-ok
```

### Tests

- New Windows integration tests in
`crates/nu-command/tests/commands/run_external.rs` (`mod
file_association`), using `.vbs` (default WScript association, no
registry change). Each prefix (bare, `^`, `run-external`) × script is
its own rstest case:
- `can_run_file_associated_scripts_with_forward_slashes`: `./hello.vbs`,
`./hello`, `./sub/hello.vbs`, `./sub/./hello.vbs`, `.\sub\hello.vbs` (15
cases)
- `can_run_file_associated_scripts_in_dirs_with_cmd_special_chars`: cwd
`John Doe` / `R&D`, with `.\hello.vbs`, `./hello.vbs`, `.\hello.vbs "a
b"` (18 cases)
- Checked that they catch the bugs: against `main` the 18 forward-slash
cases fail, and against the first version of this PR (resolved path) the
special-chars cases fail.
- Windows-only unit test `cmd_script_path_uses_backslashes` (7 rstest
cases) for the normalization itself.
- Ran locally on Windows:
  - `cargo fmt --all -- --check`
- `cargo clippy -p nu-command --all-targets -- -D warnings -D
clippy::unwrap_used -D clippy::unchecked_time_subtraction`
  - `cargo test -p nu-command --lib run_external` (10 passed)
- `cargo test -p nu-command --test tests -- commands::run_external` (124
passed, 3 ignored Linux-only)

## User-facing changes (Release notes)

Fixed an issue on Windows where running a file-associated script with a
forward-slash path such as `./script.nu` failed with `'.' is not
recognized as an internal or external command`, while `.\script.nu`
worked.

## Additional notes

- Fixes #19584
- Related: #6440, #15611 (running scripts through their file
association)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A:external-commands Issues related to external commands platform:windows Issues which are specific to Windows

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants