zc2 0.0.46

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Fetch from `get.zakuro-ai.com` with `X-Content-SHA256` verification (#378,
//! ADR ZC-0014). Nothing is returned, and so nothing can be written or used,
//! unless the body matches the digest the server sent.
//!
//! The header is an integrity check against corruption and a mismatched cache
//! or proxy, not an authenticity proof: an attacker who controls the server
//! controls the header. HTTPS provides the authenticity.
//!
//! A missing header is rejected. The server always sends it on `/env`, `/zk0`
//! and the installers, so an absent header means a downgrade or an unexpected
//! intermediary, and accepting it would let a stripper bypass the check.

/// Base URL for every get.zakuro-ai.com fetch. HTTPS only (guarded by a test).
pub const GET_BASE: &str = "https://get.zakuro-ai.com";

pub const HASH_HEADER: &str = "X-Content-SHA256";

/// Check `body` against the digest from the `X-Content-SHA256` header value.
pub fn verify_body(url: &str, body: &[u8], header: Option<&str>) -> Result<(), String> {
    let expected = header
        .map(|h| h.trim().to_ascii_lowercase())
        .filter(|h| !h.is_empty())
        .ok_or_else(|| {
            format!("GET {url}: response has no {HASH_HEADER} header; refusing unverified content")
        })?;
    let actual = hex::encode(ring::digest::digest(&ring::digest::SHA256, body));
    if actual != expected {
        return Err(format!(
            "GET {url}: integrity check failed ({HASH_HEADER} {expected} != body sha256 {actual}); content rejected"
        ));
    }
    Ok(())
}

/// GET `url` and return the body only if it matches `X-Content-SHA256`.
pub fn fetch_verified(agent: &ureq::Agent, url: &str) -> Result<String, String> {
    let mut resp = agent
        .get(url)
        .call()
        .map_err(|e| format!("GET {url}: {e}"))?;
    let header = resp
        .headers()
        .get(HASH_HEADER)
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);
    let body = resp
        .body_mut()
        .read_to_vec()
        .map_err(|e| format!("reading {url}: {e}"))?;
    verify_body(url, &body, header.as_deref())?;
    String::from_utf8(body).map_err(|e| format!("GET {url}: body is not UTF-8: {e}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    const BODY: &str = "export FOO=bar\n";

    fn sha(b: &str) -> String {
        hex::encode(ring::digest::digest(&ring::digest::SHA256, b.as_bytes()))
    }

    /// One-shot local server answering a single request.
    fn serve(body: &'static str, header: Option<String>) -> String {
        let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
        let addr = server.server_addr().to_ip().unwrap();
        std::thread::spawn(move || {
            if let Ok(req) = server.recv() {
                let mut resp = tiny_http::Response::from_string(body);
                if let Some(h) = header {
                    resp = resp.with_header(
                        tiny_http::Header::from_bytes(HASH_HEADER.as_bytes(), h.as_bytes())
                            .unwrap(),
                    );
                }
                let _ = req.respond(resp);
            }
        });
        format!("http://{addr}/env")
    }

    fn agent() -> ureq::Agent {
        ureq::Agent::new_with_config(ureq::Agent::config_builder().build())
    }

    #[test]
    fn matching_digest_is_accepted() {
        let url = serve(BODY, Some(sha(BODY)));
        assert_eq!(fetch_verified(&agent(), &url).unwrap(), BODY);
    }

    #[test]
    fn uppercase_digest_is_accepted() {
        assert!(verify_body("u", BODY.as_bytes(), Some(&sha(BODY).to_uppercase())).is_ok());
    }

    #[test]
    fn tampered_body_is_rejected() {
        let url = serve("export FOO=evil\n", Some(sha(BODY)));
        let err = fetch_verified(&agent(), &url).unwrap_err();
        assert!(err.contains("integrity check failed"), "{err}");
    }

    #[test]
    fn missing_header_is_rejected() {
        let url = serve(BODY, None);
        let err = fetch_verified(&agent(), &url).unwrap_err();
        assert!(err.contains("no X-Content-SHA256"), "{err}");
    }

    #[test]
    fn no_plain_http_get_zakuro_ai_in_src() {
        // Built from parts so this file does not contain the needle itself.
        let needle = format!("{}://get.zakuro-ai.com", "http");
        let mut hits = Vec::new();
        scan(
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src").as_path(),
            &needle,
            &mut hits,
        );
        assert!(hits.is_empty(), "plain-HTTP get.zakuro-ai.com in: {hits:?}");
    }

    fn scan(dir: &Path, needle: &str, hits: &mut Vec<String>) {
        for e in std::fs::read_dir(dir).unwrap().flatten() {
            let p = e.path();
            if p.is_dir() {
                scan(&p, needle, hits);
            } else if p.extension().is_some_and(|x| x == "rs")
                && std::fs::read_to_string(&p).is_ok_and(|s| s.contains(needle))
            {
                hits.push(p.display().to_string());
            }
        }
    }
}