Skip to content

Tainted input

A value that comes from outside the program is tainted. This includes the address, a form field, a header, a cookie and a JSON body. The type of such a value is tainted string, not string.

  • Core\Request::queryParameter and Core\Request::formField return a ?tainted string.
  • Core\Request::queryParameters and Core\Request::formFields return an array<tainted string>.
  • Core\Request::json returns mixed. Text you convert from a mixed value with as string is a tainted string.
  • In a foreach over such an array, the key is a tainted string too.

The compiler checks every place where your code uses a tainted value. You cannot pass it where a plain string is needed, so it cannot reach SQL, a file name or HTML without a check.

<?nvs
// This program reads two values from the address and uses them in a safe way.
// The request is `GET /search?q=<b>tea</b>&page=2`.
// `queryParameter` returns a `tainted string`, or `null` if the address has no `q`.
tainted string $search = Core\Request::queryParameter('q') ?? '';
// `as ?int` checks the value and gives a plain `int`, or `null`.
int $next = (Core\Request::queryParameter('page') as ?int ?? 1) + 1;
// A hole in an `html` template escapes the text, so the `<b>` is shown, not run.
echo html`<p>Results for {$search}</p>`, "\n";
echo 'next page: ', $next, "\n";
nvs serve (HTTP Server Response)
<p>Results for &lt;b&gt;tea&lt;/b&gt;</p>
next page: 3

The output above is for the address /search?q=<b>tea</b>&page=2. The program uses two of the safe ways:

  • as ?int checks the text. The result is a plain int, or null when the text is not a whole number.
  • A value you put into an html template with {$name} is escaped. The <b> is shown on the page and is not run.

There are more safe ways. A value in a database query goes in as a parameter, and the database never reads it as SQL. Core\Validate checks a value against a rule, such as an email address. Core\Request::formFieldsAs and jsonAs read a form or a JSON body into a class, and each property is checked.

Passing a tainted string where a string is needed does not compile. The error is E0401, and it points at the value. You fix it by choosing one of the safe ways above.

  • Do read input into a class with formFieldsAs or jsonAs. Declare text properties as tainted string.
  • Do convert a number from the request with as ?int and handle the null.
  • Do build HTML with html templates, so every value is escaped.
  • Don’t remove the tainted from a type to fix a compile error. Check the value.
  • Don’t use a tainted value as a file name. Choose the file name in your code.

Read more in Syntax: tainted and secret strings and Syntax: as.