Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions bin/latte-lint
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Latte linter
$argv = $_SERVER['argv'] ?? [];

if (count($argv) < 2) {
echo "Usage: latte-lint <path>\n";
echo "Usage: latte-lint <path> [--strict] [--fail-on-warnings] [--debug]\n";
exit(1);
}

Expand All @@ -29,11 +29,14 @@ if ($debug = in_array('--debug', $argv, true)) {
if ($strict = in_array('--strict', $argv, true)) {
echo "Strict mode\n";
}
if ($failOnWarnings = in_array('--fail-on-warnings', $argv, true)) {
echo "Fail on warnings mode\n";
}

$path = $argv[1];

try {
$linter = new Latte\Tools\Linter(debug: $debug, strict: $strict);
$linter = new Latte\Tools\Linter(debug: $debug, strict: $strict, failOnWarnings: $failOnWarnings);
$ok = $linter->scanDirectory($path);
exit($ok ? 0 : 1);

Expand Down
46 changes: 42 additions & 4 deletions docs/internals/escaping.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ layers that must stay in sync**.
`(contentType, state, subType)`, emits a string that **calls** a runtime escaping
function (e.g. `LR\HtmlHelpers::escapeText(...)`, `LR\Helpers::escapeCss(...)`;
plain-text output goes through the `escape` filter instead). The subType is not
purely state-derived: `enterHtmlAttribute` infers `js` for `on*` and `css` for
`style` attributes, and `enterHtmlText` classifies a `<script>` by its `type`
attribute. `export()` serializes the state as a composite string
purely state-derived: `enterHtmlAttribute` infers `js` for `on*`, `css` for
`style` and `html` for `srcdoc` attributes, and `enterHtmlText` classifies a
`<script>` by its `type` attribute and gives the content of `<textarea>` and `<title>`
(also nested elements in them, but not `<title>` in SVG) the subType `rcdata`. `export()` serializes the state as a composite string
(`'html/attr/js'`) — the key format used for block escaping and the convertor
table below.
- **Runtime** — the actual escaping functions live in `Runtime\Helpers` (JS / CSS /
Expand All @@ -36,6 +37,43 @@ type or a changed escaping rule must be reflected in *both* `Compiler\Escaper` a
`Runtime\*` helpers, or generated templates will call an escaper that behaves
differently than the compiler assumed.

## `srcdoc` is escaped twice

The value of `srcdoc` is an HTML document: the browser attribute-decodes it and then
parses the result as HTML. Escaping it only as an attribute is therefore an XSS —
`&lt;script&gt;` decodes to a live `<script>`, and an iframe without `sandbox` shares
the parent's origin. `HtmlHelpers::escapeHtmlAttr` escapes a value twice as an attribute
value: Latte does not parse the document, so the value may land in its text as well as in
one of its attributes, where an unescaped quote would let it add an event handler. An
`Html` object is markup and is encoded only once, so trusted HTML keeps its tags. All three places route
`srcdoc` through it: the `html/attr/html` state in `escape()` and in the
`Convertors`, and `formatSrcdocAttribute` for dynamic attributes and `n:attr`.

With `Feature::MigrationWarnings`, `formatSrcdocAttribute` warns about a plain value
whose document differs from its text (it contains `<` or a character reference),
i.e. one that used to render as markup. Only the formatter paths warn: a mixed value
like `srcdoc="<p>{$x}</p>"` is escaped by code `Escaper::escape()` emits, and
`Escaper` has no access to feature flags.

## Braces are separated by a comment

Frameworks that compile templates from the DOM (Vue, petite-vue, AngularJS) read the
text after the browser has decoded entities, so `&#123;&#123;` is no protection against
`{{ }}` injection. `escapeText` (and `convertAttrToHtml`, `convertRcDataToHtml`) insert
`<!-- -->` after each `{` followed by another one or ending the string, and before a
leading one, so `{{` cannot form even from two adjacent outputs. An attribute cannot hold
a comment: the `&#123;` of `escapeAttr` does not stop AngularJS, which interpolates
attributes. Where Latte cannot tell text from an attribute (the content of
`<script type="text/template">` and of `srcdoc`), the value is escaped as an attribute:
Vue 3 compiles a template string before decoding entities, so `&#123;` protects there,
while Vue 2 decodes them first.

Inside `<textarea>` and `<title>` (`html/rcdata`) a comment is displayed as text and would
corrupt the value, so `escapeRcData` leaves braces alone. A block defined there is
`html/rcdata` too: filters see that type, and `convertRcDataToHtml` separates the braces
when such a block is included into ordinary text. A block from ordinary text included
there keeps its separators, since its output was escaped elsewhere.

## How nodes obtain the context: the `PrintContext` escaper stack

At print time the current escaping context lives in a **stack of `Escaper`s inside
Expand All @@ -54,7 +92,7 @@ element's `restoreEscape()` and leak the context past the element.
A whole HTML attribute generated from an expression (`Html\ExpressionAttributeNode`)
is not escaped via `Escaper` at all. The node picks a
`Runtime\HtmlHelpers::format*Attribute` method at compile time — the attribute *type*
(`bool`/`tristate`/`valuedBool`/`list`/`data`/`aria`/`style`) comes from the attribute name via
(`bool`/`tristate`/`valuedBool`/`list`/`data`/`aria`/`style`/`srcdoc`) comes from the attribute name via
`classifyAttributeType`, or is forced by an attribute modifier: `|toggle` anywhere in
the chain, `|json` only as the **last** modifier (`json` never comes from the
attribute name). Any non-HTML content type falls back to
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ survives regeneration.
| `bytes` | `Filters::bytes` | | |
| `capitalize` | `Filters::capitalize` | | needs ext-mbstring |
| `ceil` | `Filters::ceil` | | |
| `checkUrl` | `Filters::checkUrl` | | appended automatically to URL attributes by the `checkUrls` pass; opt out with `nocheck` |
| `checkUrl` | `Filters::checkUrl` | | appended automatically to URL attributes by the `checkUrls` pass as nullsafe `?\|checkUrl`, so null still drops the attribute; opt out with `nocheck` |
| `clamp` | `Filters::clamp` | | |
| `column` | `Filters::column` | | |
| `commas` | `Filters::commas` | | |
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Getting started
Editor Integration
==================

- PhpStorm ([Latte](https://plugins.jetbrains.com/plugin/24218-latte-support) or [Latte Pro](https://plugins.jetbrains.com/plugin/19661-latte-pro))
- PhpStorm ([Latte](https://plugins.jetbrains.com/plugin/24218-latte-support), [Latte Pro](https://plugins.jetbrains.com/plugin/19661-latte-pro) or [Latte+](https://plugins.jetbrains.com/plugin/34056-latte-))
- Visual Studio Code ([Nette Latte + Neon](https://marketplace.visualstudio.com/items?itemName=Kasik96.latte) or [Nette for VS Code](https://marketplace.visualstudio.com/items?itemName=franken-ui.nette-for-vscode))

 <!---->
Expand Down
40 changes: 37 additions & 3 deletions src/Latte/Compiler/Escaper.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ class Escaper
Text = 'text',
JavaScript = 'js',
Css = 'css',
ICal = 'ical';
ICal = 'ical',
RcData = 'rcdata';

public const
HtmlText = 'html',
Expand All @@ -39,6 +40,8 @@ class Escaper
self::HtmlAttribute => 'HtmlHelpers::escapeAttr',
self::HtmlAttribute . '/' . self::JavaScript => 'HtmlHelpers::escapeAttr',
self::HtmlAttribute . '/' . self::Css => 'HtmlHelpers::escapeAttr',
self::HtmlAttribute . '/' . self::HtmlText => 'HtmlHelpers::escapeHtmlAttr',
self::HtmlText . '/' . self::RcData => 'HtmlHelpers::escapeRcData',
self::HtmlComment => 'HtmlHelpers::escapeComment',
'xml' => 'XmlHelpers::escapeText',
'xml/attr' => 'XmlHelpers::escapeAttr',
Expand All @@ -47,13 +50,17 @@ class Escaper
self::HtmlText => 'HtmlHelpers::escapeText',
self::HtmlAttribute => 'HtmlHelpers::escapeAttr',
self::HtmlAttribute . '/' . self::JavaScript => 'HtmlHelpers::escapeAttr',
self::HtmlAttribute . '/' . self::HtmlText => 'HtmlHelpers::escapeHtmlAttr',
self::HtmlText . '/' . self::RcData => 'HtmlHelpers::escapeRcData',
self::HtmlRawText . '/' . self::JavaScript => 'HtmlHelpers::convertJSToRawText',
self::HtmlComment => 'HtmlHelpers::escapeComment',
],
self::Css => [
self::HtmlText => 'HtmlHelpers::escapeText',
self::HtmlAttribute => 'HtmlHelpers::escapeAttr',
self::HtmlAttribute . '/' . self::Css => 'HtmlHelpers::escapeAttr',
self::HtmlAttribute . '/' . self::HtmlText => 'HtmlHelpers::escapeHtmlAttr',
self::HtmlText . '/' . self::RcData => 'HtmlHelpers::escapeRcData',
self::HtmlRawText . '/' . self::Css => 'HtmlHelpers::convertJSToRawText',
self::HtmlComment => 'HtmlHelpers::escapeComment',
],
Expand All @@ -62,12 +69,17 @@ class Escaper
self::HtmlAttribute => 'HtmlHelpers::convertHtmlToAttr',
self::HtmlAttribute . '/' . self::JavaScript => 'HtmlHelpers::convertHtmlToAttr',
self::HtmlAttribute . '/' . self::Css => 'HtmlHelpers::convertHtmlToAttr',
self::HtmlAttribute . '/' . self::HtmlText => 'HtmlHelpers::escapeAttr',
self::HtmlText . '/' . self::RcData => 'Helpers::nop',
self::HtmlComment => 'HtmlHelpers::escapeComment',
self::HtmlRawText . '/' . self::HtmlText => 'HtmlHelpers::convertHtmlToRawText',
],
self::HtmlAttribute => [
self::HtmlText => 'HtmlHelpers::convertAttrToHtml',
],
self::HtmlText . '/' . self::RcData => [
self::HtmlText => 'HtmlHelpers::convertRcDataToHtml',
],
];

private string $state = '';
Expand Down Expand Up @@ -125,7 +137,7 @@ public function enterHtmlText(ElementNode $el): void

} else {
$this->state = self::HtmlText;
$this->subType = '';
$this->subType = $this->contentType === ContentType::Html && self::isRcData($el) ? self::RcData : '';
}
}

Expand Down Expand Up @@ -154,6 +166,8 @@ public function enterHtmlAttribute(?string $name = null): void
$this->subType = self::JavaScript;
} elseif ($name === 'style') {
$this->subType = self::Css;
} elseif ($name === 'srcdoc') {
$this->subType = self::HtmlText;
}
}
}
Expand All @@ -175,12 +189,16 @@ public function escape(string $str): string
{
return match ($this->contentType) {
ContentType::Html => match ($this->state) {
self::HtmlText => 'LR\HtmlHelpers::escapeText(' . $str . ')',
self::HtmlText => match ($this->subType) {
'' => 'LR\HtmlHelpers::escapeText(' . $str . ')',
self::RcData => 'LR\HtmlHelpers::escapeRcData(' . $str . ')',
},
self::HtmlTag => 'LR\HtmlHelpers::escapeTag(' . $str . ')',
self::HtmlAttribute => match ($this->subType) {
'' => 'LR\HtmlHelpers::escapeAttr(' . $str . ')',
self::JavaScript => 'LR\HtmlHelpers::escapeAttr(LR\Helpers::escapeJs(' . $str . '))',
self::Css => 'LR\HtmlHelpers::escapeAttr(LR\Helpers::escapeCss(' . $str . '))',
self::HtmlText => 'LR\HtmlHelpers::escapeHtmlAttr(' . $str . ')',
},
self::HtmlComment => 'LR\HtmlHelpers::escapeComment(' . $str . ')',
self::HtmlBogusTag => 'LR\HtmlHelpers::escapeTag(' . $str . ')',
Expand Down Expand Up @@ -258,4 +276,20 @@ public static function getConvertor(string $source, string $dest): ?callable
default => null,
};
}


/**
* Is the element inside <textarea> or <title>, whose content the browser does not parse as HTML?
*/
private static function isRcData(ElementNode $el): bool
{
$res = false;
for (; $el; $el = $el->parent) {
if ($el->is('svg') || $el->is('math')) {
return false; // <title> in SVG is an ordinary element
}
$res = $res || $el->is('textarea') || $el->is('title');
}
return $res;
}
}
17 changes: 17 additions & 0 deletions src/Latte/Compiler/Nodes/Php/Expression/ArrayNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ public function toArguments(): array
}


