Skip to content

Commit 4e829ef

Browse files
manuniodjc
authored andcommitted
filter: fix errors found by fuzz
While fuzzing built-in filters `center` and `indent`, they errored out or caused an OOM due to a large value as input.
1 parent 1412a72 commit 4e829ef

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

askama/src/filters/mod.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ const URLENCODE_STRICT_SET: &AsciiSet = &NON_ALPHANUMERIC
4040
// Same as URLENCODE_STRICT_SET, but preserves forward slashes for encoding paths
4141
const URLENCODE_SET: &AsciiSet = &URLENCODE_STRICT_SET.remove(b'/');
4242

43+
// MAX_LEN is maximum allowed length for filters.
44+
const MAX_LEN: usize = 10_000;
45+
4346
/// Marks a string (or other `Display` type) as safe
4447
///
4548
/// Use this is you want to allow markup in an expression, or if you know
@@ -374,6 +377,9 @@ impl<S: fmt::Display> fmt::Display for TruncateFilter<S> {
374377
#[inline]
375378
pub fn indent(s: impl ToString, width: usize) -> Result<impl fmt::Display, Infallible> {
376379
fn indent(s: String, width: usize) -> Result<String, Infallible> {
380+
if width >= MAX_LEN {
381+
return Ok(s);
382+
}
377383
let mut indented = String::new();
378384
for (i, c) in s.char_indices() {
379385
indented.push(c);
@@ -483,7 +489,7 @@ pub fn capitalize(s: impl ToString) -> Result<impl fmt::Display, Infallible> {
483489
pub fn center(src: impl ToString, dst_len: usize) -> Result<impl fmt::Display, Infallible> {
484490
fn center(src: String, dst_len: usize) -> Result<String, Infallible> {
485491
let len = src.len();
486-
if dst_len <= len {
492+
if dst_len <= len || dst_len >= MAX_LEN {
487493
Ok(src)
488494
} else {
489495
let diff = dst_len - len;
@@ -704,6 +710,10 @@ mod tests {
704710
indent("hello\nfoo\n bar", 4).unwrap().to_string(),
705711
"hello\n foo\n bar"
706712
);
713+
assert_eq!(
714+
indent("hello", 267_332_238_858).unwrap().to_string(),
715+
"hello"
716+
);
707717
}
708718

709719
#[cfg(feature = "num-traits")]
@@ -806,6 +816,10 @@ mod tests {
806816
center("foo bar", 8).unwrap().to_string(),
807817
"foo bar ".to_string()
808818
);
819+
assert_eq!(
820+
center("foo", 111_669_149_696).unwrap().to_string(),
821+
"foo".to_string()
822+
);
809823
}
810824

811825
#[test]

0 commit comments

Comments
 (0)