Skip to content

Fix variable interpolation in .env files loaded through envFile - #14828

Open
Abdelhadi Salmaoui (abdelhadi703) wants to merge 7 commits into
microsoft:mainfrom
abdelhadi703:fix/envfile-interpolation
Open

Abdelhadi Salmaoui (abdelhadi703) wants to merge 7 commits into
microsoft:mainfrom
abdelhadi703:fix/envfile-interpolation

Conversation

@abdelhadi703

@abdelhadi703 Abdelhadi Salmaoui (abdelhadi703) commented Oct 10, 2026 •

Copy link
Copy Markdown

.env files are supposed to support variable interpolation, but when such a file is
loaded through envFile, the values keep their ${...} references and the variable is
never substituted.

With a file like

USER=admin
EMAIL=${USER}@example.org

EMAIL came out as the literal ${USER}@example.org. Later, when the debug
configuration gets expanded, ${USER} is looked up as a launch.json variable, isn't
found, and prints "Invalid variable reference ${USER} in string". The env var that was
meant to land in the debuggee doesn't.

I made ParsedEnvironmentFile resolve ${VAR} while it parses each line, against the
variables already read from the file plus the process environment. A reference to a name we
don't know is left untouched, so ${workspaceFolder} and the other launch.json variables
keep working exactly as before.

Only a reference the value actually asked to expand is expanded. A single-quoted value and a
\${VAR} reference are literal in dotenv, and both were literal here before this change, so
they stay literal now.

Keeping them literal takes more than emitting them unchanged. This parser's output goes through
expandAllStrings immediately afterwards (configurationProvider.expand), which substitutes
every ${...} it knows and warns about the rest, so a bare ${VAR} either got replaced from
the launch configuration or printed the same "Invalid variable reference" warning the issue is
about. Both literal forms are written back as ${dollar}{VAR} instead -- the one form that
expansion leaves alone and collapses to a plain $ once it is done (expand.ts), so the
debuggee is the only place that sees the literal.

Seven tests were added to the existing ParsedEnvironmentFile suite: a reference to a variable
defined earlier in the same file, a reference coming from the initial environment, an unknown
reference staying literal, a reference resolved from the process environment, the two literal
forms, and a resolved reference still coming out bare.

Testing: ran the ParsedEnvironmentFile suite against the parser alone, compiled with the
repo's TypeScript and a local vscode-nls stand-in (mocha 10 does not start on Node 26, so the
compiled file runs under a short TDD shim). 14 passing with this change.

I also ran that output through the expansion rule from expand.ts, which is what the extension
does next. Both literal forms reach the debuggee as ${USER} with no warning, while
${workspaceFolder} still resolves from the debug configuration. On the previous commit of this
branch the single-quoted value came out as admin@example.org, because the expansion took
${USER} from the launch variables.

The path through extendDebugConfiguration itself needs the extension host and the packages
from the private feed, so it is not covered here.

Fixes #13781.

Copilot AI 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.

🟡 Changes recommended

Interpolation incorrectly expands quoted or escaped literals, and the tests are incomplete and environment-dependent.

2 open findings
What changed in this PR

Adds dotenv-style ${VAR} interpolation for debugger envFile parsing.

Changes:

  • Resolves references from prior entries and the process environment.
  • Preserves unknown references.
  • Adds tests and changelog documentation.
File Description
Extension/​src/​Debugger/​ParsedEnvironmentFile.ts Implements interpolation.
Extension/​test/​scenarios/​SingleRootProject/​tests/​ParsedEnvironmentFile.test.ts Adds interpolation tests.
Extension/​CHANGELOG.md Documents the fix.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@abdelhadi703

Abdelhadi Salmaoui (abdelhadi703) commented Oct 13, 2026 •

Copy link
Copy Markdown
Author

Both addressed in 66ea67b.

The quotes came off before the references were resolved, so you are right on both counts: VALUE='${SECRET}' was expanded, and \${SECRET} lost its meaning while keeping its backslash. Both are literal in dotenv, and both were literal here before the interpolation existed, so they stay as written now -- the backslash is dropped, leaving the text ${VAR}. Two tests cover the two forms.

The process-environment fallback has a test now as well: it sets a name of its own, parses a reference to it, and restores the previous value in a finally.

13 passing against the first commit of this branch. The two literal tests fail there -- admin@example.org where ${USER}@example.org is expected for the single-quoted one, and \admin@example.org for the escaped one -- and the other 11 pass either way.

Copilot AI 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.

🟡 Changes recommended

