Skip to content

saves: survive redirected console on Windows and validate pack/extract destinations - #1438

Open
shadshuvo wants to merge 1 commit into
ItsNotRexed:mainfrom
shadshuvo:fix/saves-path-validation-redirected-console
Open

shadshuvo wants to merge 1 commit into
ItsNotRexed:mainfrom
shadshuvo:fix/saves-path-validation-redirected-console

Conversation

@shadshuvo

Copy link
Copy Markdown

Item: new BUILD item (@abilliontokens's finding 7078242007), claimed in #1380 (claim)

What and why

Addresses @abilliontokens's finding on issue #1380 (finding):

"tools that print a user-supplied output path to stdout crash the same way #1406 fixed for make_game.py when the path has a character outside the console's ANSI code page. Where: e.g. tools/saves.py:239 (print(f'{len(es)} blocks -> {out}'))..."

  1. Redirected console output encoding (tools/saves.py):
    • tools/saves.py prints output paths and save titles to stdout (extract: print(f'{len(es)} blocks -> {out}'), pack: print(f'wrote {out}...'), import: prints slot title).
    • On Windows with redirected stdout (or pipes) under python -I, stdout is strictly encoded with the console ANSI code page (cp1252), causing UnicodeEncodeError when paths or save titles contain non-Latin characters (CJK, Cyrillic, Greek, or private-use characters).
    • main() now reconfigures sys.stdout with errors="replace", matching make_game: a redirected console must not kill --find on an un-encodable path #1406 in make_game.py.
  2. CLI argument handling (main(argv=None) -> int):
    • Made argv optional defaulting to None, falling back to sys.argv.
  3. Extract path safety (extract):
    • Rejects destinations that are existing files or aliases of the input file with a clear ValueError instead of letting os.makedirs crash with FileExistsError.
    • Replaces bare sys.exit on unsupported container format with ValueError so main() reports ERROR: ... uniformly with exit code 2.
  4. Pack path safety (pack):
    • Validates that src is an existing directory.
    • Refuses destination paths that point to existing directories or would overwrite inputs inside the source directory (same_path / is_inside_dir).
    • Automatically creates the parent directory of the output file if it does not yet exist.
  5. Resource hygiene:
    • Registered tools/saves.py in tests/test_resource_hygiene.py.
  6. Test coverage (tests/test_saves.py):
    • Added RedirectedConsoleEncodingTest: executes child process under PYTHONIOENCODING=cp1252 with unencodable character in the path, asserting clean exit 0.
    • Added CliPathValidationTest: verifies extract refuses existing file destinations and input aliases, pack refuses missing/file sources, existing directories, and in-source destination paths, pack creates parent directories, and main() handles default argv=None.

Testing

Tested on Windows 11 with Python 3.14 (AMD Radeon RX 7800 XT):

  • python -I tests/test_saves.py: 38/38 pass (8 new tests).
  • python -m compileall -q make_game.py tools tests: pass.
  • python -I make_game.py --help: pass.
  • python -I tests/test_resource_hygiene.py: pass (2/2).
  • python -I tests/test_docs_links.py: pass (5/5).
  • node --test tests/test_viewer_streaming.cjs: pass (35/35).

No game data, carved files, or keys included.
AI-assisted.

…t destinations

- Reconfigure sys.stdout with errors="replace" so unencodable Unicode paths on redirected Windows consoles (strict cp1252) do not raise UnicodeEncodeError
- Default argv=None in main() and fall back to sys.argv
- Validate extract destination against existing files or input path aliases
- Validate pack source directory and output destination against directories and inside-source file clobbering; ensure parent directories are created
- Register tools/saves.py in tests/test_resource_hygiene.py
- Add RedirectedConsoleEncodingTest and CliPathValidationTest in tests/test_saves.py
@bobcatchris

Copy link
Copy Markdown
Contributor

Independent CPU/Windows verification, at head 37fc1175 (merge base c2967a5e, current main bb2e1842):

  • tests/test_saves.py 38/38 direct unittest and tests/test_resource_hygiene.py 2/2; pytest across both: 40 passed. compileall -q tools tests clean.
  • Negative control with the same test files on untouched main: 8 failed, 32 passed. Main dies on a redirected console with a charmap encode error, raises tracebacks/FileExistsError for extract and pack destinations, requires an explicit main(argv), and can write a pack inside its source directory. The PR sets stdout errors="replace", defaults main(argv=None), and validates extract/pack paths.
  • Synthetic save containers only; no game data.

The redirected-console case was exercised on Windows here; no GPU or runtime claim.

@kapitche

Copy link
Copy Markdown
Contributor

Tested on Linux (WSL2 Ubuntu), Python 3.12, CPU only: pass. Tests with main merged: 40 passed, 12 subtests. With tools/saves.py from main, 7 fail, and the cp1252 repro exits 0. It's a superset of #1426 (same stdout fix, plus output refusals and tests). It conflicts with #1426 and with #1428 in tools/saves.py.

@Flyander Flyander 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.

Found an input-clobber case in extract: the guard catches out == p, but it does not catch a source file located inside the output directory. For example, if a valid JSAV file is <out>/index.json, extract(p, out) reads it and then opens that same path with "w" while writing the generated index, replacing the source. Please reject an input beneath out (or check all generated output paths against p) before writing. The existing same-path test does not cover this directory-contained case.

@bobcatchris

Copy link
Copy Markdown
Contributor

Independent CPU verification, at head 37fc1175 against main bb2e1842 (Windows, Python 3.12) — the redirect case reproduces on main.

  • tests/test_saves.py + tests/test_resource_hygiene.py: 40 passed.
  • Negative control with only tools/saves.py reverted to main: 8 failed, 32 passed — RedirectedConsoleEncodingTest::test_redirected_console_replaces_unencodable_character, the seven CliPathValidationTest cases (extract existing file / same input, pack missing src / existing dir / out inside src / parent creation, and test_main_defaults, which on main is a TypeError because main requires argv).
  • Independently of this PR: main with a synthetic ASAV under a non-ANSI name and stdout redirected gives exit 2, no stdout, 'charmap' codec can't encode characters.

Overlap to settle before merge

#1426 (BUILD-401) adds the same sys.stdout.reconfigure(...) at the same line of main(), so whichever lands first will conflict with the other. The differences:

this PR #1426
handler errors="replace" errors="backslashreplace"
guard hasattr(sys.stdout, "reconfigure") try/except
tests yes (the case above) none
extract/pack validation yes no

Since stderr's documented fallback in CPython is backslashreplace, errors="replace" turns a path outside the code page into ? where the rest of the tool escapes it — worth a line either way in the comment above the call. This PR covers everything #1426 does and more with a test, so the simplest end state is probably this one merged and #1426 dropped, with the maintainer deciding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants