Skip to content

exec runs sudo commands with -u to preserve user #3959

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

Merged
merged 3 commits into from
Mar 26, 2025

Conversation

levkropp
Copy link
Contributor

fixes #3933

I had to run the sudo concierge prepare -p dev --extra-snaps terraform command twice whether I was shelled in with multipass shell or using multipass exec. Running multipass exec juju-dev -- sudo env | grep SUDO_ gives the correct SUDO environment variables

~/CLionProjects/multipass/build$ ./bin/multipass launch noble --disk 50G --memory 4G --cpus 2 --mount .  --name juju-dev
Launched: juju-dev
Mounted '.' into 'juju-dev:'
~/CLionProjects/multipass/build$ ./bin/multipass exec juju-dev -- sudo snap install concierge --classic
concierge 0.11.1 from Jon Seager (jnsgruk✪) installed
frame@frame-laptop:~/CLionProjects/multipass/build$ ./bin/multipass exec juju-dev -- sudo concierge prepare -p dev --extra-snaps terraform
time=2025-02-26T09:49:17.825-05:00 level=INFO msg="Preset selected" preset=dev
time=2025-02-26T09:49:37.624-05:00 level=INFO msg="Installed snap" snap=charmcraft
time=2025-02-26T09:49:47.641-05:00 level=INFO msg="Installed apt package" package=python3-pip
time=2025-02-26T09:49:50.327-05:00 level=INFO msg="Installed snap" snap=jq
time=2025-02-26T09:49:51.198-05:00 level=INFO msg="Installed apt package" package=python3-venv
time=2025-02-26T09:49:54.497-05:00 level=INFO msg="Installed snap" snap=yq
time=2025-02-26T09:50:29.489-05:00 level=INFO msg="Installed snap" snap=rockcraft
time=2025-02-26T09:50:42.662-05:00 level=INFO msg="Installed snap" snap=snapcraft
time=2025-02-26T09:51:02.735-05:00 level=INFO msg="Installed snap" snap=jhack
time=2025-02-26T09:51:08.384-05:00 level=INFO msg="Installed snap" snap=terraform
time=2025-02-26T09:51:22.508-05:00 level=INFO msg="Installed snap" snap=k8s
time=2025-02-26T09:51:28.145-05:00 level=INFO msg="Installed snap" snap=kubectl
time=2025-02-26T09:51:28.621-05:00 level=INFO msg="Refreshed snap" snap=lxd
Command: /snap/bin/k8s status
Output:
Error: The node is not part of a Kubernetes cluster. You can bootstrap a new cluster with:

  sudo k8s bootstrap
time=2025-02-26T09:51:33.206-05:00 level=INFO msg="Prepared provider" provider=lxd
time=2025-02-26T09:53:00.624-05:00 level=INFO msg="Prepared provider" provider=k8s
time=2025-02-26T09:53:19.510-05:00 level=INFO msg="Installed snap" snap=juju
Command: sudo -u ubuntu /snap/bin/juju show-controller concierge-k8s
Output:
{}
ERROR controller concierge-k8s not found
time=2025-02-26T09:53:25.349-05:00 level=INFO msg="Bootstrapping Juju" provider=k8s
Command: sudo -u ubuntu /snap/bin/juju show-controller concierge-lxd
Output:
{}
ERROR controller concierge-lxd not found
time=2025-02-26T09:53:27.397-05:00 level=INFO msg="Bootstrapping Juju" provider=lxd
time=2025-02-26T09:55:00.176-05:00 level=INFO msg="Bootstrapped Juju" provider=k8s
time=2025-02-26T09:56:18.206-05:00 level=INFO msg="Bootstrapped Juju" provider=lxd
~/CLionProjects/multipass/build$ ./bin/multipass exec juju-dev -- sudo concierge prepare -p dev --extra-snaps terraform
time=2025-02-26T09:56:59.249-05:00 level=INFO msg="Preset selected" preset=dev
time=2025-02-26T09:57:01.532-05:00 level=INFO msg="Refreshed snap" snap=jq
time=2025-02-26T09:57:02.270-05:00 level=INFO msg="Installed apt package" package=python3-pip
time=2025-02-26T09:57:02.522-05:00 level=INFO msg="Refreshed snap" snap=yq
time=2025-02-26T09:57:02.889-05:00 level=INFO msg="Installed apt package" package=python3-venv
time=2025-02-26T09:57:03.653-05:00 level=INFO msg="Refreshed snap" snap=rockcraft
time=2025-02-26T09:57:04.715-05:00 level=INFO msg="Refreshed snap" snap=snapcraft
time=2025-02-26T09:57:05.708-05:00 level=INFO msg="Refreshed snap" snap=jhack
time=2025-02-26T09:57:06.733-05:00 level=INFO msg="Refreshed snap" snap=charmcraft
time=2025-02-26T09:57:07.567-05:00 level=INFO msg="Refreshed snap" snap=terraform
time=2025-02-26T09:57:17.126-05:00 level=INFO msg="Refreshed snap" snap=k8s
time=2025-02-26T09:57:17.611-05:00 level=INFO msg="Refreshed snap" snap=lxd
time=2025-02-26T09:57:25.153-05:00 level=INFO msg="Refreshed snap" snap=kubectl
time=2025-02-26T09:57:27.131-05:00 level=INFO msg="Prepared provider" provider=lxd
time=2025-02-26T09:57:49.081-05:00 level=INFO msg="Prepared provider" provider=k8s
time=2025-02-26T09:57:50.248-05:00 level=INFO msg="Refreshed snap" snap=juju
time=2025-02-26T09:57:53.383-05:00 level=INFO msg="Previous Juju controller found" provider=lxd
time=2025-02-26T09:57:54.850-05:00 level=INFO msg="Previous Juju controller found" provider=k8s
~/CLionProjects/multipass/build$ ./bin/multipass exec juju-dev -- juju controllers
Use --refresh option with this command to see the latest information.

