arks-server 1.3.3

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
//! Standalone compile-time embedded asset registry with deterministic FNV-1a64
//! fingerprinting, weak ETag (`304 Not Modified`), and RFC 8246 `immutable` caching
//! (governed by `web-platform-baseline.sot.md` WP-CACHE-2).
//!
//! Only fingerprinted URLs (`/assets/<name>.<hash>.<ext>` or `/<name>.<hash>.<ext>`)
//! receive `Cache-Control: public, max-age=31536000, immutable`. Canonical unhashed URLs
//! receive `Cache-Control: no-cache` so upgrades never serve stale assets.

use std::collections::HashMap;
use std::sync::OnceLock;

use crate::http::{HttpRequest, HttpResponse};

const STYLESHEET: &[u8] = include_bytes!("../../web_ui.css");
const HTMX_JS: &[u8] = include_bytes!("../../assets/htmx.min.js");
const DIFF2HTML_JS: &[u8] = include_bytes!("../../assets/diff2html.min.js");
const DIFF2HTML_CSS: &[u8] = include_bytes!("../../assets/diff2html.min.css");
const APP_JS: &[u8] = include_bytes!("../../assets/app.js");
const THEME_INIT_JS: &[u8] = include_bytes!("../../assets/theme-init.js");
const FAVICON_SVG: &[u8] = include_bytes!("../../assets/favicon.svg");
const ICONS_SVG: &[u8] = include_bytes!("../../assets/icons.svg");

/// A compile-time embedded static asset served by `arks serve`.
#[derive(Debug, Clone, Copy)]
pub struct EmbeddedAsset {
    pub path: &'static str,
    pub content_type: &'static str,
    pub bytes: &'static [u8],
    pub immutable: bool,
}

impl EmbeddedAsset {
    /// Deterministic 16-hex-char FNV-1a64 fingerprint of the embedded bytes.
    pub fn fingerprint(&self) -> String {
        format!("{:016x}", fnv1a64(self.bytes))
    }

    /// Fingerprinted URL path inserting `.<hash>` before the final extension
    /// (e.g. `/assets/app.js` -> `/assets/app.<fnv16>.js`, `/style.css` -> `/style.<fnv16>.css`).
    pub fn fingerprinted_path(&self) -> String {
        let fp = self.fingerprint();
        insert_fingerprint(self.path, &fp)
    }

    /// Deterministic weak ETag computed via 64-bit FNV-1a over the embedded bytes.
    pub fn weak_etag(&self) -> String {
        let hash = fnv1a64(self.bytes);
        format!("W/\"{hash:016x}\"")
    }
}

fn insert_fingerprint(path: &str, fp: &str) -> String {
    let slash_idx = path.rfind('/').unwrap_or(0);
    if let Some(rel_dot) = path[slash_idx..].rfind('.') {
        let dot_idx = slash_idx + rel_dot;
        format!("{}.{fp}{}", &path[..dot_idx], &path[dot_idx..])
    } else {
        format!("{path}.{fp}")
    }
}

/// Core shared Web UI assets embedded in both `v1.0` and `v2.0`.
pub const CORE_ASSETS: &[EmbeddedAsset] = &[
    EmbeddedAsset {
        path: "/style.css",
        content_type: "text/css; charset=utf-8",
        bytes: STYLESHEET,
        immutable: true,
    },
    EmbeddedAsset {
        path: "/assets/htmx.min.js",
        content_type: "application/javascript; charset=utf-8",
        bytes: HTMX_JS,
        immutable: true,
    },
    EmbeddedAsset {
        path: "/assets/diff2html.min.js",
        content_type: "application/javascript; charset=utf-8",
        bytes: DIFF2HTML_JS,
        immutable: true,
    },
    EmbeddedAsset {
        path: "/assets/diff2html.min.css",
        content_type: "text/css; charset=utf-8",
        bytes: DIFF2HTML_CSS,
        immutable: true,
    },
    EmbeddedAsset {
        path: "/assets/app.js",
        content_type: "application/javascript; charset=utf-8",
        bytes: APP_JS,
        immutable: true,
    },
    EmbeddedAsset {
        path: "/assets/theme-init.js",
        content_type: "application/javascript; charset=utf-8",
        bytes: THEME_INIT_JS,
        immutable: true,
    },
    EmbeddedAsset {
        path: "/favicon.svg",
        content_type: "image/svg+xml",
        bytes: FAVICON_SVG,
        immutable: true,
    },
    EmbeddedAsset {
        path: "/assets/icons.svg",
        content_type: "image/svg+xml",
        bytes: ICONS_SVG,
        immutable: true,
    },
];

