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![Example {
38            description: "Return 'iamroot' if nushell is running with admin/root privileges, and 'iamnotroot' if not.",
39            example: r#"if (is-admin) { "iamroot" } else { "iamnotroot" }"#,
40            result: Some(Value::test_string("iamnotroot")),
41        }]
42    }
43}
44
45/// Returns `true` if user is root; `false` otherwise
46fn is_root() -> bool {
47    is_root_impl()
48}
49
50#[cfg(unix)]
51fn is_root_impl() -> bool {
52    nix::unistd::Uid::current().is_root()
53}
54
55#[cfg(windows)]
56fn is_root_impl() -> bool {
57    use windows::Win32::{
58        Foundation::{CloseHandle, HANDLE},
59        Security::{GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation},
60        System::Threading::{GetCurrentProcess, OpenProcessToken},
61    };
62
63    let mut elevated = false;
64
65    // Checks whether the access token associated with the current process has elevated privileges.
66    // SAFETY: `elevated` only touched by safe code.
67    // `handle` lives long enough, initialized, mutated, used and closed with validity check.
68    // `elevation` only read on success and passed with correct `size`.
69    unsafe {
70        let mut handle = HANDLE::default();
71
72        // Opens the access token associated with the current process.
73        if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle).is_ok() {
74            let mut elevation = TOKEN_ELEVATION::default();
75            let mut size = std::mem::size_of::<TOKEN_ELEVATION>() as u32;
76
77            // Retrieves elevation token information about the access token associated with the current process.
78            // Call available since XP
79            // https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation
80            if GetTokenInformation(
81                handle,
82                TokenElevation,
83                Some(&mut elevation as *mut TOKEN_ELEVATION as *mut _),
84                size,
85                &mut size,
86            )
87            .is_ok()
88            {
89                // Whether the token has elevated privileges.
90                // Safe to read as `GetTokenInformation` will not write outside `elevation` and it succeeded
91                // See: https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation#parameters
92                elevated = elevation.TokenIsElevated != 0;
93            }
94        }
95
96        if !handle.is_invalid() {
97            // Closes the object handle.
98            let _ = CloseHandle(handle);
99        }
100    }
101
102    elevated
103}
104
105#[cfg(target_arch = "wasm32")]
106fn is_root_impl() -> bool {
107    // in wasm we don't have a user system, so technically we are never root
108    false
109}