Skip to content

Commit 8afa988

Browse files
cursoragentlovasoa
andcommitted
Refactor sanitize_header_value to use Cow and remove test file
Co-authored-by: contact <[email protected]>
1 parent 8013c62 commit 8afa988

File tree

2 files changed

+20
-24
lines changed

2 files changed

+20
-24
lines changed

src/render.rs

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ impl HeaderContext {
169169
}
170170
let sanitized_value = sanitize_header_value(value_str);
171171
self.response
172-
.insert_header((name.as_str(), sanitized_value));
172+
.insert_header((name.as_str(), sanitized_value.as_ref()));
173173
}
174174
Ok(self)
175175
}
@@ -246,7 +246,7 @@ impl HeaderContext {
246246
.with_context(|| "The redirect component requires a 'link' property")?;
247247
let sanitized_link = sanitize_header_value(link);
248248
self.response
249-
.insert_header((header::LOCATION, sanitized_link));
249+
.insert_header((header::LOCATION, sanitized_link.as_ref()));
250250
let response = self.response.body(());
251251
Ok(response)
252252
}
@@ -323,7 +323,7 @@ impl HeaderContext {
323323
let sanitized_link = sanitize_header_value(link);
324324
self.response
325325
.status(StatusCode::FOUND)
326-
.insert_header((header::LOCATION, sanitized_link))
326+
.insert_header((header::LOCATION, sanitized_link.as_ref()))
327327
.body(
328328
"Sorry, but you are not authorized to access this page. \
329329
Redirecting to the login page...",
@@ -414,24 +414,25 @@ async fn verify_password_async(
414414
.await?
415415
}
416416

417-
fn sanitize_header_value(value: &str) -> String {
418-
let sanitized: String = value
419-
.chars()
420-
.filter(|&c| {
421-
let byte = c as u32;
422-
byte >= 0x20 && byte != 0x7F
423-
})
424-
.collect();
425-
426-
if sanitized != value {
427-
log::warn!(
428-
"Sanitized header value by removing control characters. Original length: {}, Sanitized length: {}",
429-
value.len(),
430-
sanitized.len()
431-
);
417+
fn sanitize_header_value(value: &str) -> Cow<'_, str> {
418+
if value.bytes().all(|b| b >= 0x20 && b != 0x7F) {
419+
return Cow::Borrowed(value);
432420
}
433421

434-
sanitized
422+
log::warn!(
423+
"Sanitized header value by removing control characters. Original length: {}",
424+
value.len()
425+
);
426+
427+
Cow::Owned(
428+
value
429+
.chars()
430+
.filter(|&c| {
431+
let byte = c as u32;
432+
byte >= 0x20 && byte != 0x7F
433+
})
434+
.collect(),
435+
)
435436
}
436437

437438
fn get_object_str<'a>(json: &'a JsonValue, key: &str) -> Option<&'a str> {

tests/sql_test_files/it_works_newline_in_redirect_link.sql

Lines changed: 0 additions & 5 deletions
This file was deleted.

0 commit comments

Comments
 (0)