struct CoreAssetManifest {
    canonical_to_fingerprinted: HashMap<&'static str, String>,
    fingerprinted_to_idx: HashMap<String, usize>,
    canonical_to_idx: HashMap<&'static str, usize>,
}

fn core_manifest() -> &'static CoreAssetManifest {
    static MANIFEST: OnceLock<CoreAssetManifest> = OnceLock::new();
    MANIFEST.get_or_init(|| {
        let mut canonical_to_fingerprinted = HashMap::with_capacity(CORE_ASSETS.len());
        let mut fingerprinted_to_idx = HashMap::with_capacity(CORE_ASSETS.len());
        let mut canonical_to_idx = HashMap::with_capacity(CORE_ASSETS.len());
        for (idx, asset) in CORE_ASSETS.iter().enumerate() {
            let fp = asset.fingerprinted_path();
            canonical_to_fingerprinted.insert(asset.path, fp.clone());
            fingerprinted_to_idx.insert(fp, idx);
            canonical_to_idx.insert(asset.path, idx);
        }
        CoreAssetManifest {
            canonical_to_fingerprinted,
            fingerprinted_to_idx,
            canonical_to_idx,
        }
    })
}

/// Return the fingerprinted URL for a core embedded asset, falling back to `canonical_path`
/// if not registered in [`CORE_ASSETS`].
pub fn core_asset_url(canonical_path: &str) -> &str {
    core_manifest()
        .canonical_to_fingerprinted
        .get(canonical_path)
        .map(String::as_str)
        .unwrap_or(canonical_path)
}

/// Combined manifest hash across all core assets (usable as a Service Worker cache version).
pub fn core_manifest_hash() -> String {
    let mut acc = 0xcbf2_9ce4_8422_2325u64;
    for asset in CORE_ASSETS {
        let h = fnv1a64(asset.bytes);
        acc ^= h;
        acc = acc.wrapping_mul(0x0100_0000_01b3);
    }
    format!("{acc:016x}")
}

/// Extensible asset registry allowing `v2.0` (e.g. Kinetic Graph assets) to mount
/// additional embedded assets without modifying [`CORE_ASSETS`].
#[derive(Debug, Clone, Default)]
pub struct AssetRegistry {
    extra: Vec<EmbeddedAsset>,
}

impl AssetRegistry {
    pub fn with_core() -> Self {
        Self { extra: Vec::new() }
    }

    pub fn register(&mut self, asset: EmbeddedAsset) -> &mut Self {
        self.extra.push(asset);
        self
    }

    pub fn find(&self, path: &str) -> Option<&EmbeddedAsset> {
        self.find_with_kind(path).map(|(a, _)| a)
    }

    fn find_with_kind(&self, path: &str) -> Option<(&EmbeddedAsset, bool)> {
        for asset in &self.extra {
            if asset.fingerprinted_path() == path {
                return Some((asset, true));
            }
            if asset.path == path {
                return Some((asset, false));
            }
        }
        find_core_asset_with_kind(path)
    }

    /// Serve a matching `GET` or `HEAD` asset with ETag / `304 Not Modified` and `Cache-Control`.
    pub fn serve(&self, req: &HttpRequest) -> Option<HttpResponse> {
        if !matches!(req.method.as_str(), "GET" | "HEAD") {
            return None;
        }
        let (asset, is_fingerprinted) = self.find_with_kind(req.path.as_str())?;
        Some(build_asset_response(asset, req, is_fingerprinted))
    }
}

fn find_core_asset_with_kind(path: &str) -> Option<(&'static EmbeddedAsset, bool)> {
    let manifest = core_manifest();
    if let Some(&idx) = manifest.fingerprinted_to_idx.get(path) {
        return Some((&CORE_ASSETS[idx], true));
    }
    if let Some(&idx) = manifest.canonical_to_idx.get(path) {
        return Some((&CORE_ASSETS[idx], false));
    }
    None
}

/// Return the default core asset slice.
pub const fn core_assets() -> &'static [EmbeddedAsset] {
    CORE_ASSETS
}

/// Returns `true` if `path` matches a canonical or fingerprinted core embedded asset.
pub fn has_core_asset(path: &str) -> bool {
    find_core_asset_with_kind(path).is_some()
}

/// Serve a core embedded asset directly (usable in both single-repo and empty multi-repo roots).
pub fn serve_core_asset(req: &HttpRequest) -> Option<HttpResponse> {
    if req.method == "OPTIONS" && has_core_asset(req.path.as_str()) {
        return Some(HttpResponse {
            status: 204,
            content_type: "text/plain; charset=utf-8".into(),
            body: Vec::new(),
            www_authenticate: None,
            extra_headers: vec![("Allow".into(), "GET, HEAD, OPTIONS".into())],
        });
    }
    if !matches!(req.method.as_str(), "GET" | "HEAD") {
        return None;
    }
    let (asset, is_fingerprinted) = find_core_asset_with_kind(req.path.as_str())?;
    Some(build_asset_response(asset, req, is_fingerprinted))
}

