When you develop a public facing website that accepts user input you have to assure that your input is valid, there are a myriad of risks that face you, but don't take my word for it, see https://www.owasp.org.
OWASP (weird application super protected)
Recently a shiny new web framework for Rust was announced called rocket (http://rocket.rs), and for my own part rocket just clicked with me. What's truly great about rocket is it's pervasive use of the Rust type system and Traits, allowing you to write inspired apps with minimal code, that just "makes sense" and is intuitively readable and understandable.
In order to support client requests we define routes in rocket.
The code above defines two routes and mounts them in main. The first route is just a catch-all for browsers, the second route, process accepts a query string of type QueryString which is defined as follows:
As can be noted we define types for each query parameter that we're expecting. With the struct defined above we expect a request a with three parameters w, s and b, for example:
As can be seen in the first listing (the process route, line 8), will return a String when called, which it returns to the user with the output below, the app claims that this output is "Safe to process", well that's great, but how can we know that.
This is where rocket and its built-in traits come in, in this case we're interested in the trait FromFormValue. Rocket takes care of parsing the query string into a &str, we then need to implement the trait for our types. The rocket documentation illustrates it's use here: https://api.rocket.rs/rocket/request/trait.FromFormValue.html.
QWordString only accepts the words "foo" and "boo", QSmallNumber only allows unsigned integers under 100 and QBoolean will accept "yes", "no", "true", "false", "1" and "0".
Lets test it as follows:
As can be seen, our number parameter, s, was not accepted (its above 100).
In order to accomplish the input validation we implement the FromFormValue trait for our types.
Here we use the regex crate and a regex that only allows the words "foo" or "boo". It will throw a "unacceptable word parameter" error if the string doesn't strictly match.
In this snippet we only accept valid number (line 7), and only if it is below 100 (line 11).
Where we again use the regex crate to check for the acceptable true and false values.
As can be seen, this mechanism can be incredibly powerful and can be used to assure that only valid input gets processed on the server. Have a look at the final product at https://github.com/stephanbuys/rocket-wasp, the code doesn't have to be super verbose and a basic understanding of rust types and traits is really the only bits that the developer needs to understand, rocket just gets out of the way.