Skip to content

Commit

Permalink
refactor: ♻️ refactor run_as logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Jisu-Woniu committed Feb 22, 2024
1 parent 8cecf38 commit 5292b4f
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 35 deletions.
22 changes: 13 additions & 9 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions crates/rsjudge-runner/examples/demo.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
use std::process::Command;

use anyhow::anyhow;
use rsjudge_runner::{
user::{builder, runner},
RunAs,
};
use uzers::{get_current_uid, get_user_by_uid};
fn main() -> anyhow::Result<()> {
let self_output = Command::new("id")
.run_as(&get_user_by_uid(get_current_uid()).ok_or(anyhow!("invalid user"))?)
.output()?;
println!("{}", String::from_utf8_lossy(&self_output.stdout));

let builder_output = Command::new("id").run_as(builder()?).output()?;
println!("{}", String::from_utf8_lossy(&builder_output.stdout));

Expand Down
8 changes: 7 additions & 1 deletion crates/rsjudge-runner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,17 @@ impl RunAs for Command {
fn run_as(&mut self, user: &User) -> &mut Command {
let uid = user.uid();
let gid = user.primary_group_id();
let groups: Vec<_> = user
.groups()
.unwrap_or_default()
.into_iter()
.map(|g| g.gid().into())
.collect();

self.uid(uid).gid(gid);
unsafe {
self.pre_exec(move || {
setgroups(&[gid.into()])?;
setgroups(&groups)?;
Ok(())
})
};
Expand Down
25 changes: 0 additions & 25 deletions crates/rsjudge-runner/src/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,28 +27,3 @@ pub fn runner() -> anyhow::Result<&'static User> {
.as_ref()
.ok_or_else(|| anyhow!("No such user: rsjudge-runner"))
}

#[cfg(all(test, unix))]
mod tests {
use std::{os::unix::process::CommandExt, process::Command};

use super::*;

#[test]
#[ignore = "Requires additional users."]
fn test_uid() -> anyhow::Result<()> {
let builder = builder()?;
let builder_output = Command::new("id")
.uid(builder.uid())
.gid(builder.primary_group_id())
.output()?;
println!("{}", String::from_utf8_lossy(&builder_output.stdout));
let runner = runner()?;
let runner_output = Command::new("id")
.uid(runner.uid())
.gid(runner.primary_group_id())
.output()?;
println!("{}", String::from_utf8_lossy(&runner_output.stdout));
Ok(())
}
}

0 comments on commit 5292b4f

Please sign in to comment.