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::queryParameterandCore\Request::formFieldreturn a?tainted string.Core\Request::queryParametersandCore\Request::formFieldsreturn anarray<tainted string>.Core\Request::jsonreturnsmixed. Text you convert from amixedvalue withas stringis atainted string.- In a
foreachover such an array, the key is atainted stringtoo.
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.
The safe ways to use it
Section titled “The safe ways to use it”<?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";<p>Results for <b>tea</b></p>next page: 3The output above is for the address /search?q=<b>tea</b>&page=2. The program uses two of the
safe ways:
as ?intchecks the text. The result is a plainint, ornullwhen the text is not a whole number.- A value you put into an
htmltemplate 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.
When the check fails
Section titled “When the check fails”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 and don’t
Section titled “Do and don’t”- Do read input into a class with
formFieldsAsorjsonAs. Declare text properties astainted string. - Do convert a number from the request with
as ?intand handle thenull. - Do build HTML with
htmltemplates, so every value is escaped. - Don’t remove the
taintedfrom 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.
