Skip to content

fix: add explicit encoding to open() calls for cross-platform portability - #10307

Open
KeloYuan wants to merge 1 commit into
celery:mainfrom
KeloYuan:fix/open-encoding
Open

KeloYuan wants to merge 1 commit into
celery:mainfrom
KeloYuan:fix/open-encoding

Conversation

@KeloYuan

@KeloYuan KeloYuan commented May 8, 2026

Copy link
Copy Markdown

Python open() uses locale-dependent encoding by default. On systems with non-UTF-8 locale (e.g. Windows cp1252), reading PID files, certificates, and auth keys can fail or produce corrupted data.

Fixed 3 files in celery/production code:

  • platforms.py: PID file read/write (2 calls)
  • security/certificate.py: PEM certificate loading (1 call)
  • security/init.py: SSL key and cert loading (2 calls)

…lity

Python open() uses locale-dependent encoding by default. On systems with
non-UTF-8 locale (e.g. Windows cp1252), reading PID files, certificates,
and auth keys can fail or produce corrupted data.

Fixed 4 files in celery/production code:
- platforms.py: PID file read/write (2 calls)
- security/certificate.py: PEM certificate loading (1 call)
- security/__init__.py: SSL key and cert loading (2 calls)
Copilot AI review requested due to automatic review settings May 8, 2026 17:05

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.

Pull request overview

This PR aims to make file reads in a few Celery runtime paths deterministic across platforms by avoiding locale-dependent default encodings in open().

Changes:

  • Use encoding="utf-8" when reading X.509 certificate PEM files in the filesystem cert store.
  • Use encoding="utf-8" when reading the security key/certificate files during setup_security().
  • Use encoding="utf-8" when reading and re-reading pidfiles for lock verification.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
celery/security/certificate.py Reads PEM certificate files using explicit UTF-8 decoding.
celery/security/__init__.py Reads auth serializer key/cert files using explicit UTF-8 decoding.
celery/platforms.py Reads pidfile contents using explicit UTF-8 decoding (including re-read verification).

@auvipy auvipy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the changes seems to be useful. should we also update or improve relevant tests for the relevant changes as well?

@auvipy auvipy added this to the 5.7.0 milestone May 9, 2026
@codecov

codecov Bot commented May 9, 2026

Copy link
Copy Markdown

❌ 1 Tests Failed:

Tests completed Failed Passed Skipped
3813 1 3812 21
View the top 1 failed test(s) by shortest run time
t/unit/utils/test_platforms.py::test_Pidfile::test_write_pid
Stack Traces | 0.003s run time
self = <t.unit.utils.test_platforms.test_Pidfile object at 0x7fc069175f90>
open_ = <MagicMock name='open' id='140464460109136'>
fdopen = <MagicMock name='fdopen' id='140463914351456'>
osopen = <MagicMock name='open' id='140463914351792'>
getpid = <MagicMock name='getpid' id='140463914352128'>
fsync = <MagicMock name='fsync' id='140463922135120'>

    @patch('os.fsync')
    @patch('os.getpid')
    @patch('os.open')
    @patch('os.fdopen')
    @patch('builtins.open')
    def test_write_pid(self, open_, fdopen, osopen, getpid, fsync):
        getpid.return_value = 1816
        osopen.return_value = 13
        w = fdopen.return_value = WhateverIO()
        w.close = Mock()
        r = open_.return_value = WhateverIO()
        r.write('1816\n')
        r.seek(0)
    
        p = Pidfile('/var/pid')
        p.write_pid()
        w.seek(0)
        assert w.readline() == '1816\n'
        w.close.assert_called()
        getpid.assert_called_with()
        osopen.assert_called_with(
            p.path, platforms.PIDFILE_FLAGS, platforms.PIDFILE_MODE,
        )
        fdopen.assert_called_with(13, 'w')
        fsync.assert_called_with(13)
>       open_.assert_called_with(p.path)

.../unit/utils/test_platforms.py:733: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <MagicMock name='open' id='140464460109136'>, args = ('/var/pid',)
kwargs = {}, expected = call('/var/pid')
actual = call('/var/pid', encoding='utf-8')
_error_message = <function NonCallableMock.assert_called_with.<locals>._error_message at 0x7fc052d7ab90>
cause = None

    def assert_called_with(self, /, *args, **kwargs):
        """assert that the last call was made with the specified arguments.
    
        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            actual = 'not called.'
            error_message = ('expected call not found.\nExpected: %s\n  Actual: %s'
                    % (expected, actual))
            raise AssertionError(error_message)
    
        def _error_message():
            msg = self._format_mock_failure_message(args, kwargs)
            return msg
        expected = self._call_matcher(_Call((args, kwargs), two=True))
        actual = self._call_matcher(self.call_args)
        if actual != expected:
            cause = expected if isinstance(expected, Exception) else None
>           raise AssertionError(_error_message()) from cause
E           AssertionError: expected call not found.
E           Expected: open('/var/pid')
E             Actual: open('/var/pid', encoding='utf-8')

.../hostedtoolcache/Python/3.14.2.../x64/lib/python3.14/unittest/mock.py:985: AssertionError

To view more test analytics, go to the Test Analytics Dashboard
📋 Got 3 mins? Take this short survey to help us improve Test Analytics.

@auvipy

auvipy commented May 9, 2026

Copy link
Copy Markdown
Member

the tests are failing

@auvipy auvipy modified the milestones: 5.7.0, 5.8.0 Aug 27, 2026

This branch has not been deployed

No deployments
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.

3 participants