Skip to main content

arks_server/web/core/
html.rs

1//! Escape-by-default single-buffer HTML rendering engine with compile-time strict-CSP
2//! attribute guarantees (zero inline `style="..."` or `on*="..."` constructors).
3
4use std::fmt::Write as _;
5
6/// Append `input` to `out` with strict HTML entity escaping (`&`, `<`, `>`, `"`, `'`).
7pub fn write_html_escaped(out: &mut String, input: &str) {
8    for ch in input.chars() {
9        match ch {
10            '&' => out.push_str("&amp;"),
11            '<' => out.push_str("&lt;"),
12            '>' => out.push_str("&gt;"),
13            '"' => out.push_str("&quot;"),
14            '\'' => out.push_str("&#x27;"),
15            other => out.push(other),
16        }
17    }
18}
19
20/// Percent-encode a single URL path segment or query value (RFC 3986 unreserved set).
21pub fn url_encode_component(input: &str) -> String {
22    let mut out = String::with_capacity(input.len());
23    for byte in input.bytes() {
24        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
25            out.push(byte as char);
26        } else {
27            let _ = write!(out, "%{byte:02X}");
28        }
29    }
30    out
31}
32
33/// Audited compile-time static HTML fragment (e.g. inline SVG icon literals).
34///
35/// Intentionally accepts only `&'static str` so runtime user input cannot bypass escaping.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct TrustedHtml(&'static str);
38
39impl TrustedHtml {
40    /// Construct a trusted static HTML literal.
41    pub const fn from_static(html: &'static str) -> Self {
42        Self(html)
43    }
44
45    pub const fn as_str(self) -> &'static str {
46        self.0
47    }
48}
49
50/// Audited dynamic HTML produced exclusively by internal sanitizing renderers
51/// (e.g. syntax highlighter or sanitized Markdown converter).
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct SanitizedHtml(String);
54
55impl SanitizedHtml {
56    /// Wrap pre-sanitized HTML output from an audited internal subsystem.
57    pub fn from_audited(html: String) -> Self {
58        Self(html)
59    }
60
61    pub fn as_str(&self) -> &str {
62        &self.0
63    }
64}
65
66/// Typed HTML attributes enforcing strict CSP by omitting `style` and `on*` constructors.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum Attr<'a> {
69    Class(&'a str),
70    Id(&'a str),
71    Href(&'a str),
72    Src(&'a str),
73    Action(&'a str),
74    Method(&'a str),
75    Name(&'a str),
76    Value(&'a str),
77    Type(&'a str),
78    Placeholder(&'a str),
79    Title(&'a str),
80    Rel(&'a str),
81    Role(&'a str),
82    Target(&'a str),
83    Alt(&'a str),
84    Lang(&'a str),
85    Content(&'a str),
86    Property(&'a str),
87    Charset(&'a str),
88    Width(&'a str),
89    Height(&'a str),
90    Rows(&'a str),
91    Colspan(&'a str),
92    For(&'a str),
93    /// `data-<suffix>="<escaped>"`
94    Data(&'static str, &'a str),
95    /// `aria-<suffix>="<escaped>"`
96    Aria(&'static str, &'a str),
97    /// `hx-<suffix>="<escaped>"`
98    Hx(&'static str, &'a str),
99    Required,
100    Hidden,
101    Disabled,
102    Checked,
103    Selected,
104    Defer,
105    Open,
106}
107
108impl<'a> Attr<'a> {
109    fn write_to(&self, out: &mut String) {
110        match *self {
111            Attr::Class(v) => write_kv(out, "class", v),
112            Attr::Id(v) => write_kv(out, "id", v),
113            Attr::Href(v) => write_kv(out, "href", v),
114            Attr::Src(v) => write_kv(out, "src", v),
115            Attr::Action(v) => write_kv(out, "action", v),
116            Attr::Method(v) => write_kv(out, "method", v),
117            Attr::Name(v) => write_kv(out, "name", v),
118            Attr::Value(v) => write_kv(out, "value", v),
119            Attr::Type(v) => write_kv(out, "type", v),
120            Attr::Placeholder(v) => write_kv(out, "placeholder", v),
121            Attr::Title(v) => write_kv(out, "title", v),
122            Attr::Rel(v) => write_kv(out, "rel", v),
123            Attr::Role(v) => write_kv(out, "role", v),
124            Attr::Target(v) => write_kv(out, "target", v),
125            Attr::Alt(v) => write_kv(out, "alt", v),
126            Attr::Lang(v) => write_kv(out, "lang", v),
127            Attr::Content(v) => write_kv(out, "content", v),
128            Attr::Property(v) => write_kv(out, "property", v),
129            Attr::Charset(v) => write_kv(out, "charset", v),
130            Attr::Width(v) => write_kv(out, "width", v),
131            Attr::Height(v) => write_kv(out, "height", v),
132            Attr::Rows(v) => write_kv(out, "rows", v),
133            Attr::Colspan(v) => write_kv(out, "colspan", v),
134            Attr::For(v) => write_kv(out, "for", v),
135            Attr::Data(suffix, v) => write_prefixed_kv(out, "data-", suffix, v),
136            Attr::Aria(suffix, v) => write_prefixed_kv(out, "aria-", suffix, v),
137            Attr::Hx(suffix, v) => write_prefixed_kv(out, "hx-", suffix, v),
138            Attr::Required => out.push_str(" required"),
139            Attr::Hidden => out.push_str(" hidden"),
140            Attr::Disabled => out.push_str(" disabled"),
141            Attr::Checked => out.push_str(" checked"),
142            Attr::Selected => out.push_str(" selected"),
143            Attr::Defer => out.push_str(" defer"),
144            Attr::Open => out.push_str(" open"),
145        }
146    }
147}
148
149fn write_kv(out: &mut String, key: &str, val: &str) {
150    out.push(' ');
151    out.push_str(key);
152    out.push_str("=\"");
153    write_html_escaped(out, val);
154    out.push('"');
155}
156
157fn write_prefixed_kv(out: &mut String, prefix: &str, suffix: &str, val: &str) {
158    out.push(' ');
159    out.push_str(prefix);
160    out.push_str(suffix);
161    out.push_str("=\"");
162    write_html_escaped(out, val);
163    out.push('"');
164}
165
166/// Single-buffer HTML writer avoiding intermediate `format!()` heap allocations.
167#[derive(Debug, Default, Clone)]
168pub struct HtmlBuf {
169    buf: String,
170}
171
172impl HtmlBuf {
173    pub fn new() -> Self {
174        Self { buf: String::new() }
175    }
176
177    pub fn with_capacity(capacity: usize) -> Self {
178        Self {
179            buf: String::with_capacity(capacity),
180        }
181    }
182
183    /// Write escaped text content.
184    pub fn text(&mut self, input: &str) -> &mut Self {
185        write_html_escaped(&mut self.buf, input);
186        self
187    }
188
189    /// Write a compile-time trusted static HTML literal.
190    pub fn raw_trusted(&mut self, html: TrustedHtml) -> &mut Self {
191        self.buf.push_str(html.as_str());
192        self
193    }
194
195    /// Write audited dynamic HTML (e.g. syntax-highlighted lines or sanitized Markdown).
196    pub fn raw_sanitized(&mut self, html: &SanitizedHtml) -> &mut Self {
197        self.buf.push_str(html.as_str());
198        self
199    }
200
201    /// Render any [`Render`] value directly into this buffer.
202    pub fn push(&mut self, node: impl Render) -> &mut Self {
203        node.render_to(self);
204        self
205    }
206
207    /// Write a normal HTML element `<tag ...attrs>children</tag>`.
208    pub fn el(
209        &mut self,
210        tag: &'static str,
211        attrs: &[Attr<'_>],
212        children: impl Render,
213    ) -> &mut Self {
214        self.buf.push('<');
215        self.buf.push_str(tag);
216        for attr in attrs {
217            attr.write_to(&mut self.buf);
218        }
219        self.buf.push('>');
220        children.render_to(self);
221        self.buf.push_str("</");
222        self.buf.push_str(tag);
223        self.buf.push('>');
224        self
225    }
226
227    /// Write an HTML void element (`<input ...>`, `<meta ...>`, `<link ...>`, `<img ...>`).
228    pub fn void_el(&mut self, tag: &'static str, attrs: &[Attr<'_>]) -> &mut Self {
229        self.buf.push('<');
230        self.buf.push_str(tag);
231        for attr in attrs {
232            attr.write_to(&mut self.buf);
233        }
234        self.buf.push('>');
235        self
236    }
237
238    /// Consume the buffer and return the rendered HTML string.
239    pub fn finish(self) -> String {
240        self.buf
241    }
242
243    pub fn as_str(&self) -> &str {
244        &self.buf
245    }
246}
247
248/// Composable UI rendering trait. Dynamic text implementations ALWAYS escape HTML.
249pub trait Render {
250    fn render_to(&self, out: &mut HtmlBuf);
251
252    /// Convenience helper to render a standalone fragment to `String`.
253    fn render_to_string(&self) -> String {
254        let mut buf = HtmlBuf::with_capacity(256);
255        self.render_to(&mut buf);
256        buf.finish()
257    }
258}
259
260impl Render for () {
261    fn render_to(&self, _out: &mut HtmlBuf) {}
262}
263
264impl Render for &str {
265    fn render_to(&self, out: &mut HtmlBuf) {
266        out.text(self);
267    }
268}
269
270impl Render for String {
271    fn render_to(&self, out: &mut HtmlBuf) {
272        out.text(self);
273    }
274}
275
276impl Render for &String {
277    fn render_to(&self, out: &mut HtmlBuf) {
278        out.text(self);
279    }
280}
281
282impl Render for usize {
283    fn render_to(&self, out: &mut HtmlBuf) {
284        let _ = write!(out.buf, "{self}");
285    }
286}
287
288impl Render for u64 {
289    fn render_to(&self, out: &mut HtmlBuf) {
290        let _ = write!(out.buf, "{self}");
291    }
292}
293
294impl Render for i64 {
295    fn render_to(&self, out: &mut HtmlBuf) {
296        let _ = write!(out.buf, "{self}");
297    }
298}
299
300impl Render for TrustedHtml {
301    fn render_to(&self, out: &mut HtmlBuf) {
302        out.raw_trusted(*self);
303    }
304}
305
306impl Render for SanitizedHtml {
307    fn render_to(&self, out: &mut HtmlBuf) {
308        out.raw_sanitized(self);
309    }
310}
311
312impl Render for &SanitizedHtml {
313    fn render_to(&self, out: &mut HtmlBuf) {
314        out.raw_sanitized(self);
315    }
316}
317
318impl<T: Render> Render for Option<T> {
319    fn render_to(&self, out: &mut HtmlBuf) {
320        if let Some(inner) = self {
321            inner.render_to(out);
322        }
323    }
324}
325
326impl<T: Render> Render for &[T] {
327    fn render_to(&self, out: &mut HtmlBuf) {
328        for item in *self {
329            item.render_to(out);
330        }
331    }
332}
333
334impl<T: Render> Render for Vec<T> {
335    fn render_to(&self, out: &mut HtmlBuf) {
336        for item in self {
337            item.render_to(out);
338        }
339    }
340}
341
342impl<A: Render, B: Render> Render for (A, B) {
343    fn render_to(&self, out: &mut HtmlBuf) {
344        self.0.render_to(out);
345        self.1.render_to(out);
346    }
347}
348
349impl<A: Render, B: Render, C: Render> Render for (A, B, C) {
350    fn render_to(&self, out: &mut HtmlBuf) {
351        self.0.render_to(out);
352        self.1.render_to(out);
353        self.2.render_to(out);
354    }
355}
356
357impl<F: Fn(&mut HtmlBuf)> Render for F {
358    fn render_to(&self, out: &mut HtmlBuf) {
359        self(out);
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn dynamic_strings_and_attrs_escape_by_default() {
369        let xss = "<script>alert(\"x\" & 'y')</script>";
370        let mut buf = HtmlBuf::new();
371        buf.el("a", &[Attr::Href(xss), Attr::Title(xss)], xss);
372        let html = buf.finish();
373        assert!(!html.contains("<script>"));
374        assert!(
375            html.contains("&lt;script&gt;alert(&quot;x&quot; &amp; &#x27;y&#x27;)&lt;/script&gt;")
376        );
377    }
378
379    #[test]
380    fn trusted_and_sanitized_html_render_verbatim() {
381        let icon = TrustedHtml::from_static("<svg viewBox=\"0 0 16 16\"></svg>");
382        let md = SanitizedHtml::from_audited("<p>safe</p>".into());
383        let mut buf = HtmlBuf::new();
384        buf.el("div", &[Attr::Class("box")], (icon, &md));
385        assert_eq!(
386            buf.finish(),
387            "<div class=\"box\"><svg viewBox=\"0 0 16 16\"></svg><p>safe</p></div>"
388        );
389    }
390
391    #[test]
392    fn url_encode_component_handles_special_chars() {
393        assert_eq!(
394            url_encode_component("feat/a b#1?x=2"),
395            "feat%2Fa%20b%231%3Fx%3D2"
396        );
397        assert_eq!(url_encode_component("safe_name-1.0~rc"), "safe_name-1.0~rc");
398    }
399
400    #[test]
401    fn strict_csp_zero_inline_styles_and_handlers_in_renderers() {
402        use std::path::{Path, PathBuf};
403
404        fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
405            let Ok(entries) = std::fs::read_dir(dir) else {
406                return;
407            };
408            for entry in entries.flatten() {
409                let p = entry.path();
410                if p.is_dir() {
411                    collect_rs(&p, out);
412                } else if p.extension().and_then(|e| e.to_str()) == Some("rs") {
413                    out.push(p);
414                }
415            }
416        }
417
418        let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
419        let mut files = Vec::new();
420        collect_rs(&src_dir.join("web_ui"), &mut files);
421        collect_rs(&src_dir.join("web"), &mut files);
422        let multi_repo = src_dir.join("multi_repo.rs");
423        if multi_repo.exists() {
424            files.push(multi_repo);
425        }
426        files.sort();
427        assert!(!files.is_empty(), "expected web_ui/web renderer files");
428
429        let forbidden = [
430            "style=\\\"",
431            "style='",
432            "onclick=\\\"",
433            "onclick='",
434            "onsubmit=\\\"",
435            "onsubmit='",
436            "onchange=\\\"",
437            "onchange='",
438            "oninput=\\\"",
439            "oninput='",
440        ];
441
442        let mut violations = Vec::new();
443        for path in &files {
444            let content = std::fs::read_to_string(path).expect("read renderer file");
445            let mut in_cfg_test = false;
446            for (idx, line) in content.lines().enumerate() {
447                let trimmed = line.trim();
448                if trimmed == "#[cfg(test)]" {
449                    in_cfg_test = true;
450                }
451                if in_cfg_test || trimmed.starts_with("//") {
452                    continue;
453                }
454                for pat in forbidden {
455                    if line.contains(pat) {
456                        violations.push(format!(
457                            "{}:{}: forbidden Strict-CSP pattern `{pat}` in `{trimmed}`",
458                            path.display(),
459                            idx + 1
460                        ));
461                    }
462                }
463            }
464        }
465
466        assert!(
467            violations.is_empty(),
468            "Strict-CSP regression detected:\n{}",
469            violations.join("\n")
470        );
471    }
472
473    #[test]
474    fn zero_legacy_post_render_html_rewriters_in_server() {
475        use std::path::{Path, PathBuf};
476
477        fn collect_rs(dir: &Path, out: &mut Vec<PathBuf>) {
478            let Ok(entries) = std::fs::read_dir(dir) else {
479                return;
480            };
481            for entry in entries.flatten() {
482                let p = entry.path();
483                if p.is_dir() {
484                    collect_rs(&p, out);
485                } else if p.extension().and_then(|e| e.to_str()) == Some("rs") {
486                    out.push(p);
487                }
488            }
489        }
490
491        let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
492        let mut files = Vec::new();
493        collect_rs(&src_dir.join("web_ui"), &mut files);
494        collect_rs(&src_dir.join("web"), &mut files);
495        files.sort();
496
497        let forbidden = [
498            "fn decorate_html_for_session",
499            "fn inject_csrf_into_post_forms",
500            "fn rewrite_response_for_repo_prefix",
501            "fn rewrite_repo_prefix_html",
502            "fn rewrite_repo_prefix_location",
503        ];
504
505        let mut violations = Vec::new();
506        for path in &files {
507            if path.ends_with("html.rs") {
508                continue;
509            }
510            let content = std::fs::read_to_string(path).expect("read web source");
511            for (idx, line) in content.lines().enumerate() {
512                for pat in forbidden {
513                    if line.contains(pat) {
514                        violations.push(format!(
515                            "{}:{}: legacy post-processor `{pat}` must not be reintroduced",
516                            path.display(),
517                            idx + 1
518                        ));
519                    }
520                }
521            }
522        }
523        assert!(
524            violations.is_empty(),
525            "Legacy post-render HTML rewriter regression:\n{}",
526            violations.join("\n")
527        );
528    }
529}