Literal references are exposed to subsequent launch-variable expansion instead of reaching the debuggee unchanged.

2 open findings
2 resolved since last review

🧠 Review effort: Balanced

Comment thread Extension/CHANGELOG.md Resolved
@abdelhadi703

Copy link
Copy Markdown
Author

You are right, and I had this wrong.

I went looking for a later expansion before writing the previous commit and concluded there was none, because resolveVariables is only applied to envFile and sourceFileMap. I missed that resolveEnvFile is followed by expand(config, folder) two lines further down, and that expandAllStrings walks every environment value. So a bare ${VAR} was never going to survive: it gets taken from the launch variables when one matches, and reported as "Invalid variable reference" when none does -- the exact symptom this change exists to remove. Emitting the literal unchanged only moved the problem.

Both literal forms are now written back as ${dollar}{VAR}, the form that expansion skips and collapses to a plain $ at the end.

Run through the expansion rule from expand.ts, the single-quoted and escaped values both reach the debuggee as ${USER}@example.org with no warning, while ${workspaceFolder} still resolves from the debug configuration. On the previous commit the single-quoted value came out as admin@example.org, straight from the launch variables.

On the wording finding: the changelog entry is gone rather than corrected, for the same reason as the other PR -- those are written separately before a release.

14 tests pass. The path through extendDebugConfiguration itself needs the extension host and the private feed's packages, so it is not covered here.

@abdelhadi703

Copy link
Copy Markdown
Author

Rebased on main and added the CHANGELOG line under 1.35.6 - CONTRIBUTING asks for it and I had left it out. Build, CodeQL and the CLA check are green, so the only thing left is a review.

Sean McManus (@sean-mcmanus), you seem to be merging most of what goes through here - would you take a look when you have a minute? The change is in the debugger's envFile parsing: ${VAR} references inside a .env file are now resolved, with single-quoted values and \${VAR} left as written, and there is a test for each case.

@abdelhadi703

Copy link
Copy Markdown
Author

Dropped the CHANGELOG line - Sean McManus (@sean-mcmanus) mentioned on another PR that you write it yourselves before the release, so CONTRIBUTING is out of date on that point. The diff is just the parsing change and its tests now.

@abdelhadi703

Copy link
Copy Markdown
Author

Rebased onto main (04acc76f); no conflict. Two files, and the CHANGELOG is left alone as you asked on the other one.

The new cases pass: ParsedEnvironmentFile.test.ts, 14 passing. I ran that file on its own with mocha and tsx rather than the extension host — the module only needs fs and vscode-nls — and changed nothing but the import style in my local copy, since import * as assert is not callable outside the compiled extension.

Copilot AI 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.

🟡 Changes recommended

Literal protection fails for colon-qualified references in single-quoted or escaped values, allowing unintended environment expansion and even command execution from single-quoted values.

1 open issue
2 resolved since last review

Review effort: Balanced

The quotes come off before the references are resolved, so VALUE='${SECRET}' was expanded and
a \${SECRET} reference kept its backslash while losing its meaning. Both are literal in dotenv,
and both were literal before the interpolation existed.

Adds the missing test for the process-environment fallback the changelog advertises.
The parser's output goes through expandAllStrings straight after it (configurationProvider.expand),
which substitutes every ${...} it knows and warns about the rest. Writing a literal back as a bare
${VAR} therefore did not keep it literal: the expansion either replaced it from the launch
configuration or reported "Invalid variable reference" -- the very symptom this change set out to
remove. Both literal forms now come out as ${dollar}{VAR}, the one form that expansion leaves alone
and collapses to a plain $ once it is finished.

Drops the changelog entry, since those are written separately before a release.
The literal protection only matched dotenv-style names, but the launch
expansion also rewrites ${env:...} and runs ${command:...} on anything up
to the closing brace. A single-quoted value and a backslash-escaped
reference were therefore still expanded, and the escaped one kept its
backslash.

