nushell/crates/nu-command/src/experimental/is_admin.rs
Ian Manske 7e1b922ea7
Add functions for each Value case (#9736)
# Description
This PR ensures functions exist to extract and create each and every
`Value` case. It also renames `Value::boolean` to `Value::bool` to match
`Value::test_bool`, `Value::as_bool`, and `Value::Bool`. Similarly,
`Value::as_integer` was renamed to `Value::as_int` to be consistent with
`Value::int`, `Value::test_int`, and `Value::Int`. These two renames can
be undone if necessary.

# User-Facing Changes
No user facing changes, but two public functions were renamed which may
affect downstream dependents.
2023-07-21 08:20:33 -05:00

109 lines
3.6 KiB
Rust

use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Type, Value,
};
#[derive(Clone)]
pub struct IsAdmin;
impl Command for IsAdmin {
fn name(&self) -> &str {
"is-admin"
}
fn usage(&self) -> &str {
"Check if nushell is running with administrator or root privileges."
}
fn signature(&self) -> nu_protocol::Signature {
Signature::build("is-admin")
.category(Category::Core)
.input_output_types(vec![(Type::Nothing, Type::Bool)])
.allow_variants_without_examples(true)
}
fn search_terms(&self) -> Vec<&str> {
vec!["root", "administrator", "superuser", "supervisor"]
}
fn run(
&self,
_engine_state: &EngineState,
_stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
Ok(Value::bool(is_root(), call.head).into_pipeline_data())
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Return 'iamroot' if nushell is running with admin/root privileges, and 'iamnotroot' if not.",
example: r#"if (is-admin) { "iamroot" } else { "iamnotroot" }"#,
result: Some(Value::test_string("iamnotroot")),
},
]
}
}
/// Returns `true` if user is root; `false` otherwise
fn is_root() -> bool {
is_root_impl()
}
#[cfg(unix)]
fn is_root_impl() -> bool {
nix::unistd::Uid::current().is_root()
}
#[cfg(windows)]
fn is_root_impl() -> bool {
use windows::Win32::{
Foundation::{CloseHandle, HANDLE},
Security::{GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY},
System::Threading::{GetCurrentProcess, OpenProcessToken},
};
let mut handle = HANDLE::default();
let mut elevated = false;
// Checks whether the access token associated with the current process has elevated privileges.
// SAFETY: `elevated` only touched by safe code.
// `handle` lives long enough, initialized, mutated as out param, used, closed with validity check.
// `elevation` only read on success and passed with correct `size`.
unsafe {
// Opens the access token associated with the current process.
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut handle).as_bool() {
let mut elevation = TOKEN_ELEVATION::default();
let mut size = std::mem::size_of::<TOKEN_ELEVATION>() as u32;
// Retrieves elevation token information about the access token associated with the current process.
// Call available since XP
// https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation
if GetTokenInformation(
handle,
TokenElevation,
Some(&mut elevation as *mut TOKEN_ELEVATION as *mut _),
size,
&mut size,
)
.as_bool()
{
// Whether the token has elevated privileges.
// Safe to read as `GetTokenInformation` will not write outside `elevation` and it succeeded
// See: https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-gettokeninformation#parameters
elevated = elevation.TokenIsElevated != 0;
}
}
if !handle.is_invalid() {
// Closes the object handle.
CloseHandle(handle);
}
}
elevated
}