pub const ALLOW_PRIVILEGED_ENV: &str = "RUNNING_PROCESS_BROKER_ALLOW_PRIVILEGED";
#[derive(Debug, thiserror::Error)]
pub enum PrivilegeError {
#[error(
"running-process-broker-v1 refuses to run as {identity} by default; set {ALLOW_PRIVILEGED_ENV}=1 only for isolated test environments"
)]
Privileged {
identity: PrivilegedIdentity,
},
#[error("failed to determine broker process privilege: {0}")]
PlatformLookup(String),
}
pub use crate::platform::host::PrivilegedIdentity;
pub fn refuse_privileged_run() -> Result<(), PrivilegeError> {
if allow_privileged_from_env() {
return Ok(());
}
refuse_process_privilege(current_process_privilege()?)
}
fn refuse_process_privilege(identity: Option<PrivilegedIdentity>) -> Result<(), PrivilegeError> {
match identity {
Some(identity) => Err(PrivilegeError::Privileged { identity }),
None => Ok(()),
}
}
fn allow_privileged_from_env() -> bool {
crate::env_vars::BROKER_ALLOW_PRIVILEGED.is_set()
}
fn current_process_privilege() -> Result<Option<PrivilegedIdentity>, PrivilegeError> {
crate::platform::host::current_process_privilege()
.map_err(|error| PrivilegeError::PlatformLookup(error.to_string()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::env_vars::EnvKind;
#[test]
fn refuses_privileged_identity() {
let err = refuse_process_privilege(Some(PrivilegedIdentity::UnixRoot)).unwrap_err();
assert!(matches!(
err,
PrivilegeError::Privileged {
identity: PrivilegedIdentity::UnixRoot
}
));
}
#[test]
fn allows_unprivileged_identity() {
refuse_process_privilege(None).unwrap();
}
#[test]
fn allow_env_value_requires_exact_one() {
assert!(crate::env_vars::BROKER_ALLOW_PRIVILEGED.kind == EnvKind::ExactValue("1"));
}
}