arks-server 1.3.6

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
//! Per-request Web UI context: mount prefix, HTMX protocol metadata, session/CSRF state,
//! parsed route params, and query parameters — eliminating post-render HTML rewriting.

use crate::http::HttpRequest;
use crate::web_ui::store::{ForgeStore, parse_form_urlencoded};
use std::collections::BTreeMap;
use std::sync::Arc;

/// Normalized URL mount prefix for single-repo (`""`), multi-repo (`"/alpha"`),
/// or reverse-proxy sub-path (`"/git/alpha"`).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MountPrefix(String);

impl MountPrefix {
    /// Root mount (single-repo default `""`).
    pub fn root() -> Self {
        Self(String::new())
    }

    /// Normalize a mount prefix (e.g. `"alpha/"` or `"/alpha/"` -> `"/alpha"`).
    pub fn new(raw: &str) -> Self {
        let trimmed = raw.trim().trim_matches('/');
        if trimmed.is_empty() {
            Self(String::new())
        } else {
            Self(format!("/{trimmed}"))
        }
    }

    /// Append a child path segment to this mount prefix.
    pub fn join_segment(&self, segment: &str) -> Self {
        let seg = segment.trim().trim_matches('/');
        if seg.is_empty() {
            return self.clone();
        }
        if self.0.is_empty() {
            Self(format!("/{seg}"))
        } else {
            Self(format!("{}/{seg}", self.0))
        }
    }

    /// Raw normalized prefix (`""` or `"/alpha"`).
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Build a mount-prefixed application URL path (e.g. `"/issues"` -> `"/alpha/issues"`).
    pub fn path(&self, rel: &str) -> String {
        let rel_norm = if rel.is_empty() || rel == "/" {
            "/"
        } else if rel.starts_with('/') {
            rel
        } else {
            return if self.0.is_empty() {
                format!("/{rel}")
            } else {
                format!("{}/{rel}", self.0)
            };
        };
        if self.0.is_empty() {
            rel_norm.to_string()
        } else if rel_norm == "/" {
            format!("{}/", self.0)
        } else {
            format!("{}{rel_norm}", self.0)
        }
    }

    /// Build a root-relative asset URL (shared assets always live at the server root).
    pub fn asset(&self, asset_path: &str) -> String {
        if asset_path.starts_with('/') {
            asset_path.to_string()
        } else {
            format!("/{asset_path}")
        }
    }
}

/// HTMX v2 protocol headers extracted once from an incoming [`HttpRequest`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct HtmxInfo {
    pub is_htmx: bool,
    pub is_boosted: bool,
    pub target: Option<String>,
    pub trigger: Option<String>,
    pub current_url: Option<String>,
}

impl HtmxInfo {
    pub fn from_request(req: &HttpRequest) -> Self {
        let is_true = |name: &str| {
            req.header(name)
                .is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
        };
        Self {
            is_htmx: is_true("hx-request"),
            is_boosted: is_true("hx-boosted"),
            target: req.header("hx-target").map(|s| s.trim().to_string()),
            trigger: req.header("hx-trigger").map(|s| s.trim().to_string()),
            current_url: req.header("hx-current-url").map(|s| s.trim().to_string()),
        }
    }

    /// Returns true when the server should render only a target partial fragment
    /// rather than the full HTML document shell.
    pub fn wants_main_partial(&self) -> bool {
        self.is_htmx && !self.is_boosted && self.target.as_deref() == Some("main-content")
    }
}

/// Authenticated user role in `arks serve` RBAC.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum UserRole {
    Viewer,
    Member,
    Maintainer,
    Admin,
}

impl UserRole {
    pub fn parse(raw: &str) -> Self {
        match raw.trim().to_ascii_lowercase().as_str() {
            "admin" | "owner" => Self::Admin,
            "maintainer" => Self::Maintainer,
            "write" | "member" | "developer" => Self::Member,
            _ => Self::Viewer,
        }
    }

    pub fn can_write(self) -> bool {
        self >= Self::Member
    }

    pub fn is_admin(self) -> bool {
        self == Self::Admin
    }
}

/// Authenticated browser session + bound CSRF token resolved once per request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionCtx {
    pub username: String,
    pub role: UserRole,
    pub csrf_token: String,
}

/// Captured route path parameters (e.g. `:id`, `:branch`, `*path`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RouteParams {
    entries: Vec<(String, String)>,
}

impl RouteParams {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.entries.push((key.into(), value.into()));
    }

    pub fn get(&self, key: &str) -> Option<&str> {
        self.entries
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, v)| v.as_str())
    }

    pub fn get_u64(&self, key: &str) -> Option<u64> {
        self.get(key)?.parse::<u64>().ok()
    }
}

