From 858bab7ff97b12c15f63627d7c069fd35098bb47 Mon Sep 17 00:00:00 2001 From: Nick Porter Date: Thu, 21 Mar 2024 13:45:12 +0000 Subject: [PATCH] fixes #66252 correct use of egrep to parse semanage output --- changelog/66252.fixed.md | 1 + salt/modules/selinux.py | 2 +- tests/pytests/unit/modules/test_selinux.py | 32 ++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 changelog/66252.fixed.md diff --git a/changelog/66252.fixed.md b/changelog/66252.fixed.md new file mode 100644 index 000000000000..2227c8998448 --- /dev/null +++ b/changelog/66252.fixed.md @@ -0,0 +1 @@ +Applying `selinux.fcontext_policy_present` to a shorter path than an existing entry now works diff --git a/salt/modules/selinux.py b/salt/modules/selinux.py index da7d0bc3beee..44e0bd48b30a 100644 --- a/salt/modules/selinux.py +++ b/salt/modules/selinux.py @@ -616,7 +616,7 @@ def _fcontext_add_or_delete_policy( if "add" == action: # need to use --modify if context for name file exists, otherwise ValueError filespec = re.escape(name) - cmd = f"semanage fcontext -l | egrep '{filespec}'" + cmd = f"semanage fcontext -l | egrep '{filespec} '" current_entry_text = __salt__["cmd.shell"](cmd, ignore_retcode=True) if current_entry_text != "": action = "modify" diff --git a/tests/pytests/unit/modules/test_selinux.py b/tests/pytests/unit/modules/test_selinux.py index b67a1b525774..818a5f97a496 100644 --- a/tests/pytests/unit/modules/test_selinux.py +++ b/tests/pytests/unit/modules/test_selinux.py @@ -410,3 +410,35 @@ def test_selinux_add_policy_regex(name, sel_type): mock_cmd_run_all.assert_called_once_with( expected_cmd_run_all, ) + + +@pytest.mark.parametrize( + "name,sel_type", + ( + ("/usr/share/munin/plugins/mysql_queries", "services_munin_plugin_exec_t"), + ("/usr/share/munin/plugins/mysql_", "unconfined_munin_plugin_exec_t"), + ), +) +def test_selinux_add_policy_shorter_path(name, sel_type): + """ + Test adding policy with a shorter path than an existing entry + """ + mock_cmd_shell = MagicMock(return_value={"retcode": 0}) + mock_cmd_run_all = MagicMock(return_value={"retcode": 0}) + + with patch.dict(selinux.__salt__, {"cmd.shell": mock_cmd_shell}), patch.dict( + selinux.__salt__, {"cmd.run_all": mock_cmd_run_all} + ): + selinux.fcontext_add_policy(name, sel_type=sel_type) + filespec = re.escape(name) + expected_cmd_shell = f"semanage fcontext -l | egrep '{filespec}'" + mock_cmd_shell.assert_called_once_with( + expected_cmd_shell, + ignore_retcode=True, + ) + expected_cmd_run_all = ( + f"semanage fcontext --modify --type {sel_type} {filespec}" + ) + mock_cmd_run_all.assert_called_once_with( + expected_cmd_run_all, + )