Skip to main content

arks_server/web/core/
ctx.rs

1//! Per-request Web UI context: mount prefix, HTMX protocol metadata, session/CSRF state,
2//! parsed route params, and query parameters — eliminating post-render HTML rewriting.
3
4use crate::http::HttpRequest;
5use crate::web_ui::store::{ForgeStore, parse_form_urlencoded};
6use std::collections::BTreeMap;
7use std::sync::Arc;
8
9/// Normalized URL mount prefix for single-repo (`""`), multi-repo (`"/alpha"`),
10/// or reverse-proxy sub-path (`"/git/alpha"`).
11#[derive(Debug, Clone, PartialEq, Eq, Default)]
12pub struct MountPrefix(String);
13
14impl MountPrefix {
15    /// Root mount (single-repo default `""`).
16    pub fn root() -> Self {
17        Self(String::new())
18    }
19
20    /// Normalize a mount prefix (e.g. `"alpha/"` or `"/alpha/"` -> `"/alpha"`).
21    pub fn new(raw: &str) -> Self {
22        let trimmed = raw.trim().trim_matches('/');
23        if trimmed.is_empty() {
24            Self(String::new())
25        } else {
26            Self(format!("/{trimmed}"))
27        }
28    }
29
30    /// Append a child path segment to this mount prefix.
31    pub fn join_segment(&self, segment: &str) -> Self {
32        let seg = segment.trim().trim_matches('/');
33        if seg.is_empty() {
34            return self.clone();
35        }
36        if self.0.is_empty() {
37            Self(format!("/{seg}"))
38        } else {
39            Self(format!("{}/{seg}", self.0))
40        }
41    }
42
43    /// Raw normalized prefix (`""` or `"/alpha"`).
44    pub fn as_str(&self) -> &str {
45        &self.0
46    }
47
48    /// Build a mount-prefixed application URL path (e.g. `"/issues"` -> `"/alpha/issues"`).
49    pub fn path(&self, rel: &str) -> String {
50        let rel_norm = if rel.is_empty() || rel == "/" {
51            "/"
52        } else if rel.starts_with('/') {
53            rel
54        } else {
55            return if self.0.is_empty() {
56                format!("/{rel}")
57            } else {
58                format!("{}/{rel}", self.0)
59            };
60        };
61        if self.0.is_empty() {
62            rel_norm.to_string()
63        } else if rel_norm == "/" {
64            format!("{}/", self.0)
65        } else {
66            format!("{}{rel_norm}", self.0)
67        }
68    }
69
70    /// Build a root-relative asset URL (shared assets always live at the server root).
71    pub fn asset(&self, asset_path: &str) -> String {
72        if asset_path.starts_with('/') {
73            asset_path.to_string()
74        } else {
75            format!("/{asset_path}")
76        }
77    }
78}
79
80/// HTMX v2 protocol headers extracted once from an incoming [`HttpRequest`].
81#[derive(Debug, Clone, Default, PartialEq, Eq)]
82pub struct HtmxInfo {
83    pub is_htmx: bool,
84    pub is_boosted: bool,
85    pub target: Option<String>,
86    pub trigger: Option<String>,
87    pub current_url: Option<String>,
88}
89
90impl HtmxInfo {
91    pub fn from_request(req: &HttpRequest) -> Self {
92        let is_true = |name: &str| {
93            req.header(name)
94                .is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
95        };
96        Self {
97            is_htmx: is_true("hx-request"),
98            is_boosted: is_true("hx-boosted"),
99            target: req.header("hx-target").map(|s| s.trim().to_string()),
100            trigger: req.header("hx-trigger").map(|s| s.trim().to_string()),
101            current_url: req.header("hx-current-url").map(|s| s.trim().to_string()),
102        }
103    }
104
105    /// Returns true when the server should render only a target partial fragment
106    /// rather than the full HTML document shell.
107    pub fn wants_main_partial(&self) -> bool {
108        self.is_htmx && !self.is_boosted && self.target.as_deref() == Some("main-content")
109    }
110}
111
112/// Authenticated user role in `arks serve` RBAC.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
114pub enum UserRole {
115    Viewer,
116    Member,
117    Maintainer,
118    Admin,
119}
120
121impl UserRole {
122    pub fn parse(raw: &str) -> Self {
123        match raw.trim().to_ascii_lowercase().as_str() {
124            "admin" | "owner" => Self::Admin,
125            "maintainer" => Self::Maintainer,
126            "write" | "member" | "developer" => Self::Member,
127            _ => Self::Viewer,
128        }
129    }
130
131    pub fn can_write(self) -> bool {
132        self >= Self::Member
133    }
134
135    pub fn is_admin(self) -> bool {
136        self == Self::Admin
137    }
138}
139
140/// Authenticated browser session + bound CSRF token resolved once per request.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct SessionCtx {
143    pub username: String,
144    pub role: UserRole,
145    pub csrf_token: String,
146}
147
148/// Captured route path parameters (e.g. `:id`, `:branch`, `*path`).
149#[derive(Debug, Clone, Default, PartialEq, Eq)]
150pub struct RouteParams {
151    entries: Vec<(String, String)>,
152}
153
154impl RouteParams {
155    pub fn new() -> Self {
156        Self::default()
157    }
158
159    pub fn insert(&mut self, key: impl Into<String>, value: impl Into<String>) {
160        self.entries.push((key.into(), value.into()));
161    }
162
163    pub fn get(&self, key: &str) -> Option<&str> {
164        self.entries
165            .iter()
166            .find(|(k, _)| k == key)
167            .map(|(_, v)| v.as_str())
168    }
169
170    pub fn get_u64(&self, key: &str) -> Option<u64> {
171        self.get(key)?.parse::<u64>().ok()
172    }
173}
174
175/// Parsed URL query parameters.
176#[derive(Debug, Clone, Default)]
177pub struct QueryMap(BTreeMap<String, String>);
178
179impl QueryMap {
180    pub fn parse(raw_query: &str) -> Self {
181        Self(parse_form_urlencoded(raw_query.as_bytes()))
182    }
183
184    pub fn get(&self, key: &str) -> Option<&str> {
185        self.0.get(key).map(String::as_str)
186    }
187
188    pub fn get_non_empty(&self, key: &str) -> Option<&str> {
189        self.get(key).map(str::trim).filter(|s| !s.is_empty())
190    }
191}
192
193/// Unified per-request context passed to Web UI views and handlers.
194pub struct RequestCtx<'a> {
195    pub req: &'a HttpRequest,
196    pub params: RouteParams,
197    pub query: QueryMap,
198    pub mount: MountPrefix,
199    pub htmx: HtmxInfo,
200    pub session: Option<SessionCtx>,
201    pub(crate) store: Option<Arc<ForgeStore>>,
202}
203
204impl<'a> RequestCtx<'a> {
205    pub fn new(req: &'a HttpRequest, mount: MountPrefix) -> Self {
206        Self {
207            req,
208            params: RouteParams::new(),
209            query: QueryMap::parse(&req.query),
210            mount,
211            htmx: HtmxInfo::from_request(req),
212            session: None,
213            store: None,
214        }
215    }
216
217    pub fn with_params(mut self, params: RouteParams) -> Self {
218        self.params = params;
219        self
220    }
221
222    pub fn with_session(mut self, session: Option<SessionCtx>) -> Self {
223        self.session = session;
224        self
225    }
226
227    #[allow(dead_code)]
228    pub(crate) fn with_store(mut self, store: Arc<ForgeStore>) -> Self {
229        self.store = Some(store);
230        self
231    }
232
233    #[allow(dead_code)]
234    pub(crate) fn store(&self) -> Option<&Arc<ForgeStore>> {
235        self.store.as_ref()
236    }
237
238    /// Return the bound CSRF token if a browser session is active.
239    pub fn csrf_token(&self) -> Option<&str> {
240        self.session.as_ref().map(|s| s.csrf_token.as_str())
241    }
242
243    /// Build a mount-aware relative URL (e.g. `"/issues"` -> `"/alpha/issues"`).
244    pub fn path(&self, rel: &str) -> String {
245        self.mount.path(rel)
246    }
247
248    /// Build a typed route URL via [`super::route::AppRoute`].
249    pub fn url(&self, route: super::route::AppRoute<'_>) -> String {
250        route.to_url(&self.mount)
251    }
252}
253
254/// Shared read-only UI rendering context implemented by [`RequestCtx`] and legacy [`crate::web_ui::RepoContext`].
255pub trait UiCtx {
256    fn mount(&self) -> &MountPrefix;
257    fn htmx(&self) -> &HtmxInfo;
258    fn session(&self) -> Option<&SessionCtx>;
259
260    fn csrf_token(&self) -> Option<&str> {
261        self.session().map(|s| s.csrf_token.as_str())
262    }
263
264    fn path(&self, rel: &str) -> String {
265        self.mount().path(rel)
266    }
267
268    fn url(&self, route: super::route::AppRoute<'_>) -> String {
269        route.to_url(self.mount())
270    }
271}
272
273impl UiCtx for RequestCtx<'_> {
274    fn mount(&self) -> &MountPrefix {
275        &self.mount
276    }
277
278    fn htmx(&self) -> &HtmxInfo {
279        &self.htmx
280    }
281
282    fn session(&self) -> Option<&SessionCtx> {
283        self.session.as_ref()
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn mount_prefix_normalizes_and_joins_cleanly() {
293        let root = MountPrefix::root();
294        assert_eq!(root.path("/"), "/");
295        assert_eq!(root.path("/issues"), "/issues");
296
297        let child = MountPrefix::new("/alpha/");
298        assert_eq!(child.as_str(), "/alpha");
299        assert_eq!(child.path("/"), "/alpha/");
300        assert_eq!(child.path("/issues/42"), "/alpha/issues/42");
301
302        let sub = MountPrefix::new("/git").join_segment("alpha");
303        assert_eq!(sub.path("/pulls"), "/git/alpha/pulls");
304    }
305
306    #[test]
307    fn htmx_info_distinguishes_boosted_and_partial_requests() {
308        let boosted = HttpRequest::new("GET", "/issues", "", Vec::new())
309            .with_header("HX-Request", "true")
310            .with_header("HX-Boosted", "true")
311            .with_header("HX-Target", "main-content");
312        let hb = HtmxInfo::from_request(&boosted);
313        assert!(hb.is_htmx);
314        assert!(hb.is_boosted);
315        assert!(!hb.wants_main_partial());
316
317        let partial = HttpRequest::new("GET", "/issues", "", Vec::new())
318            .with_header("HX-Request", "true")
319            .with_header("HX-Target", "main-content");
320        let hp = HtmxInfo::from_request(&partial);
321        assert!(hp.wants_main_partial());
322    }
323}