Skip to content

Input from outside is tainted

A value that comes from outside the program is tainted. That includes a form field, a header and a command-line argument. The compiler checks every place where your code uses the value:

<?nvs
// This program uses two values from a form in a safe way.
// `tainted` says that a string comes from outside the program.
tainted string $amount = '42';
tainted string $comment = '<b>great</b>';
// `as int` checks the value. The result is a plain `int`.
int $count = $amount as int;
echo $count * 2, "\n";
// A hole in an `html` template escapes the tainted string.
echo html`<p>{$comment}</p>`, "\n";
Output
84
<p>&lt;b&gt;great&lt;/b&gt;</p>

as int checks the text and gives a plain int. A hole in an html template escapes the text. These are safe ways to use the value. A type test with is does not remove tainted.

Using a tainted value as a plain string does not compile:

<?nvs
// This program uses a tainted string as a plain `string`, so it does not compile.
tainted string $comment = '<b>great</b>';
string $plain = $comment;
echo $plain, "\n";
Compiler error
error[E0401]: expected `string`, found `tainted string`
--> tainted-input-error.nvs:4:17
|
4 | string $plain = $comment;
| ^^^^^^^^ this is `tainted string`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

The compiler finds the mistake before the program runs. No person has to find it in a code review.

Read more in Syntax: tainted and secret strings.