Skip to content

Commit d40f8b5

Browse files
fix: add missing checks in os.chmod
1 parent f74cdf8 commit d40f8b5

3 files changed

Lines changed: 36 additions & 0 deletions

File tree

Lib/test/test_os/test_posix.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1109,6 +1109,30 @@ def test_fchmod_file(self):
11091109
self.check_chmod(posix.fchmod, f.fileno())
11101110
self.check_chmod(posix.chmod, f.fileno())
11111111

1112+
@os_helper.skip_unless_working_chmod
1113+
@unittest.skipUnless(os.chmod in os.supports_fd,
1114+
"test needs fd support in os.chmod()")
1115+
@unittest.skipUnless(os.chmod in os.supports_dir_fd,
1116+
"test needs dir_fd support in os.chmod()")
1117+
def test_chmod_fd_with_dir_fd(self):
1118+
with open(os_helper.TESTFN, 'wb+') as f:
1119+
dir_fd = os.open(os.curdir, os.O_RDONLY)
1120+
self.addCleanup(os.close, dir_fd)
1121+
with self.assertRaisesRegex(ValueError,
1122+
'can\'t specify both dir_fd and fd'):
1123+
posix.chmod(f.fileno(), 0o600, dir_fd=dir_fd)
1124+
1125+
@os_helper.skip_unless_working_chmod
1126+
@unittest.skipUnless(os.chmod in os.supports_fd,
1127+
"test needs fd support in os.chmod()")
1128+
@unittest.skipIf(os.name == 'nt',
1129+
'follow_symlinks defaults to False on Windows')
1130+
def test_chmod_fd_follow_symlinks(self):
1131+
with open(os_helper.TESTFN, 'wb+') as f:
1132+
with self.assertRaisesRegex(ValueError,
1133+
'cannot use fd and follow_symlinks together'):
1134+
posix.chmod(f.fileno(), 0o600, follow_symlinks=False)
1135+
11121136
@unittest.skipUnless(hasattr(posix, 'lchmod'), 'test needs os.lchmod()')
11131137
def test_lchmod_file(self):
11141138
self.check_chmod(posix.lchmod, os_helper.TESTFN)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
:func:`os.chmod` now raises :exc:`ValueError` when *dir_fd* or
2+
*follow_symlinks* is used together with a file descriptor *path*, matching
3+
the documented behaviour and :func:`os.chown`.

Modules/posixmodule.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4113,6 +4113,15 @@ os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
41134113
return NULL;
41144114
#endif
41154115

4116+
if (dir_fd_and_fd_invalid("chmod", dir_fd, path->fd))
4117+
return NULL;
4118+
#ifndef MS_WINDOWS
4119+
/* On Windows, follow_symlinks defaults to False, so doing this check
4120+
would reject the valid os.chmod(fd, mode). */
4121+
if (fd_and_follow_symlinks_invalid("chmod", path->is_fd, follow_symlinks))
4122+
return NULL;
4123+
#endif
4124+
41164125
if (PySys_Audit("os.chmod", "Oii", path->object, mode,
41174126
dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
41184127
return NULL;

0 commit comments

Comments
 (0)