Controller      Model    User   Access     Cloud/Region         Models  Nodes    HA  Version
concierge-k8s   testing  admin  superuser  k8s                       2      -     -  3.6.2  
concierge-lxd*  testing  admin  superuser  localhost/localhost       2      1  none  3.6.2  

In order to cd into directories we need to do sudo sh -c because cd cannot be run with sudo. This changes our SUDO_ user. We could use sudo -E to preserve the entire environment but that may cause unintended behavior. Instead we use sudo -u to restore the user. We know the user from the ssh_info.username()

@levkropp levkropp force-pushed the exec-sudo-dir-mapping branch 2 times, most recently from 4a2ddab to 1e95dc2 Compare February 27, 2025 19:54
Copy link

codecov bot commented Feb 27, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 89.14%. Comparing base (1954ca0) to head (f5ca6ad).
Report is 3590 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3959      +/-   ##
==========================================
+ Coverage   89.11%   89.14%   +0.03%     
==========================================
  Files         255      257       +2     
  Lines       14603    14644      +41     
==========================================
+ Hits        13014    13055      +41     
  Misses       1589     1589              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@levkropp levkropp force-pushed the exec-sudo-dir-mapping branch from 1e95dc2 to 15d9e46 Compare February 27, 2025 20:12
@levkropp levkropp marked this pull request as ready for review March 18, 2025 16:36
@levkropp levkropp requested review from xmkg and georgeliao March 18, 2025 16:36
Copy link
Member

@xmkg xmkg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't reviewed the sudo part -- checked code semantics only. Will look into that in the second pass.

// ran with sudo, what forces us to run everything through `sh`.
auto sh_args = fmt::format("cd {} && {}", *dir, fmt::join(args, " "));
// Extract the command without the sudo prefix
std::vector<std::string> cmd_args(args.begin() + 1, args.end());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unchecked iterator access: begin() + 1 might not be present in the args

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also, std::next(args.begin()) would express the intent better here.

Copy link
Member

@xmkg xmkg Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
std::vector<std::string> cmd_args(args.begin() + 1, args.end());
const auto cmd_args = [&args]() -> std::vector<std::string> {
if(args.size() < 2){
return {};
}
return {std::next(args.begin()), args.end()};
}();

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that this change results in a compiler error for me, possibly because the initializer list constructors {std::next(args.begin()), args.end()} create temporary objects that cannot be bound to references when using decltype(args).

multipass/src/client/cli/cmd/exec.cpp: In lambda function:
multipass/src/client/cli/cmd/exec.cpp:174:33: error: returning reference to temporary [-Werror=return-local-addr]
  174 |                         return {};
      |                                 ^
