pe: harden atomic temp cleanup and error paths in intake_exe with unit and CLI suite #2350

Merged
Ammmae0x merged 2 commits from upstream-pr/2358 into main 2026-11-25 14:23:42 +00:00
Ammmae0x commented 2026-11-25 13:34:28 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Ammmae0x on 2026-11-25T13:34:28Z.


Change

Harden path checks, report-directory creation, and atomic temp-file cleanup in tools/intake_exe.py and add a dedicated pure-Python unit and CLI hardening suite (tests/intake_exe_check.py, registered as pe_intake_checks in CMakeLists.txt):

  • Harden inside() by resolving the root base explicitly and rejecting leading / or \ prefixes (in addition to Path.is_absolute(), traversal outside base, and path == base).
  • Guard args.build.resolve() / args.reports.resolve() against OSError in main(argv=None) -> int, exiting cleanly with code 1 and zero raw tracebacks.
  • Guard reports.mkdir(parents=True, exist_ok=True), NamedTemporaryFile + json.dump, and os.replace(tmp_path, dest) inside try/except (OSError, TypeError, ValueError) with finally: tmp_path.unlink(missing_ok=True) so partial .tmp files are always removed on write or replace failure.

Verification

Verified on commit a1e2eaee (rebased onto upstream/main 43608f2e):

  • out/pe-env/Scripts/python.exe -B tests/intake_exe_check.py -v -> Ran 5 tests in 0.314s / OK (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/intake/routing_check.py -> intake routing synthetic checks passed (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/intake/import_forms_check.py -> named, ordinal and delay-load import form checks passed (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/pe_inventory_cli_check.py -> Ran 7 tests in 2.139s / OK (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/pe_run_package_plan_check.py -> Ran 11 tests in 1.173s / OK (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/pe_run_package_invalid_check.py -> Ran 3 tests in 0.502s / OK (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/pe_package_preflight_check.py -> Ran 14 tests in 0.371s / OK (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/pe_package_ordinal_plan_check.py -> Ran 3 tests in 0.001s / OK (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/form_coverage_check.py -> form coverage checks passed (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/docs_links_check.py -> Self-test passed. Checked 19 Markdown files and 459 links. (exit 0)
  • out/pe-env/Scripts/python.exe -B tests/bidi_controls_check.py -> Self-test passed. Checked 1646 tracked source, script and build/CI files: no bidirectional controls. (exit 0)

Evidence and follow-up

  • All test fixtures in tests/intake_exe_check.py are synthetic in-memory PE32+ binaries (.text, .rdata normal/delay imports, TLS callback table, .pdata runtime-function records) and synthetic MicrosoftGame.Config/layout.xml/baseline/integrity JSON files created inside temporary directories.
  • Negative controls cover path traversal/root/absolute-slash rejections in inside(), absent/misaligned/overlapping .pdata fallback, non-x64/DLL/truncated PE rejection, missing candidate and malformed XML error reports (exit 2), --reports colliding with build directory (exit 2) or pointing to an existing file (exit 1), --require-routing unsupported imports (exit 1), Path.resolve OSError (exit 1), and temp .tmp unlink verification on both json.dump and os.replace failures.

Checklist

  • This pull request covers one reviewable behavior.
  • I included the exact command and result for every check I ran.
  • I considered a negative control or failure case for a new fixture.
  • I updated README/docs when a capability or build requirement changed.
  • I did not include game files, dumps, distribution links or secrets.

AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6605683072 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2358). Originally posted by [Ammmae0x](https://github.com/Ammmae0x) on 2026-11-25T13:34:28Z. --- ## Change Harden path checks, report-directory creation, and atomic temp-file cleanup in `tools/intake_exe.py` and add a dedicated pure-Python unit and CLI hardening suite (`tests/intake_exe_check.py`, registered as `pe_intake_checks` in `CMakeLists.txt`): - Harden `inside()` by resolving the root base explicitly and rejecting leading `/` or `\` prefixes (in addition to `Path.is_absolute()`, traversal outside `base`, and `path == base`). - Guard `args.build.resolve()` / `args.reports.resolve()` against `OSError` in `main(argv=None) -> int`, exiting cleanly with code 1 and zero raw tracebacks. - Guard `reports.mkdir(parents=True, exist_ok=True)`, `NamedTemporaryFile` + `json.dump`, and `os.replace(tmp_path, dest)` inside `try/except (OSError, TypeError, ValueError)` with `finally: tmp_path.unlink(missing_ok=True)` so partial `.tmp` files are always removed on write or replace failure. ## Verification Verified on commit `a1e2eaee` (rebased onto `upstream/main` `43608f2e`): - `out/pe-env/Scripts/python.exe -B tests/intake_exe_check.py -v` -> `Ran 5 tests in 0.314s` / `OK` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/intake/routing_check.py` -> `intake routing synthetic checks passed` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/intake/import_forms_check.py` -> `named, ordinal and delay-load import form checks passed` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/pe_inventory_cli_check.py` -> `Ran 7 tests in 2.139s` / `OK` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/pe_run_package_plan_check.py` -> `Ran 11 tests in 1.173s` / `OK` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/pe_run_package_invalid_check.py` -> `Ran 3 tests in 0.502s` / `OK` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/pe_package_preflight_check.py` -> `Ran 14 tests in 0.371s` / `OK` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/pe_package_ordinal_plan_check.py` -> `Ran 3 tests in 0.001s` / `OK` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/form_coverage_check.py` -> `form coverage checks passed` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/docs_links_check.py` -> `Self-test passed. Checked 19 Markdown files and 459 links.` (exit 0) - `out/pe-env/Scripts/python.exe -B tests/bidi_controls_check.py` -> `Self-test passed. Checked 1646 tracked source, script and build/CI files: no bidirectional controls.` (exit 0) ## Evidence and follow-up - All test fixtures in `tests/intake_exe_check.py` are synthetic in-memory PE32+ binaries (`.text`, `.rdata` normal/delay imports, TLS callback table, `.pdata` runtime-function records) and synthetic `MicrosoftGame.Config`/`layout.xml`/baseline/integrity JSON files created inside temporary directories. - Negative controls cover path traversal/root/absolute-slash rejections in `inside()`, absent/misaligned/overlapping `.pdata` fallback, non-x64/DLL/truncated PE rejection, missing candidate and malformed XML error reports (exit 2), `--reports` colliding with build directory (exit 2) or pointing to an existing file (exit 1), `--require-routing` unsupported imports (exit 1), `Path.resolve` `OSError` (exit 1), and temp `.tmp` unlink verification on both `json.dump` and `os.replace` failures. ## Checklist - [x] This pull request covers one reviewable behavior. - [x] I included the exact command and result for every check I ran. - [x] I considered a negative control or failure case for a new fixture. - [x] I updated README/docs when a capability or build requirement changed. - [x] I did not include game files, dumps, distribution links or secrets. AI-assisted.
tedin7 commented 2026-11-25 14:05:00 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T13:40:30Z.

Review: COMMENTED


Review of head a1e2eaeee91f40894cb2580b0192817d5df6e4ae (Linux, local).

Scope: tools/intake_exe.py (+28/-11), new tests/intake_exe_check.py, CMakeLists.txt (pe_intake_checks). Title is neutral. MERGEABLE. CI: Linux checks, gfx1013 fixtures and Windows build/test pass.

Commands executed locally (venv with pefile):

  • python -B tests/intake_exe_check.py -> Ran 5 tests / OK
  • python -B tests/intake/routing_check.py -> intake routing synthetic checks passed
  • python -B tests/pe_inventory_cli_check.py -> 4 errors, all KeyError: 'SystemRoot' (Windows-only env var on Linux; file not touched by this PR, so not a regression)
  • python3 tests/docs_links_check.py -> pass (459 links)
  • python3 tests/bidi_controls_check.py -> pass
  • git diff --check origin/main...HEAD -> clean

Mutations (all reverted):

  • os.replace(tmp_path, dest) replaced by raise OSError -> suite FAILED (2 failures), killed
  • finally temp cleanup disabled (if tmp_path is not None -> if False) -> FAILED (1), killed
  • leading / or \ check removed from inside() -> FAILED (1), killed

Findings:

  • P1: none.
  • P2: none.
  • nit tools/intake_exe.py (main, os.replace): replace now overwrites an existing <name>.<status>.json, where the old rename failed on Windows. Harmless since temp names are random, but worth one line in the description.
  • nit tools/intake_exe.py (inside): the startswith(("/", "\\")) check matters on Windows (rooted but not absolute paths such as \x). On Linux the new test only exercises the / half, so the \ half is covered only by the Windows CI job.
  • nit: the failure path prints error: and returns 1 while the argparse path uses parser.error (exit 2). Fine, just inconsistent.

No Windows run needed: pure Python, no shader or C++ change.

AI-assisted; commands listed were executed locally.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6058659208 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2358#pullrequestreview-6058659208). Originally posted by [tedin7](https://github.com/tedin7) on 2026-11-25T13:40:30Z. **Review:** COMMENTED --- Review of head `a1e2eaeee91f40894cb2580b0192817d5df6e4ae` (Linux, local). **Scope:** `tools/intake_exe.py` (+28/-11), new `tests/intake_exe_check.py`, `CMakeLists.txt` (`pe_intake_checks`). Title is neutral. MERGEABLE. CI: Linux checks, gfx1013 fixtures and Windows build/test pass. **Commands executed locally (venv with `pefile`):** - `python -B tests/intake_exe_check.py` -> `Ran 5 tests` / `OK` - `python -B tests/intake/routing_check.py` -> `intake routing synthetic checks passed` - `python -B tests/pe_inventory_cli_check.py` -> 4 errors, all `KeyError: 'SystemRoot'` (Windows-only env var on Linux; file not touched by this PR, so not a regression) - `python3 tests/docs_links_check.py` -> pass (459 links) - `python3 tests/bidi_controls_check.py` -> pass - `git diff --check origin/main...HEAD` -> clean **Mutations (all reverted):** - `os.replace(tmp_path, dest)` replaced by `raise OSError` -> suite FAILED (2 failures), killed - `finally` temp cleanup disabled (`if tmp_path is not None` -> `if False`) -> FAILED (1), killed - leading `/` or `\` check removed from `inside()` -> FAILED (1), killed **Findings:** - P1: none. - P2: none. - nit `tools/intake_exe.py` (`main`, `os.replace`): replace now overwrites an existing `<name>.<status>.json`, where the old `rename` failed on Windows. Harmless since temp names are random, but worth one line in the description. - nit `tools/intake_exe.py` (`inside`): the `startswith(("/", "\\"))` check matters on Windows (rooted but not absolute paths such as `\x`). On Linux the new test only exercises the `/` half, so the `\` half is covered only by the Windows CI job. - nit: the failure path prints `error:` and returns 1 while the argparse path uses `parser.error` (exit 2). Fine, just inconsistent. No Windows run needed: pure Python, no shader or C++ change. AI-assisted; commands listed were executed locally.
ChazY11 commented 2026-11-25 14:05:15 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by ChazY11 on 2026-11-25T13:55:34Z.


Four mutations: two caught, two equivalent — and I checked the equivalence rather than reporting it as a gap

Baseline on this branch (tests/intake_exe_check.py → OK, exit 0).

mutation result
base = root.resolve() → base = root survived
path == base → False (the root itself is accepted) caught
Path(name).is_absolute() → False survived
except OSError → except ZeroDivisionError in main caught

Why the two survivors are equivalent, measured rather than assumed

is_absolute() removed. Every absolute form is still refused by the other clauses:

'/etc/passwd'            -> ValueError: Invalid package path: /etc/passwd
'\\\\server\\share\\x'   -> ValueError: Invalid package path: \\server\share\x
'C:/Windows/win.ini'     -> ValueError: Invalid package path: C:/Windows/win.ini

C:/Windows/win.ini is the interesting one: it is not startswith(('/', '\\')), so the clause that saves it is is_relative_to(base) — joining an absolute
name with a base yields the absolute path, which is not relative to the base. So two of the three clauses are redundant for the cases I could construct.

base = root (no resolve). With an unresolved root the check gets stricter, not looser — inside() then refuses even a plain name, because the
symlink-free .. in the root does not normalise:

'plain.txt'        -> ValueError: Invalid package path: plain.txt
'../sibling.txt'   -> ValueError: Invalid package path: ../sibling.txt

So it is not an escape, it is a false refusal — which is why the mutant survives: no test asserts that a resolved root makes a plain name work. The
resolve() on line 43 is therefore load-bearing in the opposite direction from the one a reader might assume, and that is worth one sentence in the
docstring of inside().

The one thing I would add

inside() is the security boundary for package paths, and today its guarantee is provided by three clauses of which any one would do for the inputs I tried.
That is fine as defence in depth, but it means a future "simplify this" edit cannot be caught by construction — only by the cases that happen to be in the
test. A table with one row per rejection reason would pin the intent rather than the current overlap:

'/etc/passwd'          refused   (absolute, POSIX)
'C:/Windows/win.ini'   refused   (absolute, drive)
'\\\\server\\share\\x' refused   (absolute, UNC)
'../escape.txt'        refused   (escapes the root)
'.'                    refused   (the root itself)

Your check already covers behaviour; this would make the reasons explicit, which is what a security helper's test is for.

What the change gets right that is easy to miss

except OSError around args.build.resolve() is the correct catch: resolve() raises OSError (not FileNotFoundError specifically) for a path that
cannot be resolved, and returning 1 with error: … on stderr instead of a traceback is what a CLI should do. The temp-file rework also drops the
NamedTemporaryFile(delete=False) + rename pattern that leaked the file when the rename failed — I checked that the two survivors above do not weaken
that path, since it is the part of the diff most likely to lose a .tmp on an exception.

AI-assisted; the four mutations and both probes were run locally on Windows 11 build 26300.9974.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7164491075 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2358#issuecomment-7164491075). Originally posted by [ChazY11](https://github.com/ChazY11) on 2026-11-25T13:55:34Z. --- ## Four mutations: two caught, two equivalent — and I checked the equivalence rather than reporting it as a gap Baseline on this branch (`tests/intake_exe_check.py` → `OK`, exit 0). | mutation | result | |---|---| | `base = root.resolve()` → `base = root` | survived | | `path == base` → `False` (the root itself is accepted) | **caught** | | `Path(name).is_absolute()` → `False` | survived | | `except OSError` → `except ZeroDivisionError` in `main` | **caught** | ### Why the two survivors are equivalent, measured rather than assumed **`is_absolute()` removed.** Every absolute form is still refused by the other clauses: ```text '/etc/passwd' -> ValueError: Invalid package path: /etc/passwd '\\\\server\\share\\x' -> ValueError: Invalid package path: \\server\share\x 'C:/Windows/win.ini' -> ValueError: Invalid package path: C:/Windows/win.ini ``` `C:/Windows/win.ini` is the interesting one: it is not `startswith(('/', '\\'))`, so the clause that saves it is `is_relative_to(base)` — joining an absolute name with a base yields the absolute path, which is not relative to the base. So two of the three clauses are redundant for the cases I could construct. **`base = root` (no `resolve`).** With an unresolved root the check gets *stricter*, not looser — `inside()` then refuses even a plain name, because the symlink-free `..` in the root does not normalise: ```text 'plain.txt' -> ValueError: Invalid package path: plain.txt '../sibling.txt' -> ValueError: Invalid package path: ../sibling.txt ``` So it is not an escape, it is a false refusal — which is why the mutant survives: no test asserts that a resolved root makes a plain name work. The `resolve()` on line 43 is therefore load-bearing in the opposite direction from the one a reader might assume, and that is worth one sentence in the docstring of `inside()`. ### The one thing I would add `inside()` is the security boundary for package paths, and today its guarantee is provided by three clauses of which any one would do for the inputs I tried. That is fine as defence in depth, but it means a future "simplify this" edit cannot be caught by construction — only by the cases that happen to be in the test. A table with one row per rejection reason would pin the intent rather than the current overlap: ```text '/etc/passwd' refused (absolute, POSIX) 'C:/Windows/win.ini' refused (absolute, drive) '\\\\server\\share\\x' refused (absolute, UNC) '../escape.txt' refused (escapes the root) '.' refused (the root itself) ``` Your check already covers behaviour; this would make the *reasons* explicit, which is what a security helper's test is for. ## What the change gets right that is easy to miss `except OSError` around `args.build.resolve()` is the correct catch: `resolve()` raises `OSError` (not `FileNotFoundError` specifically) for a path that cannot be resolved, and returning 1 with `error: …` on stderr instead of a traceback is what a CLI should do. The temp-file rework also drops the `NamedTemporaryFile(delete=False)` + `rename` pattern that leaked the file when the rename failed — I checked that the two survivors above do not weaken that path, since it is the part of the diff most likely to lose a `.tmp` on an exception. AI-assisted; the four mutations and both probes were run locally on Windows 11 build 26300.9974.
Ammmae0x commented 2026-11-25 14:05:16 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Ammmae0x on 2026-11-25T14:02:16Z.


Addressed in commit 5ce306b9:

  • Added a docstring to inside() in tools/intake_exe.py noting why root.resolve() is required before is_relative_to(base).
  • Expanded test_inside_rejects_traversal_root_and_absolute_paths in tests/intake_exe_check.py with explicit refusal cases (absolute_posix, absolute_drive, absolute_unc, escape_parent, escape_nested, root_dot, empty) and added an unresolved root / "sub" / ".." positive case that pins base = root.resolve() (verified mutating base = root.resolve() to base = root now fails with 1 error).
  • Verified tests/intake_exe_check.py (5/5 OK), tests/intake/routing_check.py, tests/intake/import_forms_check.py, tests/pe_inventory_cli_check.py (7/7 OK), tests/form_coverage_check.py, tests/docs_links_check.py (19 files, 459 links), and tests/bidi_controls_check.py (1646 files).

AI-assisted.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7164660766 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/2358#issuecomment-7164660766). Originally posted by [Ammmae0x](https://github.com/Ammmae0x) on 2026-11-25T14:02:16Z. --- Addressed in commit `5ce306b9`: - Added a docstring to `inside()` in `tools/intake_exe.py` noting why `root.resolve()` is required before `is_relative_to(base)`. - Expanded `test_inside_rejects_traversal_root_and_absolute_paths` in `tests/intake_exe_check.py` with explicit refusal cases (`absolute_posix`, `absolute_drive`, `absolute_unc`, `escape_parent`, `escape_nested`, `root_dot`, `empty`) and added an unresolved `root / "sub" / ".."` positive case that pins `base = root.resolve()` (verified mutating `base = root.resolve()` to `base = root` now fails with 1 error). - Verified `tests/intake_exe_check.py` (5/5 OK), `tests/intake/routing_check.py`, `tests/intake/import_forms_check.py`, `tests/pe_inventory_cli_check.py` (7/7 OK), `tests/form_coverage_check.py`, `tests/docs_links_check.py` (19 files, 459 links), and `tests/bidi_controls_check.py` (1646 files). AI-assisted.
upstream-sync closed this pull request 2026-11-25 15:01:41 +00:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!2350
No description provided.