summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn Estabrook <jestabro@vyos.io>2026-11-10 08:21:46 -0600
committerGitHub <noreply@github.com>2026-11-10 08:21:46 -0600
commit7c8d8b1a4e7a62e80fddd7164f4e0366c1983f25 (patch)
tree394c64c1218bec8e7da09c5e83d32264a0199ff7
parent0ad0ab7490f3cdc23f2702152c0fa60e2ca1bec4 (diff)
parent2ddaeff36fdeb0684953634fdb85cfcd87e51e7a (diff)
downloadvyos-1x-7c8d8b1a4e7a62e80fddd7164f4e0366c1983f25.tar.gz
vyos-1x-7c8d8b1a4e7a62e80fddd7164f4e0366c1983f25.zip
Merge pull request #5636 from jestabro/perms-write-file
T9590: fix order of set perms/ownership and first write in utils write_file
-rw-r--r--python/vyos/utils/file.py16
-rw-r--r--src/tests/test_utils_file.py70
2 files changed, 83 insertions, 3 deletions
diff --git a/python/vyos/utils/file.py b/python/vyos/utils/file.py
index b21f56d5f..e31e8af26 100644
--- a/python/vyos/utils/file.py
+++ b/python/vyos/utils/file.py
@@ -62,21 +62,31 @@ def write_file(fname, data, defaultonfailure=None, user=None, group=None,
If directory of file is not present, it is auto-created.
"""
+ from stat import S_IMODE
+
dirname = os.path.dirname(fname)
if dirname and not os.path.isdir(dirname):
os.makedirs(dirname, mode=0o755, exist_ok=False)
chown(dirname, user, group)
+ def opener(path, flags):
+ if os.path.exists(fname):
+ cur_mode = S_IMODE(os.stat(fname).st_mode)
+ else:
+ cur_mode = 0o664
+ set_mode = mode & cur_mode if mode else cur_mode
+ return os.open(path, flags, mode=set_mode)
+
try:
""" Write a file to string """
bytes = 0
- with open(fname, 'w' if not append else 'a') as f:
+ with open(fname, 'w' if not append else 'a', opener=opener) as f:
+ chown(f.fileno(), user, group)
+ chmod(f.fileno(), mode)
bytes = f.write(data)
if trailing_newline and not data.endswith('\n'):
f.write('\n')
bytes += 1
- chown(fname, user, group)
- chmod(fname, mode)
return bytes
except Exception as e:
if defaultonfailure is not None:
diff --git a/src/tests/test_utils_file.py b/src/tests/test_utils_file.py
index 4519cf03c..b4d5191d9 100644
--- a/src/tests/test_utils_file.py
+++ b/src/tests/test_utils_file.py
@@ -12,11 +12,15 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
+import os
+import stat
import tempfile
import unittest
+from unittest import mock
from pathlib import Path
+import vyos.utils.file
from vyos.utils.file import copy_recursive
from vyos.utils.file import move_recursive
@@ -84,3 +88,69 @@ class TestVyOSUtilsFile(unittest.TestCase):
content = (self.dst / 'file1.txt').read_text()
self.assertEqual(content, 'hello world') # overwritten
self.assertFalse(self.src.exists()) # source cleaned up
+
+
+class _SpyFile:
+ """Proxy around a file object that records perms on each write."""
+
+ def __init__(self, fh, log):
+ self._fh = fh
+ self._log = log
+
+ def write(self, data):
+ self._log.append(stat.S_IMODE(os.fstat(self._fh.fileno()).st_mode))
+ return self._fh.write(data)
+
+ def writelines(self, lines):
+ for line in lines:
+ self.write(line)
+
+ def __enter__(self):
+ self._fh.__enter__()
+ return self
+
+ def __exit__(self, *exc):
+ return self._fh.__exit__(*exc)
+
+ def __getattr__(self, name):
+ return getattr(self._fh, name)
+
+
+EXPECTED_MODE = 0o600
+
+
+class TestWriteFilePermissions(unittest.TestCase):
+ def setUp(self):
+ # pylint: disable=consider-using-with
+ self._tmp = tempfile.TemporaryDirectory()
+ self.path = os.path.join(self._tmp.name, 'dummy.txt')
+ # Set umask so default perms are known.
+ self._old_umask = os.umask(0o022)
+
+ def tearDown(self):
+ os.umask(self._old_umask)
+ self._tmp.cleanup()
+
+ def test_permissions_at_write(self):
+ real_open = open
+ modes_at_write = []
+
+ def spy_open(file, *args, **kwargs):
+ # pylint: disable=consider-using-with
+ fh = real_open(file, *args, **kwargs)
+ if os.fspath(file) == self.path:
+ return _SpyFile(fh, modes_at_write)
+ return fh
+
+ with mock.patch.object(
+ vyos.utils.file, 'open', side_effect=spy_open, create=True
+ ) as mock_open:
+ vyos.utils.file.write_file(self.path, 'secret data', mode=EXPECTED_MODE)
+
+ mock_open.assert_called()
+ self.assertTrue(modes_at_write, 'write() was not called')
+ self.assertEqual(
+ modes_at_write[0],
+ EXPECTED_MODE,
+ f'first write happened with mode {oct(modes_at_write[0])}, expected {oct(EXPECTED_MODE)}',
+ )