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

[master] Prevent possible KeyError exception on calling salt.utils.user.get_group_dict #64599

Merged
merged 11 commits into from
Aug 18, 2023
2 changes: 2 additions & 0 deletions changelog/64599.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix possible `KeyError` exceptions in `salt.utils.user.get_group_dict`
while reading improper duplicated GID assigned for the user.
12 changes: 8 additions & 4 deletions salt/utils/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,13 @@ def get_specific_user():
user = get_user()
if salt.utils.platform.is_windows():
if _win_current_user_is_admin():
return "sudo_{}".format(user)
return f"sudo_{user}"
else:
env_vars = ("SUDO_USER",)
if user == "root":
for evar in env_vars:
if evar in os.environ:
return "sudo_{}".format(os.environ[evar])
return f"sudo_{os.environ[evar]}"
return user


Expand All @@ -182,7 +182,7 @@ def chugid(runas, group=None):
target_pw_gid = grp.getgrnam(group).gr_gid
except KeyError as err:
raise CommandExecutionError(
"Failed to fetch the GID for {}. Error: {}".format(group, err)
f"Failed to fetch the GID for {group}. Error: {err}"
)
else:
target_pw_gid = uinfo.pw_gid
Expand Down Expand Up @@ -352,7 +352,11 @@ def get_group_dict(user=None, include_default=True):
group_dict = {}
group_names = get_group_list(user, include_default=include_default)
for group in group_names:
group_dict.update({group: grp.getgrnam(group).gr_gid})
try:
group_dict.update({group: grp.getgrnam(group).gr_gid})
except KeyError:
# In case if imporer duplicate group was returned by get_group_list
pass
return group_dict


Expand Down
21 changes: 21 additions & 0 deletions tests/pytests/functional/utils/user/test_get_group_dict.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import logging

import pytest

import salt.utils.platform
import salt.utils.user
from tests.support.mock import patch

log = logging.getLogger(__name__)

pytestmark = [
pytest.mark.skip_unless_on_linux(
reason="Should only run in platforms which have duplicate GID support"
),
]


def test_get_group_dict_with_improper_duplicate_root_group():
with patch("salt.utils.user.get_group_list", return_value=["+", "root"]):
group_list = salt.utils.user.get_group_dict("root")
assert group_list == {"root": 0}
Loading