index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
author Yousef Al-Harbi <yo2w86@gmail.com> 2026-11-18 09:27:39 +0300
committer Yousef Al-Harbi <yo2w86@gmail.com> 2026-11-18 09:27:39 +0300
commit f0a69f56d54875c37f93393ab9d0930e51151842 [patch]
tree 990cd43a537a5a19e97c11eb1d8672de69066dc5
parent a38b49917c6f9b42d1c14ae610696f491c17d807
download f0a69f56d54875c37f93393ab9d0930e51151842.tar.gz

fix: html injection and about ignore the branch selected

Diffstat

-rw-r--r-- src/main.rs 27
-rw-r--r-- src/markdown.rs 18
-rw-r--r-- src/time.rs 34
-rw-r--r-- src/git/diff.rs 9
-rw-r--r-- src/git/repository.rs 50
-rw-r--r-- src/git/signature.rs 2
-rw-r--r-- templates/repository/tree.html 7
-rw-r--r-- src/routes/repository/about.rs 2
-rw-r--r-- src/routes/repository/tree.rs 4
 9 files changed, 111 insertions(+), 42 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index ef61bfd..9913e79 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -102,4 +102,31 @@
        assert!(!commits[0].branch_tips(&repo).unwrap().is_empty());
        assert!(start.elapsed().as_millis() < 100);
    }

    #[test]
    fn resolve_path_supports_explicit_commit_id() {
        let repo = Repository::open(Path::new(env!("CARGO_MANIFEST_DIR"))).unwrap();
        let current_ref = Ref {
            name: repo.head_branch_name().unwrap(),
            is_head: true,
        };
        let gix_repo = repo.gix();
        let (commits, _) = repo.commits(&gix_repo, &current_ref, 0, 2, None).unwrap();
        let oldest = commits.last().unwrap();

        let view = repo
            .resolve_path(&current_ref, Some(&oldest.id), "Cargo.toml")
            .unwrap();
        assert!(matches!(view, crate::git::tree::PathView::Blob(_)));
    }

    #[test]
    fn markdown_escapes_attribute_injections_in_media() {
        let md = "![demo & test](https://github.com/user-attachments/assets/1234?a=1&b=2)";
        let html = markdown::render(md, "git-rs", "main");
        assert!(html.contains(r#"alt="demo &amp; test""#));
        assert!(
            html.contains(r#"src="https://github.com/user-attachments/assets/1234?a=1&amp;b=2""#)
        );
    }
}
diff --git a/src/markdown.rs b/src/markdown.rs
index 8e17298..ed0c6ce 100644
--- a/src/markdown.rs
+++ b/src/markdown.rs
@@ -174,7 +174,23 @@
        || (url.starts_with("https://github.com/") && url.contains("/assets/"))
}

fn escape_attr(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
    out
}

fn video_html(url: &str, fallback_to_img: bool) -> String {
    let url = escape_attr(url);
    if fallback_to_img {
        format!(
            r#"<video class="readme-video" controls playsinline preload="metadata" src="{url}" onerror="const img=document.createElement('img');img.src=this.src;img.className='readme-img';this.replaceWith(img);"></video>"#
@@ -187,6 +203,8 @@
}

fn github_asset_img_html(url: &str, alt: &str) -> String {
    let url = escape_attr(url);
    let alt = escape_attr(alt);
    format!(
        r#"<img class="readme-img" src="{url}" alt="{alt}" onerror="const v=document.createElement('video');v.src=this.src;v.controls=true;v.playsInline=true;v.preload='metadata';v.className='readme-video';this.replaceWith(v);">"#
    )
diff --git a/src/time.rs b/src/time.rs
index 53a33d4..4664fae 100644
--- a/src/time.rs
+++ b/src/time.rs
@@ -36,24 +36,32 @@
    }

    pub fn format(&self) -> String {
        let dt: DateTime<Utc> = Utc.timestamp_opt(self.gix.seconds, 0).unwrap();
        let offset = FixedOffset::east_opt(self.gix.offset).unwrap();
        let dt: DateTime<Utc> = Utc
            .timestamp_opt(self.gix.seconds, 0)
            .single()
            .unwrap_or_default();
        let offset = FixedOffset::east_opt(self.gix.offset)
            .or_else(|| FixedOffset::east_opt(0))
            .unwrap();
        let local = dt.with_timezone(&offset);
        local.format("%Y-%m-%d %H:%M:%S %z").to_string()
    }

    pub fn format_rfc(&self, writer: &mut Writer<BytesMut>) {
        let dt: DateTime<Utc> = Utc.timestamp_opt(self.gix.seconds, 0).unwrap();
        let offset = FixedOffset::east_opt(self.gix.offset).unwrap();
        let local = dt.with_timezone(&offset);
        writer
            .write_all(
                local
                    .format("%a, %d %b %Y %H:%M:%S %z")
                    .to_string()
                    .as_bytes(),
            )
        let dt: DateTime<Utc> = Utc
            .timestamp_opt(self.gix.seconds, 0)
            .single()
            .unwrap_or_default();
        let offset = FixedOffset::east_opt(self.gix.offset)
            .or_else(|| FixedOffset::east_opt(0))
            .unwrap();
        let local = dt.with_timezone(&offset);
        let _ = writer.write_all(
            local
                .format("%a, %d %b %Y %H:%M:%S %z")
                .to_string()
                .as_bytes(),
        );
    }

    pub fn format_relative(&self) -> (String, Recency) {
@@ -62,7 +70,7 @@
}

pub fn format_relative(seconds: i64) -> (String, Recency) {
    let then = Utc.timestamp_opt(seconds, 0).unwrap();
    let then = Utc.timestamp_opt(seconds, 0).single().unwrap_or_default();
    let now = Utc::now();
    let diff = now.signed_duration_since(then);

diff --git a/src/git/diff.rs b/src/git/diff.rs
index d246b42..c25c551 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -440,8 +440,9 @@

impl DiffFormatter for PlainDiffFormatter {
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>) {
        write!(output, r#"<span class="diff-file-header">{data}</span>"#).unwrap();
        output.push('\n');
        output.push_str(r#"<span class="diff-file-header">"#);
        write!(output, "{data}").unwrap();
        output.push_str("</span>\n");
    }

    fn write(&self, output: &mut String, class: &str, data: &str) {
@@ -466,8 +467,10 @@
        if is_null {
            "/dev/null".to_string()
        } else {
            let escaped_path = v_htmlescape::escape(&rela_path.to_string()).to_string();
            let escaped_rev = v_htmlescape::escape(rev_id).to_string();
            format!(
                "{prefix}/<a class='{state}' href='/{repo_name}/diff/{rela_path}?id={rev_id}'>{rela_path}</a>"
                "{prefix}/<a class='{state}' href='/{repo_name}/diff/{escaped_path}?id={escaped_rev}'>{escaped_path}</a>"
            )
        }
    }
diff --git a/src/git/repository.rs b/src/git/repository.rs
index 9fc99b1..6765001 100644
--- a/src/git/repository.rs
+++ b/src/git/repository.rs
@@ -59,9 +59,18 @@
        self.gix.to_thread_local()
    }

    pub fn readme(&self) -> Option<String> {
    pub fn readme(&self, current_ref: &Ref) -> Option<String> {
        let gix_repo = self.gix();
        let tree = gix_repo.head().ok()?.peel_to_commit().ok()?.tree().ok()?;
        let tree = Self::root_tree(&gix_repo, current_ref, None)
            .or_else(|_| {
                gix_repo
                    .head()
                    .ok()
                    .and_then(|mut h| h.peel_to_commit().ok())
                    .and_then(|c| c.tree().ok())
                    .context("no head tree")
            })
            .ok()?;

        for entry in tree.iter().flatten() {
            if entry
@@ -83,16 +92,10 @@
        commit: &Option<String>,
    ) -> Result<(Vec<u8>, String), anyhow::Error> {
        let gix_repo = self.gix();
        let (tree, filename) = if let Some(commit) = commit {
            (
                self.find_commit(&gix_repo, commit)?.gix.tree()?,
                format!("{commit}.tar.gz"),
            )
        } else {
            (
                Self::root_tree(&gix_repo, current_ref)?,
                format!("{}.tar.gz", current_ref.name.replace('/', "-")),
            )
        let tree = Self::root_tree(&gix_repo, current_ref, commit.as_deref())?;
        let filename = match commit {
            Some(c) => format!("{c}.tar.gz"),
            None => format!("{}.tar.gz", current_ref.name.replace('/', "-")),
        };

        let encoder = GzEncoder::new(Vec::new(), Compression::default());
@@ -137,9 +140,14 @@
        Ok(())
    }

    pub fn resolve_path(&self, current_ref: &Ref, path: &str) -> anyhow::Result<PathView> {
    pub fn resolve_path(
        &self,
        current_ref: &Ref,
        commit_id: Option<&str>,
        path: &str,
    ) -> anyhow::Result<PathView> {
        let gix_repo = self.gix();
        let root_tree = Self::root_tree(&gix_repo, current_ref)?;
        let root_tree = Self::root_tree(&gix_repo, current_ref, commit_id)?;
        let path = path.trim_matches('/');

        if path.is_empty() {
@@ -174,14 +182,19 @@
        }
    }

    pub fn read_raw_blob(&self, current_ref: &Ref, path: &str) -> anyhow::Result<Option<Vec<u8>>> {
    pub fn read_raw_blob(
        &self,
        current_ref: &Ref,
        commit_id: Option<&str>,
        path: &str,
    ) -> anyhow::Result<Option<Vec<u8>>> {
        let path = path.trim_matches('/');
        if path.is_empty() {
            return Ok(None);
        }

        let gix_repo = self.gix();
        let root_tree = Self::root_tree(&gix_repo, current_ref)?;
        let root_tree = Self::root_tree(&gix_repo, current_ref, commit_id)?;
        let entry = Self::lookup_entry(&root_tree, path)?;

        match entry.mode().kind() {
@@ -200,7 +213,12 @@
    fn root_tree<'a>(
        gix_repo: &'a gix::Repository,
        current_ref: &Ref,
        commit_id: Option<&str>,
    ) -> anyhow::Result<gix::Tree<'a>> {
        if let Some(id) = commit_id {
            let oid = id.parse::<gix::ObjectId>()?;
            return Ok(gix_repo.find_commit(oid)?.tree()?);
        }
        gix_repo
            .find_reference(&current_ref.name)?
            .peel_to_tree()
diff --git a/src/git/signature.rs b/src/git/signature.rs
index e1f50f4..8c5033f 100644
--- a/src/git/signature.rs
+++ b/src/git/signature.rs
@@ -14,7 +14,7 @@
        GitSignature {
            name: sig.name.to_string(),
            email: sig.email.to_string(),
            time: Time::new(sig.time().unwrap()),
            time: Time::new(sig.time().unwrap_or_default()),
        }
    }

diff --git a/templates/repository/tree.html b/templates/repository/tree.html
index 6c34e24..b7d3ec6 100644
--- a/templates/repository/tree.html
+++ b/templates/repository/tree.html
@@ -10,12 +10,7 @@
  {{ macros::repo_tabs(repo, current_ref, query, "tree") }}
{% endblock %}

{% decl parameters %}
{% if !current_ref.is_head %}
{% let parameters %}?h={{ current_ref.name }}{% endlet %}
{% else %}
{% let parameters = "".to_string() %}
{% endif %}
{% let parameters = query.id_or_head_param() %}

{% block breadcrumb %}
  <div class="tree-breadcrumb">
diff --git a/src/routes/repository/about.rs b/src/routes/repository/about.rs
index 2d1de37..ca355b3 100644
--- a/src/routes/repository/about.rs
+++ b/src/routes/repository/about.rs
@@ -20,7 +20,7 @@
    let current_ref = Ref::resolve(&repo, &query)?;
    let branch_names = repo.branch_names()?;
    let readme_html = repo
        .readme()
        .readme(&current_ref)
        .map(|raw| markdown::render(&raw, &repo.name, &current_ref.name));

    render_html(&AboutPage {
diff --git a/src/routes/repository/tree.rs b/src/routes/repository/tree.rs
index d3bdfe4..de9992f 100644
--- a/src/routes/repository/tree.rs
+++ b/src/routes/repository/tree.rs
@@ -30,7 +30,7 @@
    let repo = data.get_repo(&name)?;
    let current_ref = Ref::resolve(&repo, &query)?;
    let branch_names = repo.branch_names()?;
    let kind = repo.resolve_path(&current_ref, &filepath)?;
    let kind = repo.resolve_path(&current_ref, query.id.as_deref(), &filepath)?;

    render_html(&TreePage {
        repo,
@@ -54,7 +54,7 @@
    let repo = data.get_repo(&name)?;
    let current_ref = Ref::resolve(&repo, &query)?;

    match repo.read_raw_blob(&current_ref, &path)? {
    match repo.read_raw_blob(&current_ref, query.id.as_deref(), &path)? {
        Some(bytes) => {
            let mime = mime_guess::from_path(&path).first_or_text_plain();
            Ok(HttpResponse::Ok().content_type(mime.as_ref()).body(bytes))