Every ${ opener in a single-quoted value is now written back, and so is
every escaped opener, whatever follows it. Unescaped dotenv-style names
are still the only ones resolved here.

Copilot AI 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.

🟡 Changes recommended

Trailing whitespace after a closing quote causes single-quoted environment values to be misclassified as unquoted, leading to unintended interpolation and malformed output.

1 open issue
1 resolved since last review

Review effort: Balanced


// A single-quoted value is literal, so a reference inside it must not be
// expanded. The quotes come off on the next line, so this has to be read here.
const singleQuoted: boolean = (value.length > 1) && (value.charAt(0) === "'") && (value.charAt(value.length - 1) === "'");

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed. The value is trimmed of trailing whitespace before the quotes are read, so '${USER}@example.org' is recognised as single-quoted and stays literal. Added a case for it.

@abdelhadi703

Copy link
Copy Markdown
Author

The Windows job that failed is the E2E IntelliSense step, and all 12 failures sit in MultirootDeadlockTest. They start at the before-all hook with "First workspace folder is unavailable", right after this in the log:

Error: illegal state - object is disposed
  at i._checkDisposed (...)
  at i.clear (...)
  at CppProperties.handleSquigglesImpl (Extension/dist/src/LanguageServer/configurations.js:1878:39)

A diagnostics collection got disposed mid-run, and everything after it comes back empty: 0 !== 12 for the inlay hints, undefined contents for the hovers, 0 == 2 for the references.

Mentioning it because this branch only touches Extension/src/Debugger/ParsedEnvironmentFile.ts and its test, nothing under LanguageServer/, and it sits on the current main (9e3516f). Unit tests and the SimpleCppProject scenario pass on the same commit, and Linux and Mac are green. If this is a known Windows flake in that scenario then it is not mine to chase, I just did not want it read as a regression from the .env change.

@sean-mcmanus

Copy link
Copy Markdown
Contributor

The Windows job that failed is the E2E IntelliSense step, and all 12 failures sit in MultirootDeadlockTest. They start at the before-all hook with "First workspace folder is unavailable", right after this in the log:

Error: illegal state - object is disposed
  at i._checkDisposed (...)
  at i.clear (...)
  at CppProperties.handleSquigglesImpl (Extension/dist/src/LanguageServer/configurations.js:1878:39)

A diagnostics collection got disposed mid-run, and everything after it comes back empty: 0 !== 12 for the inlay hints, undefined contents for the hovers, 0 == 2 for the references.

Mentioning it because this branch only touches Extension/src/Debugger/ParsedEnvironmentFile.ts and its test, nothing under LanguageServer/, and it sits on the current main (9e3516f). Unit tests and the SimpleCppProject scenario pass on the same commit, and Linux and Mac are green. If this is a known Windows flake in that scenario then it is not mine to chase, I just did not want it read as a regression from the .env change.

Yes we see this random failure in our internal runs as well, also repros for Linux (not Mac so far). I'm looking into fixing it.

@sean-mcmanus

Copy link
Copy Markdown
Contributor

✨Copilot (devbox3-wsl/agent179): [Moderate] The process-environment lookup changes the precedence of existing launch-configuration variables. For example, if the process has USER=host-user, launch.json sets variables.USER to configured-user, and the env file contains RESULT=${USER}, the base resolves RESULT to configured-user, but this change resolves it to host-user before the launch expander can see it. Please preserve or disambiguate existing launch-variable references when a process variable has the same name.

if (singleQuoted) {
value = value.replace(/\$\{/g, `\${dollar}{`);
} else {
value = value.replace(/(\\)?\$\{([\w\.\-]+)\}|\\\$\{/g, (full: string, escape: string | undefined, name: string | undefined): string => {

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.

✨Copilot (devbox3-wsl/agent179): [Moderate] Treating every backslash before ${ as an escape breaks existing Windows paths. For example, with USERNAME=Alice, an env-file value USER_DIR=C:\Users\${env:USERNAME}\project previously expanded to C:\Users\Alice\project; it now becomes C:\Users${env:USERNAME}\project, losing the separator and leaving the reference literal. Please preserve this existing Windows path and launch-variable case.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You are right, and this one was mine: before the change that value came out as C:\Users\Alice\project, with the backslash acting as a separator rather than an escape.

A backslash now only escapes the reference where it cannot be a separator -- at the start of the value, or after =, a space or a quote. In C:\Users\${env:USERNAME}\project the backslash follows a path character, so it is kept and the reference still expands, while \${USER} at the start of a value stays literal. The expansion is a single pass now instead of a regex over the whole value, so a reference the file cannot answer is passed through untouched rather than rebuilt.

The new test pins the path case: USER_DIR=C:\Users\${env:USERNAME}\project comes out bare, before any launch expansion.

// Escaped opener that is not a dotenv-style name, e.g. \${env:HOME}.
return `\${dollar}{`;
}
if (env.has(name)) {

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.

✨Copilot (devbox3-wsl/agent179): [Moderate] On Windows, environment variable names are case-insensitive, but the initial environment map is not. If the launch configuration supplies Path=C:\override, the process has PATH=C:\host, and the env file contains COPY=${PATH}, this lookup misses the configured Path and falls back to the host value. Please apply Windows environment-name semantics to the initial environment before using the process fallback.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed as well. On Windows the lookup folds the name over both the file/initial environment and process.env, so ${PATH} finds a Path entry supplied by the launch configuration instead of falling through to the host value. Other platforms still match exactly.

The test is skipped off Windows, since that is the only place the semantics exist.

Treating every backslash in front of ${ as an escape broke Windows paths. In
C:\Users\${env:USERNAME}\project the backslash separates path segments, so the
value used to expand to C:\Users\Alice\project and now came out as
C:\Users${env:USERNAME}\project with the reference left literal.

A backslash only escapes the reference where it cannot be a separator: at the
start of the value, or after =, a space or a quote. The expansion is also done
in one pass now, so a reference the file cannot answer is passed through
instead of being rebuilt.

Environment names are case-insensitive on Windows, so ${PATH} now finds a Path
entry from the launch configuration instead of falling through to the host
environment.

Tested on the compiled output: 19 passing, and the two new cases fail on the
previous commit.

Copilot AI 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.

🟡 Changes recommended

Environment parsing can corrupt escaped dollar-prefixed values and incorrectly expand embedded escaped references in ordinary non-path strings.

3 open issues

Review effort: Balanced

// An escaped reference is literal. ${dollar} is the form the launch expansion leaves
// alone and collapses back to a plain $ once it is done, so the debuggee is the only
// place that sees the literal.
if (char === "\\" && value.charAt(i + 1) === "$" && ParsedEnvironmentFile.isReferenceEscape(value, i)) {

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed. The escape branch now requires the whole \${ opener, so \$USER} is left exactly as written. Added a case for it.

if (index === 0) {
return true;
}
return !/[A-Za-z0-9_.\-:\/\\]/.test(value.charAt(index - 1));

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed. The exception is now limited to values that start with a drive letter or a UNC prefix; everywhere else, including ordinary text, \${ is an escape again. New case: EMAIL=prefix\${USER}@example.org stays literal as prefix${dollar}{USER}@example.org. The Windows path case is unchanged and still covered.

this.skip() inside a function expression trips no-invalid-this, and the linter is
part of CI. The test now asserts the expected value per platform instead, so it
runs everywhere and still pins the Windows behaviour.

Copilot AI 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.

🟡 Changes recommended

The escape heuristic incorrectly expands escaped references in ordinary text, potentially activating command references, and the new PATH assertion ignores process-environment fallback on Linux/macOS.

4 open issues

Review effort: Balanced

Comment on lines +216 to +221
// either spelling. Elsewhere the reference stays bare for the launch expansion.
const content: string = `COPY=\${PATH}`;
const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(
content, "TestEnvFileName", [{ name: "Path", value: "C:\\override" }]);

const expected: string = process.platform === "win32" ? "C:\\override" : "${PATH}";

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

You are right, and CI caught it on Linux and Mac: PATH does exist in the process environment there, so the reference resolved and the assertion expected the opposite. The test now uses a name that only the initial environment carries, so it is deterministic on every host.

* find each other there.
*/
private static lookup(name: string, env: Map<string, any>): string | undefined {
if (env.has(name)) {

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.

✨Copilot (devbox3-wsl/agent179): [Moderate] Case-folding only the lookup still misses an env-file override with different casing. On Windows, if the initial environment contains Path=C:\initial and the file defines PATH=C:\file followed by COPY=${Path}, both case variants remain in the map and this exact-match branch returns the earlier C:\initial, even though the file redefined the same Windows variable. Please replace existing entries case-insensitively as the file is parsed, and cover the mixed-case override in a test.

The previous rule looked at the character before the backslash, so an escaped
reference in ordinary text stopped being literal: prefix\${USER} expanded
instead of staying put, which also meant a \${command:...} in prose could reach
the launch expansion. The exception now applies only to values that start with
a drive letter or a UNC prefix.

The escape branch also matched \$ without checking for the brace, so VALUE=\$USER}
was rewritten to ${dollar}{SER}. It requires the whole \${ now.

Whitespace after a closing quote kept a single-quoted value from being seen as
quoted, so '${USER}@example.org' followed by spaces was expanded. The value is
trimmed before the quotes are read.

The case test used PATH, which exists in the process environment on Linux and
macOS, so it resolved there and the expected value was wrong. It uses a name that
only the initial environment carries.

22 tests pass, and the three new cases fail on the previous commit.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Pull Request

Development

Successfully merging this pull request may close these issues.

[bug] launch.json envFile not capable of variable interpolation

3 participants