fix: html injection and about ignore the branch selected
9 files changed, 111 insertions(+), 42 deletions(-)
@@ -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, ¤t_ref, 0, 2, None).unwrap();
let oldest = commits.last().unwrap();
let view = repo
.resolve_path(¤t_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 = "";
let html = markdown::render(md, "git-rs", "main");
assert!(html.contains(r#"alt="demo & test""#));
assert!(
html.contains(r#"src="https://github.com/user-attachments/assets/1234?a=1&b=2""#)
);
}
}
@@ -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("&"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
_ => 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);">"#
)
@@ -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);
@@ -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>"
)
}
}
@@ -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(¤t_ref.name)?
.peel_to_tree()
@@ -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()),
}
}
@@ -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">
@@ -20,7 +20,7 @@
let current_ref = Ref::resolve(&repo, &query)?;
let branch_names = repo.branch_names()?;
let readme_html = repo
.readme()
.readme(¤t_ref)
.map(|raw| markdown::render(&raw, &repo.name, ¤t_ref.name));
render_html(&AboutPage {
@@ -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(¤t_ref, &filepath)?;
let kind = repo.resolve_path(¤t_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(¤t_ref, &path)? {
match repo.read_raw_blob(¤t_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))