surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! Verified downloads of a pinned tool from a GitHub release (M52): the
//! plumbing of SkillSpector's private uv
//! ([`super::skillspector::uv::PrivateUv`]). https only, from
//! [`DOWNLOAD_HOSTS`] only, redirects followed one
//! at a time, the proxy from the injected [`Env`]; what is fetched is
//! counted and hashed ([`Hashing`]) so the caller can check it against the
//! SHA-256 compiled into Surjection.
//!
//! These are real files on purpose (`std::fs`, not [`crate::fs::Fs`]): a
//! process runs them.

use std::io::{Read, Write};
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use sha2::{Digest, Sha256};
use ureq::tls::{RootCerts, TlsConfig};

use super::process::hex;
use crate::catalog::http::proxy;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};

/// Hosts a download may be served from: the release page and the two
/// storage hosts GitHub redirects release assets to.
pub const DOWNLOAD_HOSTS: &[&str] = &[
    "github.com",
    "objects.githubusercontent.com",
    "release-assets.githubusercontent.com",
];
/// Redirects followed (GitHub uses one).
const MAX_REDIRECTS: usize = 5;

/// Fetches one URL into `out`, at most `max` bytes, reporting
/// `(received, total)` (`total` 0 when unknown) and stopping with
/// `canceled` once `cancel` is set. Other errors are
/// `scanner_download_failed`.
pub trait Download: Send + Sync {
    fn fetch(
        &self,
        url: &str,
        out: &mut dyn Write,
        max: u64,
        progress: &mut dyn FnMut(u64, u64),
        cancel: Option<&AtomicBool>,
    ) -> Result<u64, CoreError>;
}

/// [`Download`] over `ureq` (rustls, the platform's certificate verifier),
/// with the proxy from the injected [`Env`] (`HTTPS_PROXY`, then
/// `ALL_PROXY`; a SOCKS or unusable proxy is an error, never a direct
/// connection). https only; redirects are followed here, one at a time,
/// and only to [`DOWNLOAD_HOSTS`].
pub struct UreqDownload {
    agent: ureq::Agent,
    problem: Option<String>,
}

impl std::fmt::Debug for UreqDownload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("UreqDownload").finish_non_exhaustive()
    }
}

impl UreqDownload {
    pub fn new(env: &Env) -> Self {
        let (proxy, problem) = match proxy(
            env,
            &["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"],
        ) {
            Ok(proxy) => (proxy, None),
            Err(why) => (None, Some(why)),
        };
        let agent = ureq::Agent::config_builder()
            .http_status_as_error(false)
            .https_only(true)
            .max_redirects(0)
            .timeout_connect(Some(Duration::from_secs(15)))
            .timeout_recv_response(Some(Duration::from_secs(30)))
            .timeout_global(Some(Duration::from_secs(15 * 60)))
            .user_agent(format!("Surjection/{}", env!("CARGO_PKG_VERSION")))
            .proxy(proxy)
            .tls_config(
                TlsConfig::builder()
                    .root_certs(RootCerts::PlatformVerifier)
                    .build(),
            )
            .build()
            .new_agent();
        Self { agent, problem }
    }
}

fn failed(url: &str, why: impl std::fmt::Display) -> CoreError {
    CoreError::new(
        ErrorCode::ScannerDownloadFailed,
        format!(
            "the file could not be downloaded from {}: {why}",
            crate::catalog::http::host_of(url)
        ),
    )
}

/// Refuses an address that is not https on one of [`DOWNLOAD_HOSTS`]
/// (default port).
pub fn check_download_url(url: &str) -> Result<url::Url, CoreError> {
    let parsed = url::Url::parse(url).map_err(|_| failed(url, "the address does not parse"))?;
    let allowed = parsed.scheme() == "https"
        && parsed.port().is_none()
        && parsed.username().is_empty()
        && parsed.password().is_none()
        && parsed
            .host_str()
            .is_some_and(|host| DOWNLOAD_HOSTS.contains(&host));
    if !allowed {
        return Err(failed(
            url,
            "it redirected to an address Surjection does not download from",
        ));
    }
    Ok(parsed)
}

impl Download for UreqDownload {
    /// [`UreqDownload::download`], logged with the host only (SPEC 4.5).
    fn fetch(
        &self,
        url: &str,
        out: &mut dyn Write,
        max: u64,
        progress: &mut dyn FnMut(u64, u64),
        cancel: Option<&AtomicBool>,
    ) -> Result<u64, CoreError> {
        let started = Instant::now();
        let result = self.download(url, out, max, progress, cancel);
        crate::diagnostics::log::http("download", url, result.as_ref().map(|_| 200), started);
        result
    }
}

