Skip to content

Fix file states raising UnicodeDecodeError on encoding mismatch#69696

Open
ggiesen wants to merge 3 commits into
saltstack:3006.xfrom
ggiesen:fix-50903-file-append-encoding
Open

Fix file states raising UnicodeDecodeError on encoding mismatch#69696
ggiesen wants to merge 3 commits into
saltstack:3006.xfrom
ggiesen:fix-50903-file-append-encoding

Conversation

@ggiesen

@ggiesen ggiesen commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

salt/states/file.py append() (and its siblings prepend/comment/blockreplace) read the target file as bytes and decode it with salt_system_encoding using strict error handling, purely to build a diff; a file whose bytes are not valid in the system encoding (e.g. ISO-8859-1 content under an ASCII/C locale) raised UnicodeDecodeError and aborted the state. The fix adds errors="replace" to all seven such decode sites, since the decoded lines only feed difflib. Verified the new unit test PASSES with the fix (1 passed via pytest with shadow confirmed) and FAILS (UnicodeDecodeError) when the fix is temporarily reverted.

What issues does this PR fix or reference?

Fixes #50903

Previous Behavior

See #50903.

New Behavior

Fix file states raising UnicodeDecodeError on encoding mismatch. Validated by a unit test proven to fail on unpatched 3006.x and pass with the fix (confirmed by adversarial review).

Merge requirements satisfied?

  • Tests written/updated
  • Changelog

Commits signed with GPG?

No

The file.comment, file.append and file.prepend states read the target
file as bytes and decode it with the system encoding purely to build a
diff. A strict decode raised UnicodeDecodeError and aborted the state
when the file contained bytes invalid in that encoding. Decode with
errors="replace" since the result is only used for the diff.

Fixes saltstack#50903
…tch fix

The direct tests call file.comment and file.prepend (the two changed state
functions previously untested for this case) with production-shape args
(name+regex / name+text, as the state compiler passes from an SLS) against a
real file holding a 0xed byte while __salt_system_encoding__ is ascii, pinning
the errors="replace" decode fix; both fail with UnicodeDecodeError when the
fix is reverted. The inverse test guards against overcorrection: file.append
on a cleanly-decodable UTF-8 file must still produce an unmangled diff with
no U+FFFD replacement characters, and passes with and without the fix.

Claude-Session: https://claude.ai/code/session_01MF2AuQNhBZg4HDt1x6xxCu
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.

1 participant