Completed
Push — master ( e2110b...10470b )
by Paweł
14s
created

StaticThemeAssetsController::screenshotsAction()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 5
cts 5
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 6
nop 3
crap 4
1
<?php
2
3
/*
4
 * This file is part of the Superdesk Web Publisher Core Bundle.
5
 *
6
 * Copyright 2015 Sourcefabric z.u. and contributors.
7
 *
8
 * For the full copyright and license information, please see the
9
 * AUTHORS and LICENSE files distributed with this source code.
10
 *
11
 * @copyright 2015 Sourcefabric z.ú
12
 * @license http://www.superdesk.org/license
13
 */
14
15
namespace SWP\Bundle\CoreBundle\Controller;
16
17
use Hoa\File\Read;
18
use Hoa\Mime\Mime;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
21
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
22
use Symfony\Component\HttpFoundation\Response;
23
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
24
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
25
26
class StaticThemeAssetsController extends Controller
27
{
28
    /**
29
     * Directory with assets inside theme.
30
     */
31
    const ASSETS_DIRECTORY = 'public';
32
33
    /**
34
     * @Route("/{fileName}.{fileExtension}", name="static_theme_assets_root", requirements={
35
     *     "fileName": "sw|manifest"
36
     * })
37
     * @Method("GET")
38
     */
39 1
    public function rootAction($fileName, $fileExtension)
40
    {
41 1
        $themes = $this->get('sylius.theme.hierarchy_provider')->getThemeHierarchy(
42 1
            $this->get('sylius.context.theme')->getTheme()
43 1
        );
44 1 View Code Duplication
        foreach ($themes as $theme) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
45
            $filePath = $theme->getPath().'/'.self::ASSETS_DIRECTORY.'/'.$fileName.'.'.$fileExtension;
46
            if (null !== $response = $this->handleFileLoading($filePath)) {
47
                return $response;
48
            }
49
        }
50
51
        throw new NotFoundHttpException('Page was not found.');
52
    }
53
54 1
    /**
55
     * @Route("/themes/{type}/{themeName}/screenshots/{fileName}", name="static_theme_screenshots", requirements={
56 1
     *     "type": "organization|tenant"
57 1
     * })
58 1
     * @Method("GET")
59 1
     */
60
    public function screenshotsAction(string $type, string $themeName, $fileName)
61
    {
62 1
        if ('organization' === $type) {
63
            $theme = $this->loadOrganizationTheme(str_replace('__', '/', $themeName));
64
        } elseif ('tenant' === $type) {
65
            $theme = $this->loadTenantTheme(str_replace('__', '/', $themeName));
66
        }
67
68
        $filePath = $theme->getPath().'/screenshots/'.$fileName;
0 ignored issues
show
Bug introduced by
The variable $theme does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
69
        if (null !== $response = $this->handleFileLoading($filePath)) {
70 2
            return $response;
71
        }
72 2
73 2
        throw new NotFoundHttpException('Page was not found.');
74 2
    }
75 2
76
    /**
77
     * @Route("/public/{filePath}", name="static_theme_assets_public", requirements={"filePath"=".+"})
78 2
     * @Method("GET")
79 2
     */
80 2
    public function publicAction($filePath)
81 2
    {
82 2
        $themes = $this->get('sylius.theme.hierarchy_provider')->getThemeHierarchy(
83
            $this->get('sylius.context.theme')->getTheme()
84 2
        );
85 View Code Duplication
        foreach ($themes as $theme) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
86 1
            $themeFilePath = $theme->getPath().'/'.self::ASSETS_DIRECTORY.'/'.$filePath;
87
            if (null !== $response = $this->handleFileLoading($themeFilePath, basename($filePath))) {
0 ignored issues
show
Unused Code introduced by
The call to StaticThemeAssetsController::handleFileLoading() has too many arguments starting with basename($filePath).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
88
                return $response;
89
            }
90
        }
91
92
        throw new NotFoundHttpException('File was not found.', null, 404);
93
    }
94
95
    /**
96
     * @param $filePath
97
     *
98
     * @return Response
99
     */
100
    private function handleFileLoading($filePath)
