Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sure permissions of saved files adhere to umask setting #832

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions annif/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ def atomic_save(
newname = fn.replace(tempfilename, os.path.join(dirname, filename))
logger.debug("renaming temporary file %s to %s", fn, newname)
os.rename(fn, newname)
umask = os.umask(0o777)
os.umask(umask)
os.chmod(newname, 0o666 & ~umask)


def cleanup_uri(uri: str) -> str:
Expand Down
45 changes: 45 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,53 @@
"""Unit tests for Annif utility functions"""

import os
from contextlib import contextmanager

import pytest

import annif.util


@contextmanager
def umask_context(mask):
"""Context manager to temporarily set umask"""
original_umask = os.umask(0o777) # Get current umask
os.umask(mask) # Set new umask
try:
yield
finally:
os.umask(original_umask) # Restore original umask


class MockSaveable:
def save(self, filename):
with open(filename, "w") as f:
f.write("data")


# parametrize test to verify that file permissions are set correctly
# using commonly used umask values
@pytest.mark.parametrize(
"umask,mode", [(0o002, 0o664), (0o022, 0o644), (0o027, 0o640), (0o077, 0o600)]
)
def test_atomic_save(tmpdir, umask, mode):
obj = MockSaveable()
dirname = str(tmpdir)
filename = "myfile"

with umask_context(umask):
annif.util.atomic_save(obj, dirname, filename)

final_path = tmpdir.join(filename)
assert final_path.exists()

# verify file content
assert final_path.read_text(encoding="utf-8") == "data"

# verify file permissions
assert final_path.stat().mode & 0o777 == mode


def test_boolean():
inputs = ["1", "0", "true", "false", "TRUE", "FALSE", "Yes", "No", True, False]
outputs = [True, False, True, False, True, False, True, False, True, False]
Expand Down
Loading