Coverage for .venv/lib/python3.13/site-packages/litellm/proxy/client/cli/commands/cmd_quoting.py: 0%

8 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 12:01 +0000

1"""Quoting for command lines that cmd.exe reads before handing them to a program.""" 

2 

3from typing import Final 

4 

5_CMD_PERCENT_GUARD: Final = "%%cd:~,%" 

6 

7 

8def _double_trailing_backslashes(segment: str) -> str: 

9 bare: Final = segment.rstrip("\\") 

10 return bare + "\\" * 2 * (len(segment) - len(bare)) 

11 

12 

13def quote_for_cmd(token: str) -> str: 

14 """Quote one token so both parsers that read it see the original text. 

15 

16 Follows the algorithm the Rust standard library settled on for batch files 

17 after CVE-2024-24576. Two parsers see this token: cmd.exe, which ends a 

18 quoted string on a lone `"` and so wants an embedded one doubled, and the 

19 program's own C runtime argv split, where a backslash escapes the quote that 

20 follows it, so every backslash run standing before a quote is doubled. 

21 Quoting cannot stop cmd expanding `%VAR%`, so each `%` is prefixed with 

22 `%%cd:~,`: the zero-length substring of the always defined `cd` expands to 

23 nothing and leaves no `%` pair for cmd to match. 

24 """ 

25 escaped: Final = '""'.join(_double_trailing_backslashes(part) for part in token.split('"')) 

26 return '"' + escaped.replace("%", _CMD_PERCENT_GUARD) + '"'