/**
* Checks that the items can be passed to parameters, i.e. no positional item follows a named one.
*/
public function validateArguments(): void
{
$named = false;
foreach ($this->items as $item) {
if ($item->key) {
$named = true;
} elseif ($named) {
trigger_error("Positional argument after a named argument is deprecated ($item->position)", E_USER_DEPRECATED);
return;
}
}
}


public function print(PrintContext $context): string
{
return '[' . $context->implode($this->items) . ']';
Expand Down
1 change: 1 addition & 0 deletions src/Latte/Compiler/TemplateParserHtml.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ private function extractIndentation(): AreaNode
if ($this->parser->lastIndentation) {
$dolly = clone $this->parser->lastIndentation;
$this->parser->lastIndentation->clear();
$this->parser->lastIndentation = null;
return $dolly;
} else {
return new Nodes\NopNode;
Expand Down
43 changes: 31 additions & 12 deletions src/Latte/Essential/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,16 @@ final class Filters
{
public ?string $locale = null;

/** @var array<string, \NumberFormatter> */
private array $numberFormatters = [];


/**
* Converts HTML to plain text.
*/
public static function stripHtml(FilterInfo $info, string|Stringable|null $s): string
{
$info->validate([null, 'html', 'html/attr', 'xml', 'xml/attr'], __FUNCTION__);
$info->validate([null, 'html', 'html/attr', 'html/rcdata', 'xml', 'xml/attr'], __FUNCTION__);
$info->contentType = ContentType::Text;
return Latte\Runtime\HtmlHelpers::convertHtmlToText((string) $s);
}
Expand All @@ -41,7 +44,7 @@ public static function stripHtml(FilterInfo $info, string|Stringable|null $s): s
public static function stripTags(FilterInfo $info, string|Stringable|null $s): string
{
$info->contentType ??= ContentType::Html;
$info->validate(['html', 'html/attr', 'xml', 'xml/attr'], __FUNCTION__);
$info->validate(['html', 'html/attr', 'html/rcdata', 'xml', 'xml/attr'], __FUNCTION__);
return strip_tags((string) $s);
}

Expand Down Expand Up @@ -222,13 +225,7 @@ public function number(
return number_format($number, $patternOrDecimals, $decimalSeparator, $thousandsSeparator);
}

$formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL);
if (is_string($patternOrDecimals)) {
$formatter->setPattern($patternOrDecimals);
} else {
$formatter->setAttribute(\NumberFormatter::FRACTION_DIGITS, $patternOrDecimals);
}
return $formatter->format($number);
return $this->getNumberFormatter($this->locale, $patternOrDecimals)->format($number);
}


Expand All @@ -250,15 +247,37 @@ public function bytes(float $bytes, int $precision = 2): string
if ($this->locale === null) {
$bytes = (string) round($bytes, $precision);
} else {
$formatter = new \NumberFormatter($this->locale, \NumberFormatter::DECIMAL);
$formatter->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $precision);
$bytes = $formatter->format($bytes);
$bytes = $this->getNumberFormatter($this->locale, $precision, \NumberFormatter::MAX_FRACTION_DIGITS)->format($bytes);
}

