Skip to content

Visual Studio Code, rebuilt in Rust

Rust
4.9 KB
Raw Blame
//! base/node/unc.ts and the UNC host allowlist Electron's Node checks before each `fs` access on Windows
//! (`ERR_UNC_HOST_NOT_ALLOWED`). The port has no patched `fs`: the file service, the text file models and
//! webview resources call `check_unc_access` before they touch a path.

use std::path::Path;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};

static RESTRICTED: AtomicBool = AtomicBool::new(true);
static ALLOWLIST: Mutex<Vec<String>> = Mutex::new(Vec::new());

/// `getUNCHostAllowlist`.
pub fn unc_host_allowlist() -> Vec<String> {
    ALLOWLIST.lock().unwrap().clone()
}

/// `addUNCHostToAllowlist`: Windows only, lowercased (UNC hosts are case-insensitive).
pub fn add_unc_host_to_allowlist(host: &str) {
    let host = host.to_lowercase();
    let added_on_this_thread = THREAD_ALLOWLIST.with_borrow_mut(|allowlist| allowlist.as_mut().map(|allowlist| allowlist.push(host.clone())).is_some());
    if added_on_this_thread || !cfg!(windows) {
        return;
    }
    let mut allowlist = ALLOWLIST.lock().unwrap();
    if !allowlist.contains(&host) {
        allowlist.push(host);
    }
}

/// `addUNCHostToAllowlist` of the `security.allowedUNCHosts` value: its strings, other entries skipped.
pub fn add_unc_hosts_to_allowlist(hosts: &serde_json::Value) {
    for host in hosts.as_array().into_iter().flatten().filter_map(|host| host.as_str()) {
        add_unc_host_to_allowlist(host);
    }
}

/// `disableUNCAccessRestrictions`.
pub fn disable_unc_access_restrictions() {
    if cfg!(windows) {
        RESTRICTED.store(false, Ordering::Relaxed);
    }
}

/// `isUNCAccessRestrictionsDisabled`.
pub fn is_unc_access_restrictions_disabled() -> bool {
    !cfg!(windows) || !RESTRICTED.load(Ordering::Relaxed)
}

/// `getUNCHost`: the host of a `\\host\`, `\\?\UNC\host\` or `\\.\UNC\host\` path.
pub fn unc_host(path: &str) -> Option<&str> {
    for root in [r"\\.\UNC\", r"\\?\UNC\", r"\\"] {
        let Some(rest) = path.strip_prefix(root) else { continue };
        let Some(end) = rest.find('\\') else { continue };
        if end > 0 {
            return Some(&rest[..end]);
        }
    }
    None
}

/// utilityProcess.ts: the variables that carry this process's UNC restrictions to a Node process it starts.
pub fn utility_process_env() -> Option<(String, String)> {
    cfg!(windows).then(|| unc_env(is_unc_access_restrictions_disabled(), &unc_host_allowlist()))
}

fn unc_env(disabled: bool, allowlist: &[String]) -> (String, String) {
    match disabled {
        true => ("NODE_DISABLE_UNC_ACCESS_CHECKS".to_owned(), "1".to_owned()),
        false => ("NODE_UNC_HOST_ALLOWLIST".to_owned(), allowlist.join("\\")),
    }
}

/// `isPathAllowedByUNCHostAllowlist`: not a UNC path, or one of an allowed host; a path that starts like a UNC path
/// without a host it understands fails closed.
pub fn is_path_allowed_by_unc_host_allowlist(path: &str, allowed_hosts: &[String]) -> bool {
    if let Some(host) = unc_host(path) {
        return allowed_hosts.iter().any(|allowed| allowed.to_lowercase() == host.to_lowercase());
    }
    !(path.starts_with(['\\', '/']) && path[1..].starts_with(['\\', '/']))
}

/// `isUNCAccessAllowed`.
pub fn is_unc_access_allowed(path: &Path) -> bool {
    check_unc_access(path).is_ok()
}

/// The error Electron's `fs` throws for a path `is_unc_access_allowed` refuses.
pub fn check_unc_access(path: &Path) -> std::io::Result<()> {
    let Some(allowlist) = THREAD_ALLOWLIST.with_borrow(Clone::clone).or_else(|| (!is_unc_access_restrictions_disabled()).then(unc_host_allowlist)) else {
        return Ok(());
    };
    match unc_access_error(&path.to_string_lossy(), &allowlist) {
        Some(message) => Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, message)),
        None => Ok(()),
    }
}

thread_local! {
    static THREAD_ALLOWLIST: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
}

/// For tests on any OS: Windows' restrictions with `allowlist` on this thread, `None` back to the process's.
pub fn restrict_unc_access_on_this_thread(allowlist: Option<&[&str]>) {
    THREAD_ALLOWLIST.set(allowlist.map(|hosts| hosts.iter().map(|host| host.to_lowercase()).collect()));
}

/// diskFileSystemProvider.ts `toFileSystemProviderError` of `ERR_UNC_HOST_NOT_ALLOWED`.
pub fn provider_message(error: &std::io::Error) -> String {
    format!("{error}. Please update the 'security.allowedUNCHosts' setting if you want to allow this host.")
}

/// Electron's `ERR_UNC_HOST_NOT_ALLOWED` message for a path its allowlist refuses. Node checks the namespaced path
/// (`path.toNamespacedPath`), in which `/` is a separator, so `//host/share` is a UNC path too.
pub fn unc_access_error(path: &str, allowed_hosts: &[String]) -> Option<String> {
    let path = path.replace('/', "\\");
    if is_path_allowed_by_unc_host_allowlist(&path, allowed_hosts) {
        return None;
    }
    Some(format!("UNC host '{}' access is not allowed", unc_host(&path).unwrap_or_default()))
}

#[cfg(test)]
mod tests;