Skip to content

Commit

Permalink
filter: fix errors found by fuzz
Browse files Browse the repository at this point in the history
While fuzzing built-in filters `center` and `indent`, they
errored out or caused an OOM due to a large value as input.
  • Loading branch information
manunio committed Jun 13, 2024
1 parent 1412a72 commit 2180649
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion askama/src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ const URLENCODE_STRICT_SET: &AsciiSet = &NON_ALPHANUMERIC
// Same as URLENCODE_STRICT_SET, but preserves forward slashes for encoding paths
const URLENCODE_SET: &AsciiSet = &URLENCODE_STRICT_SET.remove(b'/');

// MAX_LEN is maximum allowed length for filters.
const MAX_LEN: usize = 10000;

/// Marks a string (or other `Display` type) as safe
///
/// Use this is you want to allow markup in an expression, or if you know
Expand Down Expand Up @@ -374,6 +377,9 @@ impl<S: fmt::Display> fmt::Display for TruncateFilter<S> {
#[inline]
pub fn indent(s: impl ToString, width: usize) -> Result<impl fmt::Display, Infallible> {
fn indent(s: String, width: usize) -> Result<String, Infallible> {
if width >= MAX_LEN {
return Ok(s);
}
let mut indented = String::new();
for (i, c) in s.char_indices() {
indented.push(c);
Expand Down Expand Up @@ -483,7 +489,7 @@ pub fn capitalize(s: impl ToString) -> Result<impl fmt::Display, Infallible> {
pub fn center(src: impl ToString, dst_len: usize) -> Result<impl fmt::Display, Infallible> {
fn center(src: String, dst_len: usize) -> Result<String, Infallible> {
let len = src.len();
if dst_len <= len {
if dst_len <= len || dst_len >= MAX_LEN {
Ok(src)
} else {
let diff = dst_len - len;
Expand Down Expand Up @@ -704,6 +710,7 @@ mod tests {
indent("hello\nfoo\n bar", 4).unwrap().to_string(),
"hello\n foo\n bar"
);
assert_eq!(indent("hello", 267332238858).unwrap().to_string(), "hello");
}

#[cfg(feature = "num-traits")]
Expand Down Expand Up @@ -806,6 +813,10 @@ mod tests {
center("foo bar", 8).unwrap().to_string(),
"foo bar ".to_string()
);
assert_eq!(
center("foo", 111669149696).unwrap().to_string(),
"foo".to_string()
);
}

#[test]
Expand Down

0 comments on commit 2180649

Please sign in to comment.