impl UreqDownload {
    fn download(
        &self,
        url: &str,
        out: &mut dyn Write,
        max: u64,
        progress: &mut dyn FnMut(u64, u64),
        cancel: Option<&AtomicBool>,
    ) -> Result<u64, CoreError> {
        if let Some(why) = &self.problem {
            return Err(failed(url, why));
        }
        let mut current = check_download_url(url)?;
        for _ in 0..=MAX_REDIRECTS {
            let response = self
                .agent
                .get(current.as_str())
                .call()
                .map_err(|err| match err {
                    ureq::Error::Timeout(_) => failed(url, "it did not answer in time"),
                    ureq::Error::HostNotFound => failed(url, "the host was not found"),
                    ureq::Error::ConnectionFailed => failed(url, "the connection failed"),
                    other => failed(url, other),
                })?;
            let status = response.status().as_u16();
            if matches!(status, 301 | 302 | 303 | 307 | 308) {
                let location = response
                    .headers()
                    .get("location")
                    .and_then(|value| value.to_str().ok())
                    .ok_or_else(|| failed(url, "a redirect without a location"))?;
                let next = current
                    .join(location)
                    .map_err(|_| failed(url, "a redirect that does not parse"))?;
                current = check_download_url(next.as_str())?;
                continue;
            }
            if status != 200 {
                return Err(failed(url, format!("HTTP status {status}")));
            }
            let total = response
                .headers()
                .get("content-length")
                .and_then(|value| value.to_str().ok())
                .and_then(|value| value.trim().parse::<u64>().ok())
                .unwrap_or(0);
            if total > max {
                return Err(failed(url, "the file is larger than expected"));
            }
            let mut reader = response.into_body().into_reader();
            return copy(&mut reader, out, max, total, progress, cancel).map_err(|err| {
                if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
                    canceled()
                } else if err.kind() == std::io::ErrorKind::FileTooLarge {
                    failed(url, "the file is larger than expected")
                } else {
                    failed(url, err)
                }
            });
        }
        Err(failed(url, "too many redirects"))
    }
}

/// `canceled`: the user stopped the download.
pub(crate) fn canceled() -> CoreError {
    CoreError::new(
        ErrorCode::Canceled,
        "the download was canceled; nothing was installed",
    )
}

/// Copies `reader` into `out`, at most `max` bytes (`FileTooLarge` past
/// it), reporting progress about every 256 KiB; `Interrupted` once
/// `cancel` is set.
pub fn copy(
    reader: &mut dyn Read,
    out: &mut dyn Write,
    max: u64,
    total: u64,
    progress: &mut dyn FnMut(u64, u64),
    cancel: Option<&AtomicBool>,
) -> std::io::Result<u64> {
    const STEP: u64 = 256 * 1024;
    let mut buf = vec![0u8; 64 * 1024];
    let mut received = 0u64;
    let mut reported = 0u64;
    progress(0, total);
    loop {
        if cancel.is_some_and(|flag| flag.load(Ordering::Relaxed)) {
            return Err(std::io::Error::from(std::io::ErrorKind::Interrupted));
        }
        let n = reader.read(&mut buf)?;
        if n == 0 {
            break;
        }
        received += n as u64;
        if received > max {
            return Err(std::io::Error::from(std::io::ErrorKind::FileTooLarge));
        }
        out.write_all(&buf[..n])?;
        if received - reported >= STEP {
            reported = received;
            progress(received, total);
        }
    }
    progress(received, total);
    Ok(received)
}

/// Counts and hashes what is written.
pub(crate) struct Hashing<W: Write> {
    pub(crate) inner: W,
    hasher: Sha256,
    pub(crate) written: u64,
}

impl<W: Write> Hashing<W> {
    pub(crate) fn new(inner: W) -> Self {
        Self {
            inner,
            hasher: Sha256::new(),
            written: 0,
        }
    }

    /// Lowercase hex SHA-256 of everything written.
    pub(crate) fn digest(&self) -> String {
        hex(&self.hasher.clone().finalize())
    }
}

impl<W: Write> Write for Hashing<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let n = self.inner.write(buf)?;
        self.hasher.update(&buf[..n]);
        self.written += n as u64;
        Ok(n)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}

/// The size and lowercase hex SHA-256 of the file at `path`.
pub(crate) fn hash_file(path: &Path) -> std::io::Result<(u64, String)> {
    let mut file = std::fs::File::open(path)?;
    let mut sink = Hashing::new(std::io::sink());
    std::io::copy(&mut file, &mut sink)?;
    Ok((sink.written, sink.digest()))
}

/// Flushes a [`Hashing`] file sink to disk; its size and SHA-256.
pub(crate) fn finish_file(
    sink: Hashing<std::io::BufWriter<std::fs::File>>,
    path: &Path,
) -> Result<(u64, String), CoreError> {
    let digest = sink.digest();
    let written = sink.written;
    let file = sink
        .inner
        .into_inner()
        .map_err(|err| io("cannot write file", path, err.error()))?;
    file.sync_all()
        .map_err(|err| io("cannot write file", path, &err))?;
    Ok((written, digest))
}

pub(crate) fn io(what: &str, path: &Path, err: &std::io::Error) -> CoreError {
    CoreError::new(ErrorCode::IoError, format!("{what}: {err}")).with_path(path)
}

/// Lets the owner run `path` (Unix; nothing to do on Windows).
#[cfg(unix)]
pub(crate) fn make_executable(path: &Path) -> Result<(), CoreError> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755))
        .map_err(|err| io("cannot make the file executable", path, &err))
}

#[cfg(not(unix))]
pub(crate) fn make_executable(_path: &Path) -> Result<(), CoreError> {
    Ok(())
}