multipass/src/client/cli/cmd/exec.cpp:176:64: error: returning reference to temporary [-Werror=return-local-addr]
  176 |                     return {std::next(args.begin()), args.end()};
      |                                                                ^
cc1plus: all warnings being treated as errors

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah right, I missed that args is a const std::vector<std::string>&. Replacing decltype(args) with std::vector<std::string> should fix the issue.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW feel free to use any approach you're comfortable with -- the code was just an example. I'm okay with any alternative as long as it ensures that the referenced iterators are valid.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the original code is safe with args.begin() + 1 in the if (args[0] == "sudo") branch. Because that guarantees the arguments number is >=1, when there is only one argument args.begin() + 1 is args.end() and will result in cmd_args empty vector, which is expected. As to args.begin() + 1 vs std::next, std::next in the case of std::vector uses random access iterator, so it is the same performance-wise but maybe more expressive as @xmkg mentioned.

Actually, what is dubious to me is if (args[0] == "sudo") check, there is no check whether args is non-empty. So that 0 index deference might be invalid. But this is from the original code instead of this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

std::next in the case of std::vector uses random access iterator, so it is the same performance-wise but maybe more expressive as @xmkg mentioned.

I strongly agree with the benefit of replacing args.begin() + 1 with std::next in terms of readability and expressiveness

I'm okay with any alternative as long as it ensures that the referenced iterators are valid.

I have no issues with a lambda, but I believe we can also do something simpler like

            if (args[0] == "sudo")
            {
                // Extract the command without the sudo prefix
                std::vector<std::string> cmd_args;
                if (args.size() > 1)
                    cmd_args.assign(std::next(args.begin()), args.end());
                
                // Use sudo to access the directory, but run the command as the ubuntu user,
                // then use sudo again to execute the original command
                // This preserves the correct SUDO_ environment variables
                auto sh_args = fmt::format("cd {} && sudo -u {} sudo {}", *dir, username, fmt::join(cmd_args, " "));
                all_args = {{"sudo", "sh", "-c", sh_args}};
            }

@georgeliao thoughts?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new code snippet also looks good to me.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But now if I think about it again with the whole context. You do not need to extract the cmd_args, right? you can just do
const auto sh_args = fmt::format("cd {} && sudo -u {} {}", *dir, username, fmt::join(args, " "));, to avoid the 2nd hard code sudo string because the args[0] is sudo already.

// Use sudo to access the directory, but run the command as the ubuntu user,
// then use sudo again to execute the original command
// This preserves the correct SUDO_ environment variables
auto sh_args = fmt::format("cd {} && sudo -u {} sudo {}", *dir, username, fmt::join(cmd_args, " "));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
auto sh_args = fmt::format("cd {} && sudo -u {} sudo {}", *dir, username, fmt::join(cmd_args, " "));
const auto sh_args = fmt::format("cd {} && sudo -u {} sudo {}", *dir, username, fmt::join(cmd_args, " "));

@georgeliao
Copy link
Contributor

@levkropp
Well done, the sudo -u approach makes sense to me. I also did some functional testing, things worked as expected based on the issue description. I have only left some minor comments and questions.

@levkropp
Copy link
Contributor Author

levkropp commented Mar 21, 2025

After cloning and re-building this PR again, it appears that all tests are passing successfully! And the PR resolves the issue seen with SUDO_ env vars:

/bin/multipass exec juju-dev -- sudo env | grep SUDO_
SUDO_COMMAND=/usr/bin/env
SUDO_USER=ubuntu
SUDO_UID=1000
SUDO_GID=1000

@levkropp levkropp requested a review from georgeliao March 24, 2025 17:06
@georgeliao
Copy link
Contributor

It looks good to me. @levkropp Do we need a rebase to fix the doc build failure?

@georgeliao
Copy link
Contributor

@xmkg I do not have any questions on this PR anymore. Feel free to have a final check. If things are fine, we can go ahead and merge.

@georgeliao georgeliao added this pull request to the merge queue Mar 26, 2025
Merged via the queue into main with commit 13f8025 Mar 26, 2025
15 of 16 checks passed
@georgeliao georgeliao deleted the exec-sudo-dir-mapping branch March 26, 2025 18:52
@ricab ricab added this to the 1.16.0 milestone Jun 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

multipass exec yields unexpected result when command invoked uses sudo
4 participants