-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLint.php
More file actions
565 lines (476 loc) · 17.7 KB
/
Copy pathLint.php
File metadata and controls
565 lines (476 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
<?php
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
/**
* Italix Encode - Template output lint
*
* @package Italix\Encode
* @license MPL-2.0
*/
declare(strict_types=1);
namespace Italix\Encode;
/**
* Fails the build on any template output that is not encoded.
*
* The encoders in Html are only half a defence: an encoder that must be invoked
* is not a default, and a template that forgot one renders correctly for every
* value anyone tries by hand. This turns "we always encode" from a habit into
* something CI can refuse to merge.
*
* $lint = new Lint(['/^\$view->get\(/', '/^\$form_html->/']);
* foreach ($lint->check_paths(['src/Views', 'src/Themes']) as $finding) {
* printf("%s:%d: %s\n", $finding['file'], $finding['line'], $finding['expression']);
* }
*
* The check is deliberately shallow but exact about where it looks. It reads
* PHP's own token stream rather than matching source text, because a regex
* cannot tell `<?= $x ?>` from the same characters inside a string literal or a
* comment. For every echo it splits the expression into the terms that actually
* reach the page — through concatenation, comma lists, ?? and the branches of a
* ternary, but not a ternary's condition, which is tested and discarded — and
* requires each one to be a literal, a numeric cast, an Html encoder call, or a
* match against the project's allow list.
*
* The encoder alias is resolved from the file's own `use` statements, so a file
* that writes `H::e(...)` without importing Italix\Encode\Html is reported: the
* lint accepts the encoder, not the letter H.
*
* What it cannot see is the limit worth stating plainly: it reads source text,
* so a value assembled at runtime and emitted through an allow-listed
* expression passes unexamined, and a template outside the paths it is given is
* not checked at all. This is a static guarantee standing in for a guarantee
* the template engine does not provide — good enough to keep a codebase honest,
* not the same thing as escaping in the compiler.
*/
final class Lint
{
/** Methods on Html that produce encoded output. */
private const ENCODER_METHODS = ['e', 'raw', 'j', 'attribs', 'url'];
/** The class an alias has to resolve to, lower-cased. */
private const ENCODER_CLASS = 'italix\encode\html';
/**
* Other classes whose static methods return an already-encoded value.
*
* A project builds encoders of its own on top of this one — a translator
* that returns `Html`, a money formatter, a markdown renderer that has run
* a sanitiser. Their output is safe for the same reason `Html::e()`'s is,
* and without a way to say so the lint reports every call and the report
* becomes noise somebody learns to skip past. A lint nobody reads is worse
* than no lint, because it looks like coverage.
*
* Registered by name, not by prefix, and still resolved through the file's
* own `use` statements: the point stands that the lint accepts the class,
* not the letter it was aliased to.
*
* @var array<string, string[]> lower-cased FQCN => methods it encodes with
*/
private array $encoder_classes;
/** @var string[] PCRE patterns matched against a term's source. */
private array $allow;
/** @var string[] */
private array $extensions;
/**
* @param string[] $allow PCRE patterns for expressions that are safe by other means
* @param string[] $extensions File extensions to scan
* @param array<int|string, string|string[]> $encoders Extra classes whose static
* methods return encoded values. Either a bare name, which takes the
* same method list as Html, or `name => ['method', …]` when the class
* encodes through methods of its own — a translator's `choice_e()`,
* say, which has no counterpart here.
*/
public function __construct(array $allow = [], array $extensions = ['php'], array $encoders = [])
{
$this->allow = $allow;
$this->extensions = $extensions;
$this->encoder_classes = [];
foreach ($encoders as $key => $value) {
$fqcn = is_int($key) ? (string) $value : (string) $key;
$methods = is_int($key) ? self::ENCODER_METHODS : (array) $value;
$this->encoder_classes[strtolower(ltrim($fqcn, '\\'))] = $methods;
}
}
// -------------------------------------------------------------------------
// Public
// -------------------------------------------------------------------------
/**
* @param string[] $paths Files or directories
* @return array<int,array{file:string,line:int,expression:string}>
*/
public function check_paths(array $paths): array
{
$findings = [];
foreach ($paths as $path) {
foreach ($this->files_in($path) as $file) {
foreach ($this->check_file($file) as $finding) {
$findings[] = $finding;
}
}
}
return $findings;
}
/**
* @return array<int,array{file:string,line:int,expression:string}>
*/
public function check_file(string $file): array
{
$code = file_get_contents($file);
if ($code === false) {
throw new \RuntimeException(sprintf('Lint: cannot read %s', $file));
}
$tokens = token_get_all($code);
$aliases = $this->encoder_aliases($tokens);
$count = count($tokens);
$findings = [];
for ($i = 0; $i < $count; $i++) {
if (!$this->is_echo($tokens[$i])) {
continue;
}
$line = $tokens[$i][2];
$expr = $this->collect_expression($tokens, $i, $count);
foreach ($this->output_terms($expr) as $term) {
if ($this->term_is_safe($term, $aliases)) {
continue;
}
$findings[] = [
'file' => $file,
'line' => $line,
'expression' => $this->source($term),
];
}
}
return $findings;
}
// -------------------------------------------------------------------------
// Scanning
// -------------------------------------------------------------------------
/**
* @return string[]
*/
private function files_in(string $path): array
{
if (is_file($path)) {
return [$path];
}
if (!is_dir($path)) {
throw new \RuntimeException(sprintf('Lint: no such file or directory: %s', $path));
}
$files = [];
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $entry) {
/** @var \SplFileInfo $entry */
if ($entry->isFile() && in_array($entry->getExtension(), $this->extensions, true)) {
$files[] = $entry->getPathname();
}
}
sort($files);
return $files;
}
/**
* @param array|string $token
*/
private function is_echo($token): bool
{
return is_array($token)
&& in_array($token[0], [T_OPEN_TAG_WITH_ECHO, T_ECHO, T_PRINT], true);
}
/**
* Everything between the echo and its terminating ; or ?>.
*
* @param array<int,array|string> $tokens
* @return array<int,array|string>
*/
private function collect_expression(array $tokens, int &$i, int $count): array
{
$expr = [];
$depth = 0;
for ($i++; $i < $count; $i++) {
$token = $tokens[$i];
$delta = $this->depth_delta($token);
if ($delta !== 0) {
$depth += $delta;
} elseif ($depth === 0) {
if ($token === ';') {
break;
}
if (is_array($token) && $token[0] === T_CLOSE_TAG) {
break;
}
}
$expr[] = $token;
}
return $expr;
}
/**
* Nesting contributed by a token.
*
* The subtlety that makes a hand-rolled depth counter wrong: in `"{$a}"`
* the opening brace arrives as the *array* token T_CURLY_OPEN while the
* closing one is the plain string '}'. Counting only strings drives the
* depth negative, and from there every separator looks top-level and the
* expression never terminates.
*
* @param array|string $token
*/
private function depth_delta($token): int
{
if (is_string($token)) {
if (strpos('([{', $token) !== false) {
return 1;
}
return strpos(')]}', $token) !== false ? -1 : 0;
}
return in_array($token[0], self::opening_tokens(), true) ? 1 : 0;
}
/**
* @return int[]
*/
private static function opening_tokens(): array
{
static $tokens = null;
if ($tokens === null) {
$tokens = [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES];
if (defined('T_ATTRIBUTE')) {
$tokens[] = T_ATTRIBUTE; // #[ … ] — PHP 8
}
}
return $tokens;
}
// -------------------------------------------------------------------------
// Expression analysis
// -------------------------------------------------------------------------
/**
* The terms that actually reach the page.
*
* Splits on concatenation, comma lists and ??; for a ternary, drops the
* condition and keeps both branches, since only those are printed.
*
* @param array<int,array|string> $expr
* @return array<int,array<int,array|string>>
*/
private function output_terms(array $expr): array
{
$expr = $this->strip_ternary_condition($expr);
$terms = [];
$current = [];
$depth = 0;
foreach ($expr as $token) {
$delta = $this->depth_delta($token);
if ($delta !== 0) {
$depth += $delta;
} elseif ($depth === 0 && $this->is_term_separator($token)) {
$terms[] = $current;
$current = [];
continue;
}
$current[] = $token;
}
$terms[] = $current;
return array_values(array_filter($terms, fn(array $t): bool => $this->source($t) !== ''));
}
/**
* @param array|string $token
*/
private function is_term_separator($token): bool
{
if (is_string($token)) {
return $token === '.' || $token === ',' || $token === ':';
}
return $token[0] === T_COALESCE;
}
/**
* A ternary's condition is tested, not printed. `?:` has no condition to
* drop — both sides can reach the page — so it is left alone.
*
* @param array<int,array|string> $expr
* @return array<int,array|string>
*/
private function strip_ternary_condition(array $expr): array
{
$depth = 0;
foreach ($expr as $index => $token) {
$delta = $this->depth_delta($token);
if ($delta !== 0) {
$depth += $delta;
} elseif ($token === '?' && $depth === 0) {
$rest = array_slice($expr, $index + 1);
// `?:` — the left operand is printed when truthy, so keep it.
foreach ($rest as $next) {
if (is_array($next) && $next[0] === T_WHITESPACE) {
continue;
}
return ($next === ':') ? $expr : $rest;
}
return $rest;
}
}
return $expr;
}
/**
* @param array<int,array|string> $term
* @param string[] $aliases
*/
private function term_is_safe(array $term, array $aliases): bool
{
$significant = array_values(array_filter($term, static function ($token): bool {
return !is_array($token)
|| !in_array($token[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true);
}));
if ($significant === []) {
return true;
}
// A literal cannot carry markup it did not already contain.
$literal = true;
foreach ($significant as $token) {
if (!is_array($token)
|| !in_array($token[0], [T_CONSTANT_ENCAPSED_STRING, T_LNUMBER, T_DNUMBER], true)) {
$literal = false;
break;
}
}
if ($literal) {
return true;
}
// (int) $x and friends cannot produce a tag.
$first = $significant[0];
if (is_array($first) && in_array($first[0], [T_INT_CAST, T_DOUBLE_CAST, T_BOOL_CAST], true)) {
return true;
}
$source = $this->source($term);
if ($this->is_encoder_call($source, $aliases)) {
return true;
}
foreach ($this->allow as $pattern) {
if (preg_match($pattern, $source) === 1) {
return true;
}
}
return false;
}
/**
* @param string[] $aliases
*/
private function is_encoder_call(string $source, array $aliases): bool
{
$matched = preg_match(
'/^\\\\?((?:[A-Za-z_][A-Za-z0-9_]*\\\\)*[A-Za-z_][A-Za-z0-9_]*)::([A-Za-z_]+)\s*\(/',
trim($source),
$m
);
if ($matched !== 1) {
return false;
}
$alias = strtolower($m[1]);
return isset($aliases[$alias]) && in_array($m[2], $aliases[$alias], true);
}
// -------------------------------------------------------------------------
// Alias resolution
// -------------------------------------------------------------------------
/**
* Names that refer to an encoder inside this file, lower-cased, each mapped
* to the methods it encodes with.
*
* Always includes the fully qualified names; anything shorter has to be
* earned by a `use` statement, so `H::e(...)` in a file that never imported
* the class is reported rather than trusted.
*
* @param array<int,array|string> $tokens
* @return array<string, string[]>
*/
private function encoder_aliases(array $tokens): array
{
$known = [self::ENCODER_CLASS => self::ENCODER_METHODS] + $this->encoder_classes;
$aliases = $known;
foreach ($this->use_clauses($tokens) as $clause) {
if (stripos($clause, 'function ') === 0 || stripos($clause, 'const ') === 0) {
continue;
}
foreach ($this->expand_group_use($clause) as $import) {
if (preg_match('/^(.+?)\s+as\s+(\S+)$/i', $import, $m) === 1) {
$fqcn = ltrim($m[1], '\\');
$alias = $m[2];
} else {
$fqcn = ltrim($import, '\\');
$parts = explode('\\', $fqcn);
$alias = end($parts);
}
if (isset($known[strtolower($fqcn)])) {
$aliases[strtolower($alias)] = $known[strtolower($fqcn)];
}
}
}
return $aliases;
}
/**
* The source of every import `use`, read from the token stream.
*
* A regex would need an anchor, and every anchor is wrong for some real
* file: `^use` misses `<?php use … ?>` on one line, and an unanchored match
* hits the word inside comments. Tokens have no such ambiguity. Closure
* `use (…)` is excluded by looking at what precedes the keyword.
*
* @param array<int,array|string> $tokens
* @return string[]
*/
private function use_clauses(array $tokens): array
{
$clauses = [];
$count = count($tokens);
$previous = null;
for ($i = 0; $i < $count; $i++) {
$token = $tokens[$i];
if (is_array($token) && in_array($token[0], [T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], true)) {
continue;
}
if (is_array($token) && $token[0] === T_USE && $previous !== ')') {
$clause = '';
for ($i++; $i < $count && $tokens[$i] !== ';'; $i++) {
$clause .= is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i];
}
$clauses[] = trim(preg_replace('/\s+/', ' ', $clause) ?? '');
$previous = ';';
continue;
}
$previous = is_array($token) ? $token[1] : $token;
}
return $clauses;
}
/**
* `A\B\{C, D as E}` → ['A\B\C', 'A\B\D as E'].
*
* @return string[]
*/
private function expand_group_use(string $clause): array
{
if (preg_match('/^(.*?)\\\\\{(.+)\}$/', $clause, $m) !== 1) {
return [$clause];
}
$prefix = $m[1];
$imports = [];
foreach (explode(',', $m[2]) as $item) {
$item = trim($item);
if ($item !== '') {
$imports[] = $prefix . '\\' . $item;
}
}
return $imports;
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
/**
* @param array<int,array|string> $tokens
*/
private function source(array $tokens): string
{
$out = '';
foreach ($tokens as $token) {
$out .= is_array($token) ? $token[1] : $token;
}
return trim($out);
}
}