101
    {
102
        if (file_exists($filePath)) {
103
            $response = new Response(file_get_contents($filePath));
0 ignored issues
show
Security File Exposure introduced by
$filePath can contain request data and is used in file inclusion context(s) leading to a potential security vulnerability.

3 paths for user data to reach this point

  1. Path: Entered via action parameter $fileName in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 39
  1. Entered via action parameter $fileName
    in vendor/src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 39
  2. $filePath is assigned
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 45
  3. $filePath is passed to StaticThemeAssetsController::handleFileLoading()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 46
  2. Path: Entered via action parameter $fileName in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 60
  1. Entered via action parameter $fileName
    in vendor/src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 60
  2. $filePath is assigned
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 68
  3. $filePath is passed to StaticThemeAssetsController::handleFileLoading()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 69
  3. Path: Entered via action parameter $filePath in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 80
  1. Entered via action parameter $filePath
    in vendor/src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 80
  2. $themeFilePath is assigned
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 86
  3. $themeFilePath is passed to StaticThemeAssetsController::handleFileLoading()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 87

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
Security Cross-Site Scripting introduced by
file_get_contents($filePath) can contain request data and is used in output context(s) leading to a potential security vulnerability.

3 paths for user data to reach this point

  1. Path: Entered via action parameter $fileName in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 39
  1. Entered via action parameter $fileName
    in vendor/src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 39
  2. $filePath is assigned
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 45
  3. $filePath is passed to StaticThemeAssetsController::handleFileLoading()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 46
  4. $filePath is passed through file_get_contents()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 103
  2. Path: Entered via action parameter $fileName in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 60
  1. Entered via action parameter $fileName
    in vendor/src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 60
  2. $filePath is assigned
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 68
  3. $filePath is passed to StaticThemeAssetsController::handleFileLoading()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 69
  4. $filePath is passed through file_get_contents()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 103
  3. Path: Entered via action parameter $filePath in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 80
  1. Entered via action parameter $filePath
    in vendor/src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 80
  2. $themeFilePath is assigned
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 86
  3. $themeFilePath is passed to StaticThemeAssetsController::handleFileLoading()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 87
  4. $filePath is passed through file_get_contents()
    in src/SWP/Bundle/CoreBundle/Controller/StaticThemeAssetsController.php on line 103

Used in output context

  1. Response::__construct() uses Response::setContent() ($content)
    in vendor/src/Symfony/Component/HttpFoundation/Response.php on line 201
  2. Response::setContent() uses property Response::$content for writing
    in vendor/src/Symfony/Component/HttpFoundation/Response.php on line 412
  3. Property Response::$content is used in echo
    in vendor/src/Symfony/Component/HttpFoundation/Response.php on line 371

Preventing Cross-Site-Scripting Attacks

Cross-Site-Scripting allows an attacker to inject malicious code into your website - in particular Javascript code, and have that code executed with the privileges of a visiting user. This can be used to obtain data, or perform actions on behalf of that visiting user.

In order to prevent this, make sure to escape all user-provided data:

// for HTML
$sanitized = htmlentities($tainted, ENT_QUOTES);

// for URLs
$sanitized = urlencode($tainted);

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
104
            $disposition = $response->headers->makeDisposition(
105
                ResponseHeaderBag::DISPOSITION_INLINE,
106
                basename($filePath)
107
            );
108
            $response->headers->set('Content-Disposition', $disposition);
109
            $type = new Mime(new Read($filePath));
110
            $mime = str_replace('/x-', '/', Mime::getMimeFromExtension($type->getExtension()));
111
            $response->headers->set('Content-Type', $mime);
112
            $response->setStatusCode(Response::HTTP_OK);
113
            $response->setPublic();
114
            $response->setMaxAge(3600);
115
            $response->setSharedMaxAge(7200);
116
117
            return $response;
118
        }
119
    }
120
121
    /**
122
     * @param string $themeName
123
     *
124
     * @return mixed
125
     */
126
    private function loadOrganizationTheme(string $themeName)
127
    {
128
        $loadedThemes = $this->container->get('swp_core.loader.organization.theme')->load();
129
130
        return $this->filterThemes($loadedThemes, $themeName);
131
    }
132
133
    /**
134
     * @param string $themeName
135
     *
136
     * @return mixed
137
     */
138
    private function loadTenantTheme(string $themeName)
139
    {
140
        $loadedThemes = $this->container->get('sylius.repository.theme')->findAll();
141
142
        return $this->filterThemes($loadedThemes, $themeName);
143
    }
144
145
    /**
146
     * @param array  $loadedThemes
147
     * @param string $themeName
148
     *
149
     * @return mixed
150
     */
151
    private function filterThemes($loadedThemes, string $themeName)
152
    {
153
        $themes = array_filter(
154
            $loadedThemes,
155
            function ($element) use (&$themeName) {
156
                return $element->getName() === $themeName;
157
            }
158
        );
159
160
        if (count($themes) === 0) {
161
            throw new NotFoundHttpException(sprintf('Theme with name "%s" was not found in organization themes.', $themeName));
162
        }
163
164
        return reset($themes);
165
    }
166
}
167