- 
                Notifications
    
You must be signed in to change notification settings  - Fork 165
 
Rector rule added to escape unsafe output in phtml files #472
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            Jakhotiya
  wants to merge
  4
  commits into
  magento:develop
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
Jakhotiya:develop
  
      
      
   
  
    
  
  
  
 
  
      
    base: develop
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            4 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      8fb1e13
              
                This rule escapes output using ->escapeHtml output function. It shoul…
              
              
                 e8232c6
              
                Fixed phpcs errors and warnings because of which the merge checks wer…
              
              
                 9780610
              
                Added tests for different kind of expressions possible in echo statem…
              
              
                 5ddc480
              
                Fixed phpcs sniffs w.r.t to docblocks and spacing
              
              
                 File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,186 @@ | ||
| <?php | ||
| /** | ||
| * Copyright 2021 Adobe | ||
| * See COPYING.txt for license details. | ||
| */ | ||
| declare(strict_types=1); | ||
| 
     | 
||
| namespace Magento2\Rector\Src; | ||
| 
     | 
||
| use PhpParser\Node; | ||
| use PhpParser\Node\Stmt\Echo_; | ||
| use Rector\Core\Rector\AbstractRector; | ||
| use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; | ||
| use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; | ||
| 
     | 
||
| class AddHtmlEscaperToOutput extends AbstractRector | ||
| { | ||
| 
     | 
||
| /** | ||
| * @var string[] | ||
| */ | ||
| private $_phpFunctionsToIgnore = ['\count','\strip_tags']; | ||
| 
     | 
||
| /** | ||
| * @inheritDoc | ||
| */ | ||
| public function getNodeTypes(): array | ||
| { | ||
| return [Echo_::class]; | ||
| } | ||
| 
     | 
||
| /** | ||
| * @inheritDoc | ||
| */ | ||
| public function refactor(Node $node): ?Node | ||
| { | ||
| 
     | 
||
| $echoContent = $node->exprs[0]; | ||
| 
     | 
||
| if ($echoContent instanceof Node\Expr\Ternary) { | ||
| 
     | 
||
| if (!$this->hasNoEscapeAttribute($echoContent->if) && $this->canEscapeOutput($echoContent->if)) { | ||
| $node->exprs[0]->if = new Node\Expr\MethodCall( | ||
| new Node\Expr\Variable('escaper'), | ||
| 'escapeHtml', | ||
| [new Node\Arg($echoContent->if)] | ||
| ); | ||
| 
     | 
||
| } | ||
| 
     | 
||
| if (!$this->hasNoEscapeAttribute($echoContent->else) && $this->canEscapeOutput($echoContent->else)) { | ||
| $node->exprs[0]->else = new Node\Expr\MethodCall( | ||
| new Node\Expr\Variable('escaper'), | ||
| 'escapeHtml', | ||
| [new Node\Arg($echoContent->else)] | ||
| ); | ||
| 
     | 
||
| } | ||
| return $node; | ||
| 
     | 
||
| } | ||
| 
     | 
||
| if ($this->hasNoEscapeAttribute($echoContent)) { | ||
| return null; | ||
| } | ||
| 
     | 
||
| if ($this->canEscapeOutput($echoContent)) { | ||
| 
     | 
||
| $node->exprs[0] = new Node\Expr\MethodCall( | ||
| new Node\Expr\Variable('escaper'), | ||
| 'escapeHtml', | ||
| [new Node\Arg($echoContent)] | ||
| ); | ||
| return $node; | ||
| } | ||
| 
     | 
||
| return null; | ||
| } | ||
| 
     | 
||
| /** | ||
| * We check if content of the echo should be escaped | ||
| * | ||
| * @param Node $echoContent | ||
| * @return bool | ||
| */ | ||
| private function canEscapeOutput(Node $echoContent):bool | ||
| { | ||
| if ($echoContent instanceof Node\Expr\Variable) { | ||
| return true; | ||
| } | ||
| 
     | 
||
| if ($echoContent instanceof Node\Expr\FuncCall | ||
| && !$this->willFunctionReturnSafeOutput($echoContent)) { | ||
| 
     | 
||
| // if string passed to __() contains html don't do anthing | ||
| if ($echoContent->name == '__' && $this->stringContainsHtml($echoContent->args[0]->value->value)) { | ||
| return false; | ||
| } | ||
| 
     | 
||
| return true; | ||
| } | ||
| 
     | 
||
| // if the echo already has escapeHtml called on $block or escaper, don't do anthing | ||
| if ($echoContent instanceof Node\Expr\MethodCall && | ||
| !$this->methodReturnsValidHtmlOrUrl($echoContent) | ||
| ) { | ||
| 
     | 
||
| // if the method is part of secureRenderer don't do anything | ||
| if ($echoContent->var->name === 'secureRenderer') { | ||
| return false; | ||
| } | ||
| 
     | 
||
| return true; | ||
| 
     | 
||
| } | ||
| 
     | 
||
| return false; | ||
| } | ||
| 
     | 
||
| /** | ||
| * We do not want to escape __() output if the inner content contains html | ||
| * | ||
| * @param string $str | ||
| * @return bool | ||
| */ | ||
| private function stringContainsHtml(string $str) | ||
| { | ||
| return strlen($str) !== strlen(strip_tags($str)); | ||
| } | ||
| 
     | 
||
| /** | ||
| * If the developer has marked the output as noEscape by using the @noEscape we want to leave that code as it is | ||
| * | ||
| * @param Node $echoContent | ||
| */ | ||
| private function hasNoEscapeAttribute(Node $echoContent):bool | ||
| { | ||
| 
     | 
||
| $comments = $echoContent->getComments(); | ||
| foreach ($comments as $comment) { | ||
| if (stripos($comment->getText(), '@noEscape') !== false) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
| 
     | 
||
| /** | ||
| * If method contains the keyword HTML we assume developer intends to output html | ||
| * | ||
| * @param Node\Expr\MethodCall $echoContent | ||
| */ | ||
| private function methodReturnsValidHtmlOrUrl(Node\Expr\MethodCall $echoContent):bool | ||
| { | ||
| return stripos($echoContent->name->name, 'Html') !== false | ||
| || stripos($echoContent->name->name, 'Url') !== false; | ||
| } | ||
| 
     | 
||
| /** | ||
| * Some php function return safe output. count, strip_tags need not be escaped. | ||
| * | ||
| * @param Node\Expr\FuncCall $funcNode | ||
| */ | ||
| private function willFunctionReturnSafeOutput(Node\Expr\FuncCall $funcNode):bool | ||
| { | ||
| //@TODO did not handle things like $callback(); | ||
| $funcName = $funcNode->name->toCodeString(); | ||
| return in_array($funcName, $this->_phpFunctionsToIgnore); | ||
| } | ||
| 
     | 
||
| /** | ||
| * @inheritDoc | ||
| */ | ||
| public function getRuleDefinition(): RuleDefinition | ||
| { | ||
| return new RuleDefinition( | ||
| 'Add escaper methods like escapeHtml to html output', | ||
| [ | ||
| new CodeSample( | ||
| 'echo $productName', | ||
| 'echo $escaper->escapeHtml($productName)' | ||
| ), | ||
| ] | ||
| ); | ||
| } | ||
| } | 
        
          
          
            36 changes: 36 additions & 0 deletions
          
          36 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/AddHtmlEscaperToOutputTest.php
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| <?php | ||
| /** | ||
| * Copyright 2021 Adobe | ||
| * See COPYING.txt for license details. | ||
| */ | ||
| declare(strict_types=1); | ||
| 
     | 
||
| namespace Magento2\Rector\Tests\AddHtmlEscaperToOutput; | ||
| 
     | 
||
| use Iterator; | ||
| use Rector\Testing\PHPUnit\AbstractRectorTestCase; | ||
| use Symplify\SmartFileSystem\SmartFileInfo; | ||
| 
     | 
||
| class AddHtmlEscaperToOutputTest extends AbstractRectorTestCase | ||
| { | ||
| /** | ||
| * @dataProvider provideData() | ||
| */ | ||
| public function test(string $fileInfo): void | ||
| { | ||
| $this->doTestFile($fileInfo); | ||
| } | ||
| 
     | 
||
| /** | ||
| * @return Iterator<SmartFileInfo> | ||
| */ | ||
| public function provideData(): Iterator | ||
| { | ||
| return $this->yieldFilesFromDirectory(__DIR__ . '/Fixture'); | ||
| } | ||
| 
     | 
||
| public function provideConfigFilePath(): string | ||
| { | ||
| return __DIR__ . '/config/configured_rule.php'; | ||
| } | ||
| } | 
        
          
          
            11 changes: 11 additions & 0 deletions
          
          11 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/already-escaped-ouput.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <?php | ||
| 
     | 
||
| echo $escaper->escapeHtml($productName); | ||
| 
     | 
||
| ?> | ||
| ----- | ||
| <?php | ||
| 
     | 
||
| echo $escaper->escapeHtml($productName); | ||
| 
     | 
||
| ?> | 
        
          
          
            27 changes: 27 additions & 0 deletions
          
          27 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/complex-phtml-code-mix.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| <?php | ||
| $items = $block->getAllItems(); | ||
| ?> | ||
| <div class="test"> | ||
| <?php if (count($items) > 0): ?> | ||
| <div class="counter"><?= __('Total <span>%1</span> items found', count($items)) ?></div> | ||
| <?php foreach ($items as $item): ?> | ||
| <a href="<?= $block->getActionUrl($item); ?>"><?= $item->getName(); ?></a> | ||
| <?php endforeach; ?> | ||
| <?php else: ?> | ||
| <?= __('No items found.'); ?> | ||
| <?php endif; ?> | ||
| </div> | ||
| ----- | ||
| <?php | ||
| $items = $block->getAllItems(); | ||
| ?> | ||
| <div class="test"> | ||
| <?php if (count($items) > 0): ?> | ||
| <div class="counter"><?= __('Total <span>%1</span> items found', count($items)) ?></div> | ||
| <?php foreach ($items as $item): ?> | ||
| <a href="<?= $block->getActionUrl($item); ?>"><?= $escaper->escapeHtml($item->getName()); ?></a> | ||
| <?php endforeach; ?> | ||
| <?php else: ?> | ||
| <?= $escaper->escapeHtml(__('No items found.')); ?> | ||
| <?php endif; ?> | ||
| </div> | ||
        
          
          
            11 changes: 11 additions & 0 deletions
          
          11 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/function-call.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <?php | ||
| 
     | 
||
| echo $customer->getName(); | ||
| echo __('Something'); | ||
| ?> | ||
| ----- | ||
| <?php | ||
| 
     | 
||
| echo $escaper->escapeHtml($customer->getName()); | ||
| echo $escaper->escapeHtml(__('Something')); | ||
| ?> | 
        
          
          
            1 change: 1 addition & 0 deletions
          
          1 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/message-string-contains-html.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1 @@ | ||
| <div class="counter"><?= __('Total <span>%1</span> items found',count($items))?></div> | 
        
          
          
            3 changes: 3 additions & 0 deletions
          
          3 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/method-that-return-html.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| <?= $block->getChildHtml(); ?> | ||
| <?= $block->getToolBarHtml();?> | ||
| <?= $block->getChildBlock('toolbar')->setIsBottom(true)->toHtml() ?> | 
        
          
          
            11 changes: 11 additions & 0 deletions
          
          11 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/simple-echo.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <?php | ||
| 
     | 
||
| echo $productName; | ||
| 
     | 
||
| ?> | ||
| ----- | ||
| <?php | ||
| 
     | 
||
| echo $escaper->escapeHtml($productName); | ||
| 
     | 
||
| ?> | 
        
          
          
            4 changes: 4 additions & 0 deletions
          
          4 
        
  ...or/Tests/AddHtmlEscaperToOutput/Fixture/skip-escaped-output-using-secure-renderer.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| <?= $secureRenderer->renderStyleAsTag( | ||
| $position, | ||
| 'product-item-info_' . $_product->getId() . ' div.actions-primary' | ||
| ) ?> | 
        
          
          
            3 changes: 3 additions & 0 deletions
          
          3 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/skip-output-of-count-function.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| <?= count($items); ?> | ||
| <?= (int)$items ?> | ||
| <?= (bool)$items ?> | 
        
          
          
            3 changes: 3 additions & 0 deletions
          
          3 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/skip-with-no-escape-annotation.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| <?= /* @noEscape */ $block->getProductPrice($_product) ?> | ||
| <?= /* @noEscape */ $price ?> | ||
| <?= /* @noEscape */ trim($price) ?> | 
        
          
          
            11 changes: 11 additions & 0 deletions
          
          11 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/Fixture/ternary-condition.php.inc
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <?php | ||
| 
     | 
||
| echo $block->canShowInfo() ? $escaper->escapeHtml($block->getInfo()) : __('Nothing to show'); | ||
| 
     | 
||
| ?> | ||
| ----- | ||
| <?php | ||
| 
     | 
||
| echo $block->canShowInfo() ? $escaper->escapeHtml($block->getInfo()) : $escaper->escapeHtml(__('Nothing to show')); | ||
| 
     | 
||
| ?> | 
        
          
          
            13 changes: 13 additions & 0 deletions
          
          13 
        
  Magento2/Rector/Tests/AddHtmlEscaperToOutput/config/configured_rule.php
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| <?php | ||
| /** | ||
| * Copyright 2022 Adobe | ||
| * See COPYING.txt for license details. | ||
| */ | ||
| declare(strict_types=1); | ||
| 
     | 
||
| use Magento2\Rector\Src\AddArrayAccessInterfaceReturnTypes; | ||
| use Rector\Config\RectorConfig; | ||
| 
     | 
||
| return static function (RectorConfig $rectorConfig): void { | ||
| $rectorConfig->rule(\Magento2\Rector\Src\AddHtmlEscaperToOutput::class); | ||
| }; | 
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
shouldn't
$block->getActionUrl($item);be wrapped to escapeUrl? or escapeHtmlAttr (because it's part of attribute)?