Answer#
A String can contain anything. If every function that receives a user name has to remember to check it, one of them will forget. Make the check part of the type: construct a Username only through a function that validates, keep its field private, and let every other function ask for a Username.
use std::fmt;
/// A user name that has already been checked. Code that takes a `Username` never re-checks.
#[derive(Debug, Clone, PartialEq)]
pub struct Username(String);
#[derive(Debug, PartialEq)]
pub enum UsernameError {
Empty,
TooLong,
BadCharacter(char),
}
impl fmt::Display for UsernameError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
UsernameError::Empty => write!(f, "user name is empty"),
UsernameError::TooLong => write!(f, "user name is longer than 32 characters"),
UsernameError::BadCharacter(c) => write!(f, "user name contains {c:?}"),
}
}
}
impl TryFrom<&str> for Username {
type Error = UsernameError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
if s.is_empty() {
return Err(UsernameError::Empty);
}
if s.chars().count() > 32 {
return Err(UsernameError::TooLong);
}
if let Some(c) = s.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-')) {
return Err(UsernameError::BadCharacter(c));
}
Ok(Username(s.to_string()))
}
}
fn greet(name: &Username) -> String {
format!("hello {}", name.0)
}
fn main() {
for input in ["ada_l", "", "bob; DROP TABLE users", "line\nbreak", &"x".repeat(40)] {
match Username::try_from(input) {
Ok(u) => println!("{}", greet(&u)),
Err(e) => println!("rejected: {e}"),
}
}
}hello ada_l
rejected: user name is empty
rejected: user name contains ';'
rejected: user name contains '\n'
rejected: user name is longer than 32 characters(In a real program the type lives in its own module so that the field is private to it; in one file the compiler cannot enforce that.)
How to do it#
- List what is valid (length, allowed characters), rather than what is dangerous.
- Count characters with
chars().count()when the limit is about text, and uselen()for bytes when the limit is about storage. - Return a specific error type, so callers and logs say what was wrong without echoing the whole input.
- Use the same approach for e-mail addresses, IDs, file names, sort keys and anything else with rules.
- Do the check at the boundary: right where the data enters the program.
Common mistakes#
- Block-lists ("reject
;and'"). Attackers find the character you forgot. - Validating, then using the original string. Use the parsed value, so what you checked is what you use.
- Normalisation after validation. If Unicode text is compared or stored in a normalised form, normalise first, then validate.
Related questions#
Does validation replace escaping or parameterised queries?#
No. Validation reduces what can enter; output encoding and parameterised queries are still required where the data is used. See the threads on SQL queries and on path traversal.
Where do the checks go in a web framework?#
In the extractor or the function that turns the request into your types, so handlers only ever see checked values.
Sources#
- OWASP Input Validation Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html
- Rust API Guidelines, "Newtypes provide static distinctions": https://rust-lang.github.io/api-guidelines/type-safety.html#newtypes-provide-static-distinctions-c-newtype
- Standard library,
TryFrom: https://doc.rust-lang.org/std/convert/trait.TryFrom.html