Language: Python
Label: safe
CWE: CWE-269 \u2014 Improper Privilege Management
The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.

Code:
def run_as_real_user(
    args: list[str], *, get_user_env: bool = False, **kwargs
) -> None:
    """Call subprocess.run as real user if called via sudo/pkexec.

    If we are called through pkexec/sudo, determine the real user ID and
    run the command with it to get the user's web browser settings.
    If get_user_env is set to True, the D-BUS address and XDG_DATA_DIRS
    is grabbed from a running gvfsd and added to the process environment.
    """
    uid = _get_env_int("SUDO_UID", _get_env_int("PKEXEC_UID"))
    if uid is None or not get_process_user_and_group().is_root():
        subprocess.run(args, check=False, **kwargs)
        return

    pwuid = pwd.getpwuid(uid)

    gid = _get_env_int("SUDO_GID")
    if gid is None:
        gid = pwuid.pw_gid

    env = {
        k: v
        for k, v in os.environ.items()
        if not k.startswith("SUDO_") and k != "PKEXEC_UID"
    }
    if get_user_env:
        env |= _get_users_environ(uid)
    env["HOME"] = pwuid.pw_dir
    subprocess.run(
        args,
        check=False,
        env=env,
        user=uid,
        group=gid,
        extra_groups=os.getgrouplist(pwuid.pw_name, gid),
        **kwargs,
    )