nu_command/experimental/
is_admin.rs

1use nu_engine::command_prelude::*;
2
3#[derive(Clone)]
4pub struct IsAdmin;
5
6impl Command for IsAdmin {
7    fn name(&self) -> &str {
8        "is-admin"
9    }
10
11    fn description(&self) -> &str {
12        "Check if nushell is running with administrator or root privileges."
13    }
14
15    fn signature(&self) -> nu_protocol::Signature {
16        Signature::build("is-admin")
17            .category(Category::Core)
18            .input_output_types(vec![(Type::Nothing, Type::Bool)])
19            .allow_variants_without_examples(true)
20    }
21
22    fn search_terms(&self) -> Vec<&str> {
23        vec!["root", "administrator", "superuser", "supervisor"]
24    }
25
26    fn run(
27        &self,
28        _engine_state: &EngineState,
29        _stack: &mut Stack,
30        call: &Call,
31        _input: PipelineData,
32    ) -> Result<PipelineData, ShellError> {
33        Ok(Value::bool(is_root(), call.head).into_pipeline_data())
34    }
35
36    fn examples(&self) -> Vec<Example> {
37        vec![
38            Example {
39                description: "Return 'iamroot' if nushell is running with admin/root privileges, and 'iamnotroot' if not.",
40                example: r#"if (is-admin) { "iamroot" } else { "iamnotroot" }"#,
41                result: Some(Value::test_string("iamnotroot")),
42            },
43        ]
44    }
45}
46
47/// Returns `true` if user is root; `false` otherwise
48fn is_root() -> bool {
49    is_root_impl()
50}
51
52#[cfg(unix)]
53fn is_root_impl() -> bool {
54    nix::unistd::Uid::current().is_root()
55}
56
57#[cfg(windows)]
58fn is_root_impl() -> bool {
59    use windows::Win32::{
60        Foundation::{CloseHandle, HANDLE},
61        Security::{GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY},
62        System::Threading::{GetCurrentProcess, OpenProcessToken},
63    };
64
65    let mut elevated = false;
66
67    // Checks whether the access token associated with the current process has elevated privileges.
68    // SAFETY: `elevated` only touched by safe code.
69    // `handle` lives long enough, initialized, mutated, used and closed with validity check.
70    // `elevation` only read on success and passed with correct `size`.
71    unsafe {
72        let mut handle = HANDLE::default();
73
74        // Opens the access token associated with the current process.
75        if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle).is_ok() {
76            let mut elevation = TOKEN_ELEVATION::default();
77            let mut size = std::mem::size_of::<TOKEN_ELEVATION>() as u32;
78
79            // Retrieves elevation token information about the access token associated with the current process.
80            // Call available since XP
81            // https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation
82            if GetTokenInformation(
83                handle,
84                TokenElevation,
85                Some(&mut elevation as *mut TOKEN_ELEVATION as *mut _),
86                size,
87                &mut size,
88            )
89            .is_ok()
90            {
91                // Whether the token has elevated privileges.
92                // Safe to read as `GetTokenInformation` will not write outside `elevation` and it succeeded
93                // See: https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation#parameters
94                elevated = elevation.TokenIsElevated != 0;
95            }
96        }
97
98        if !handle.is_invalid() {
99            // Closes the object handle.
100            let _ = CloseHandle(handle);
101        }
102    }
103
104    elevated
105}
106
107#[cfg(target_arch = "wasm32")]
108fn is_root_impl() -> bool {
109    // in wasm we don't have a user system, so technically we are never root
110    false
111}