/// Parsed URL query parameters.
#[derive(Debug, Clone, Default)]
pub struct QueryMap(BTreeMap<String, String>);

impl QueryMap {
    pub fn parse(raw_query: &str) -> Self {
        Self(parse_form_urlencoded(raw_query.as_bytes()))
    }

    pub fn get(&self, key: &str) -> Option<&str> {
        self.0.get(key).map(String::as_str)
    }

    pub fn get_non_empty(&self, key: &str) -> Option<&str> {
        self.get(key).map(str::trim).filter(|s| !s.is_empty())
    }
}

/// Unified per-request context passed to Web UI views and handlers.
pub struct RequestCtx<'a> {
    pub req: &'a HttpRequest,
    pub params: RouteParams,
    pub query: QueryMap,
    pub mount: MountPrefix,
    pub htmx: HtmxInfo,
    pub session: Option<SessionCtx>,
    pub(crate) store: Option<Arc<ForgeStore>>,
}

impl<'a> RequestCtx<'a> {
    pub fn new(req: &'a HttpRequest, mount: MountPrefix) -> Self {
        Self {
            req,
            params: RouteParams::new(),
            query: QueryMap::parse(&req.query),
            mount,
            htmx: HtmxInfo::from_request(req),
            session: None,
            store: None,
        }
    }

    pub fn with_params(mut self, params: RouteParams) -> Self {
        self.params = params;
        self
    }

    pub fn with_session(mut self, session: Option<SessionCtx>) -> Self {
        self.session = session;
        self
    }

    #[allow(dead_code)]
    pub(crate) fn with_store(mut self, store: Arc<ForgeStore>) -> Self {
        self.store = Some(store);
        self
    }

    #[allow(dead_code)]
    pub(crate) fn store(&self) -> Option<&Arc<ForgeStore>> {
        self.store.as_ref()
    }

    /// Return the bound CSRF token if a browser session is active.
    pub fn csrf_token(&self) -> Option<&str> {
        self.session.as_ref().map(|s| s.csrf_token.as_str())
    }

    /// Build a mount-aware relative URL (e.g. `"/issues"` -> `"/alpha/issues"`).
    pub fn path(&self, rel: &str) -> String {
        self.mount.path(rel)
    }

    /// Build a typed route URL via [`super::route::AppRoute`].
    pub fn url(&self, route: super::route::AppRoute<'_>) -> String {
        route.to_url(&self.mount)
    }
}

/// Shared read-only UI rendering context implemented by [`RequestCtx`] and legacy [`crate::web_ui::RepoContext`].
pub trait UiCtx {
    fn mount(&self) -> &MountPrefix;
    fn htmx(&self) -> &HtmxInfo;
    fn session(&self) -> Option<&SessionCtx>;

    fn csrf_token(&self) -> Option<&str> {
        self.session().map(|s| s.csrf_token.as_str())
    }

    fn path(&self, rel: &str) -> String {
        self.mount().path(rel)
    }

    fn url(&self, route: super::route::AppRoute<'_>) -> String {
        route.to_url(self.mount())
    }
}

impl UiCtx for RequestCtx<'_> {
    fn mount(&self) -> &MountPrefix {
        &self.mount
    }

    fn htmx(&self) -> &HtmxInfo {
        &self.htmx
    }

    fn session(&self) -> Option<&SessionCtx> {
        self.session.as_ref()
    }
}

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

    #[test]
    fn mount_prefix_normalizes_and_joins_cleanly() {
        let root = MountPrefix::root();
        assert_eq!(root.path("/"), "/");
        assert_eq!(root.path("/issues"), "/issues");

        let child = MountPrefix::new("/alpha/");
        assert_eq!(child.as_str(), "/alpha");
        assert_eq!(child.path("/"), "/alpha/");
        assert_eq!(child.path("/issues/42"), "/alpha/issues/42");

        let sub = MountPrefix::new("/git").join_segment("alpha");
        assert_eq!(sub.path("/pulls"), "/git/alpha/pulls");
    }

    #[test]
    fn htmx_info_distinguishes_boosted_and_partial_requests() {
        let boosted = HttpRequest::new("GET", "/issues", "", Vec::new())
            .with_header("HX-Request", "true")
            .with_header("HX-Boosted", "true")
            .with_header("HX-Target", "main-content");
        let hb = HtmxInfo::from_request(&boosted);
        assert!(hb.is_htmx);
        assert!(hb.is_boosted);
        assert!(!hb.wants_main_partial());

        let partial = HttpRequest::new("GET", "/issues", "", Vec::new())
            .with_header("HX-Request", "true")
            .with_header("HX-Target", "main-content");
        let hp = HtmxInfo::from_request(&partial);
        assert!(hp.wants_main_partial());
    }
}