forked from p15670423/monkey
island: Move file_has_expected_permissions() to file_utils.py
Rename to `has_expected_permissions()` as `file_has_expected_permissions()` is now reduntant. Add unit tests
This commit is contained in:
parent
36314f09ae
commit
a45848ce0c
|
@ -3,3 +3,10 @@ import os
|
|||
|
||||
def expand_path(path: str) -> str:
|
||||
return os.path.expandvars(os.path.expanduser(path))
|
||||
|
||||
|
||||
def has_expected_permissions(path: str, expected_permissions: int) -> bool:
|
||||
file_mode = os.stat(path).st_mode
|
||||
file_permissions = file_mode & 0o777
|
||||
|
||||
return file_permissions == expected_permissions
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
import os
|
||||
|
||||
from common.utils.exceptions import InsecurePermissionsError
|
||||
from monkey_island.cc.server_utils.file_utils import has_expected_permissions
|
||||
|
||||
|
||||
def ensure_file_existence(file: str) -> None:
|
||||
|
@ -9,14 +10,7 @@ def ensure_file_existence(file: str) -> None:
|
|||
|
||||
|
||||
def ensure_file_permissions(file: str) -> None:
|
||||
if not file_has_expected_permissions(path=file, expected_permissions="0o400"):
|
||||
if not has_expected_permissions(path=file, expected_permissions="0o400"):
|
||||
raise InsecurePermissionsError(
|
||||
f"{file} has insecure permissions. Required permissions: 400. Exiting."
|
||||
)
|
||||
|
||||
|
||||
def file_has_expected_permissions(path: str, expected_permissions: str) -> bool:
|
||||
file_mode = os.stat(path).st_mode
|
||||
file_permissions = oct(file_mode & 0o777)
|
||||
|
||||
return file_permissions == expected_permissions
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from monkey_island.cc.server_utils import file_utils
|
||||
|
||||
|
||||
|
@ -15,3 +17,28 @@ def test_expand_vars(patched_home_env):
|
|||
expected_path = os.path.join(patched_home_env, "test")
|
||||
|
||||
assert file_utils.expand_path(input_path) == expected_path
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Tests Posix (not Windows) permissions.")
|
||||
def test_has_expected_permissions_true(tmpdir):
|
||||
file_name = f"{tmpdir}/test"
|
||||
|
||||
create_empty_file(file_name)
|
||||
os.chmod(file_name, 0o754)
|
||||
|
||||
assert file_utils.has_expected_permissions(file_name, 0o754)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="Tests Posix (not Windows) permissions.")
|
||||
def test_has_expected_permissions_false(tmpdir):
|
||||
file_name = f"{tmpdir}/test"
|
||||
|
||||
create_empty_file(file_name)
|
||||
os.chmod(file_name, 0o755)
|
||||
|
||||
assert not file_utils.has_expected_permissions(file_name, 0o700)
|
||||
|
||||
|
||||
def create_empty_file(file_name):
|
||||
with open(file_name, "w"):
|
||||
pass
|
||||
|
|
Loading…
Reference in New Issue