fn build_asset_response(
    asset: &EmbeddedAsset,
    req: &HttpRequest,
    is_fingerprinted: bool,
) -> HttpResponse {
    let etag = asset.weak_etag();
    // WP-CACHE-2: only fingerprinted URLs receive `immutable`; canonical unhashed URLs use `no-cache`.
    let cache = if is_fingerprinted && asset.immutable {
        "public, max-age=31536000, immutable"
    } else {
        "no-cache"
    };
    if let Some(inm) = req.header("if-none-match") {
        let matched = inm
            .split(',')
            .any(|tag| tag.trim() == etag || tag.trim() == "*");
        if matched {
            return HttpResponse {
                status: 304,
                content_type: asset.content_type.into(),
                body: Vec::new(),
                www_authenticate: None,
                extra_headers: vec![
                    ("ETag".into(), etag),
                    ("Cache-Control".into(), cache.into()),
                    ("X-Content-Type-Options".into(), "nosniff".into()),
                ],
            };
        }
    }
    let body = if req.method == "HEAD" {
        Vec::new()
    } else {
        asset.bytes.to_vec()
    };
    HttpResponse {
        status: 200,
        content_type: asset.content_type.into(),
        body,
        www_authenticate: None,
        extra_headers: vec![
            ("ETag".into(), etag),
            ("Cache-Control".into(), cache.into()),
            ("X-Content-Type-Options".into(), "nosniff".into()),
        ],
    }
}

fn fnv1a64(bytes: &[u8]) -> u64 {
    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const PRIME: u64 = 0x0100_0000_01b3;
    let mut hash = OFFSET;
    for &b in bytes {
        hash ^= u64::from(b);
        hash = hash.wrapping_mul(PRIME);
    }
    hash
}

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

    #[test]
    fn core_assets_serve_200_and_304_on_matching_etag() {
        let req = HttpRequest::new("GET", "/assets/app.js", "", Vec::new());
        let resp = serve_core_asset(&req).expect("app.js must be served");
        assert_eq!(resp.status, 200);
        assert!(!resp.body.is_empty());
        let etag = resp
            .extra_headers
            .iter()
            .find(|(k, _)| k == "ETag")
            .map(|(_, v)| v.clone())
            .expect("ETag header missing");
        let cc = resp
            .extra_headers
            .iter()
            .find(|(k, _)| k == "Cache-Control")
            .map(|(_, v)| v.as_str())
            .expect("Cache-Control missing");
        assert_eq!(cc, "no-cache", "unhashed URL must not be immutable");

        let req_304 = HttpRequest::new("GET", "/assets/app.js", "", Vec::new())
            .with_header("If-None-Match", etag);
        let resp_304 = serve_core_asset(&req_304).expect("304 expected");
        assert_eq!(resp_304.status, 304);
        assert!(resp_304.body.is_empty());
    }

    #[test]
    fn fingerprinted_asset_url_is_immutable_and_head_has_empty_body() {
        let fp_url = core_asset_url("/style.css");
        assert!(fp_url.starts_with("/style."));
        assert!(fp_url.ends_with(".css"));
        assert_ne!(fp_url, "/style.css");

        let get_req = HttpRequest::new("GET", fp_url, "", Vec::new());
        let get_resp = serve_core_asset(&get_req).expect("fingerprinted style.css served");
        assert_eq!(get_resp.status, 200);
        assert!(!get_resp.body.is_empty());
        let cc = get_resp
            .extra_headers
            .iter()
            .find(|(k, _)| k == "Cache-Control")
            .map(|(_, v)| v.as_str())
            .unwrap();
        assert_eq!(cc, "public, max-age=31536000, immutable");

        let head_req = HttpRequest::new("HEAD", fp_url, "", Vec::new());
        let head_resp = serve_core_asset(&head_req).expect("HEAD fingerprinted asset served");
        assert_eq!(head_resp.status, 200);
        assert!(head_resp.body.is_empty());
    }

    #[test]
    fn registry_supports_v2_extension_assets() {
        let mut reg = AssetRegistry::with_core();
        reg.register(EmbeddedAsset {
            path: "/assets/kinetic_graph.js",
            content_type: "application/javascript; charset=utf-8",
            bytes: b"// kinetic",
            immutable: true,
        });
        let req = HttpRequest::new("GET", "/assets/kinetic_graph.js", "", Vec::new());
        let resp = reg.serve(&req).expect("extension asset served");
        assert_eq!(resp.status, 200);
        assert_eq!(resp.body, b"// kinetic");
    }
}