trailofbits / semgrep-rules

Semgrep queries developed by Trail of Bits.
GNU Affero General Public License v3.0
317 stars 33 forks source link

Add Rust rule for dangerous use of eagerly evaluated patterns #65

Open iFrostizz opened 2 months ago

iFrostizz commented 2 months ago

Some functions in the standard lib are eagerly evaluated. This is the case of unwrap_or, map_or, ok_or, and, or, and more on other types ... One could assume that it it safe to write:

let definitely_errors: Result<(), ()> = Err(());
let potential_data: Option<()> = Some(());
let _ = potential_data.unwrap_or(definitely_errors.unwrap());

while this will result in a panic. The reason is that definitely_errors.unwrap() is lazily evaluated. To write something that means "if there some data, then unwrap the value inside of definitely_errors since it may be safe to do so, sometimes assumptions are made on these kind of invariants (ex: If some value is None then another one is Some/Ok for sure). In order to translate this, one should instead use unwrap_or_else which is lazily evaluated.

In the playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6a018576a896d586c2e7a44d72f6803e

A rule could be written that detects if the usage of such an eagerly evaluated block may be unsafe (for instance unwrapping inside of it).