return $bytes . ' ' . $unit;
}


/**
* Returns a formatter that rounds half up like round() and number_format().
*/
private function getNumberFormatter(
string $locale,
string|int $patternOrDigits,
int $digitsAttribute = \NumberFormatter::FRACTION_DIGITS,
): \NumberFormatter
{
$key = $locale . (is_string($patternOrDigits) ? " p$patternOrDigits" : " $digitsAttribute:$patternOrDigits");
if (!isset($this->numberFormatters[$key])) {
$formatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL);
$formatter->setAttribute(\NumberFormatter::ROUNDING_MODE, \NumberFormatter::ROUND_HALFUP);
if (is_string($patternOrDigits)) {
$formatter->setPattern($patternOrDigits);
} else {
$formatter->setAttribute($digitsAttribute, $patternOrDigits);
}
$this->numberFormatters[$key] = $formatter;
}
return $this->numberFormatters[$key];
}


/**
* Performs a search and replace.
* @param string|array<string, string>|array<string> $search
Expand Down
1 change: 1 addition & 0 deletions src/Latte/Essential/Nodes/EmbedNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public static function create(Tag $tag, TemplateParser $parser): \Generator
$node->mode = $mode ?? ($node->name instanceof StringNode && preg_match('~[\w-]+$~DA', $node->name->value) ? 'block' : 'file');
$tag->parser->stream->tryConsume(',');
$node->args = $tag->parser->parseArguments();
$node->args->validateArguments();

$prevIndex = $parser->blockLayer;
$layer = $parser->blockLayer = $node->layer = count($parser->blocks);
Expand Down
1 change: 1 addition & 0 deletions src/Latte/Essential/Nodes/ExtendsNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public static function create(Tag $tag): static
}
$tag->parser->consumeCommaBeforeArguments();
$node->args = $tag->parser->parseArguments();
$node->args->validateArguments();
if ($node->args->items && $node->extends instanceof BooleanNode) {
throw new CompileException("{{$tag->name} none} cannot have arguments.", $tag->position);
}
Expand Down
1 change: 1 addition & 0 deletions src/Latte/Essential/Nodes/ImportNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public static function create(Tag $tag): static
$node->file = $tag->parser->parseUnquotedStringOrExpression();
$tag->parser->stream->tryConsume(',');
$node->args = $tag->parser->parseArguments();
$node->args->validateArguments();
return $node;
}

Expand Down
1 change: 1 addition & 0 deletions src/Latte/Essential/Nodes/IncludeBlockNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public static function create(Tag $tag, TemplateParser $parser): static

$stream->tryConsume(',');
$node->args = $tag->parser->parseArguments();
$node->args->validateArguments();
$node->modifier = $tag->parser->parseModifier();

$node->parent = $tokenName->is('parent');
Expand Down
1 change: 1 addition & 0 deletions src/Latte/Essential/Nodes/IncludeFileNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public static function create(Tag $tag): static

$stream->tryConsume(',');
$node->args = $tag->parser->parseArguments();
$node->args->validateArguments();
$node->modifier = $tag->parser->parseModifier();
$node->modifier->escape = !$node->modifier->removeFilter('noescape');
return $node;
Expand Down
2 changes: 1 addition & 1 deletion src/Latte/Essential/Passes.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public function checkUrlsPass(TemplateNode $node): void
&& !$node->modifier->removeFilter('nocheck') && !$node->modifier->removeFilter('noCheck')
&& !$node->modifier->hasFilter('datastream') && !$node->modifier->hasFilter('dataStream')
) {
$node->modifier->filters[] = new Php\FilterNode(new Php\IdentifierNode('checkUrl'));
$node->modifier->filters[] = new Php\FilterNode(new Php\IdentifierNode('checkUrl'), nullsafe: true); // null drops the attribute
}
});
}
Expand Down
Loading