Issues (4)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Generator.php (3 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright   Copyright (c) 2016 ublaboo <[email protected]>
7
 * @author      Pavel Janda <[email protected]>
8
 * @package     Ublaboo
9
 */
10
11
namespace Ublaboo\ApiDocu;
12
13
use Nette\Application\IRouter;
14
use Nette\Application\Request;
15
use Nette\Application\UI\ITemplate;
16
use Nette\Application\UI\ITemplateFactory;
17
use Nette\Http;
18
use Tracy\Debugger;
19
use Ublaboo\ApiRouter\ApiRoute;
20
21
class Generator
22
{
23
24
	/**
25
	 * @var ITemplateFactory
26
	 */
27
	private $templateFactory;
28
29
	/**
30
	 * @var Http\Request
31
	 */
32
	private $httpRequest;
33
34
	/**
35
	 * @var string
36
	 */
37
	private $appDir;
38
39
	/**
40
	 * @var array
41
	 */
42
	private $httpAuth;
43
44
45
	public function __construct(
46
		string $appDir,
47
		array $httpAuth,
48
		ITemplateFactory $templateFactory,
49
		Http\Request $httpRequest
50
	) {
51
		$this->appDir = $appDir;
52
		$this->httpAuth = $httpAuth;
53
		$this->templateFactory = $templateFactory;
54
		$this->httpRequest = $httpRequest;
55
	}
56
57
58
	public function generateAll(IRouter $router): void
59
	{
60
		$sections = $this->splitRoutesIntoSections($router);
61
62
		if (!file_exists($this->appDir) && !is_dir($this->appDir)) {
63
			mkdir($this->appDir);
64
		}
65
66
		/**
67
		 * Create index.php
68
		 */
69
		$this->generateIndex($sections);
70
71
		/**
72
		 * Create *.php for each defined ApiRoute
73
		 */
74
		foreach ($sections as $sectionName => $routes) {
75
			if (is_array($routes)) {
76
				foreach ($routes as $fileName => $route) {
77
					$this->generateOne($route, $sections, "$sectionName.$fileName");
78
				}
79
			} else {
80
				$this->generateOne($routes, $sections, (string) $sectionName);
81
			}
82
		}
83
84
		$this->generateSuccess();
85
	}
86
87
88
	public function generateTarget(ApiRoute $route, Request $request): void
89
	{
90
		$template = $this->createTemplate('api_docu_matched.latte');
91
92
		$template->setParameters([
93
			'route' => $route,
94
			'request' => $request,
95
			'httpRequest' => $this->httpRequest,
96
		]);
97
98
		if (class_exists('Tracy\Debugger')) {
99
			Debugger::$productionMode = true;
100
		}
101
102
		echo (string) $template;
103
	}
104
105
106 View Code Duplication
	public function generateOne(ApiRoute $route, array $sections, string $fileName): void
0 ignored issues
show
This method seems to be duplicated in 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...
107
	{
108
		$template = $this->createTemplate('api_docu_one.latte');
109
110
		$template->setParameters([
111
			'route' => $route,
112
			'sections' => $sections,
113
		]);
114
115
		file_put_contents(
116
			"{$this->appDir}/{$fileName}.php",
117
			$this->getHttpAuthSnippet() . $template
118
		);
119
	}
120
121
122 View Code Duplication
	public function generateIndex(array $sections): void
0 ignored issues
show
This method seems to be duplicated in 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...
123
	{
124
		$template = $this->createTemplate('api_docu_index.latte');
125
126
		$template->setParameters([
127
			'sections' => $sections,
128
		]);
129
130
		file_put_contents(
131
			"{$this->appDir}/index.php",
132
			$this->getHttpAuthSnippet() . $template
133
		);
134
	}
135
136
137
	public function generateSuccess(): void
138
	{
139
		$template = $this->createTemplate('api_docu_success.latte');
140
141
		$template->setParameters([
142
			'apiDir' => $this->appDir,
143
		]);
144
145
		if (class_exists('Tracy\Debugger')) {
146
			Debugger::$productionMode = true;
147
		}
148
149
		echo (string) $template;
150
	}
151
152
153
	public function createTemplate(string $which): ITemplate
154
	{
155
		$template = $this->templateFactory->createTemplate();
156
157
		$template->addFilter(null, 'Ublaboo\ApiDocu\TemplateFilters::common');
158
159
		$template->setFile(__DIR__ . '/templates/' . $which);
160
161
		if ($template instanceof ITemplate) {
162
			$template->base_dir = __DIR__ . '/templates';
0 ignored issues
show
Accessing base_dir on the interface Nette\Application\UI\ITemplate suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
163
		}
164
165
		$template->addFilter('routeMaskStyles', function ($mask) {
166
			return str_replace(['<', '>'], ['<span class="apiDocu-mask-param">&lt;', '&gt;</span>'], $mask);
167
		});
168
169
		$template->addFilter('apiDocuResponseCode', function ($code) {
170
			if ($code >= 200 && $code <= 202) {
171
				return "<span class=\"apiDocu-code-success\">{$code}</span>";
172
			} elseif ($code >= 300 && $code < 500) {
173
				return "<span class=\"apiDocu-code-warning\">{$code}</span>";
174
			} elseif ($code >= 500) {
175
				return "<span class=\"apiDocu-code-error\">{$code}</span>";
176
			}
177
178
			return "<span class=\"apiDocu-code-other\">{$code}</span>";
179
		});
180
181
		return $template;
182
	}
183
184
185
	/********************************************************************************
186
	 *                                   INTERNAL                                   *
187
	 ********************************************************************************/
188
189
190
	private function splitRoutesIntoSections(IRouter $router): array
191
	{
192
		$routes = [];
193
		$sections = [];
194
		$fileName = 1;
195
196
		if ($router instanceof ApiRoute) {
197
			$routes = [$router];
198
		} elseif ($router instanceof \IteratorAggregate) {
199
			$routes = $this->getApiRoutesFromIterator($router);
200
		}
201
202
		foreach ($routes as $route) {
203
			if ($route->getSection()) {
204
				if (empty($sections[$route->getSection()])) {
205
					$sections[$route->getSection()] = [];
206
				}
207
208
				$sections[$route->getSection()][$fileName++] = $route;
209
			} else {
210
				$sections[$fileName++] = $route;
211
			}
212
		}
213
214
		return $sections;
215
	}
216
217
218
	/**
219
	 * Recursively flatten \IteratorAggregate (probably Nette\Application\Routers\RouteList)
220
	 */
221
	private function getApiRoutesFromIterator(\IteratorAggregate $i): array
222
	{
223
		$return = [];
224
225
		foreach ($i as $router) {
226
			if ($router instanceof ApiRoute) {
227
				$return[] = $router;
228
			} elseif ($router instanceof \IteratorAggregate) {
229
				$routes = $this->getApiRoutesFromIterator($router);
230
231
				foreach ($routes as $route) {
232
					$return[] = $route;
233
				}
234
			}
235
		}
236
237
		return $return;
238
	}
239
240
241
	private function getHttpAuthSnippet(): string
242
	{
243
		if (!$this->httpAuth['user'] || !$this->httpAuth['password']) {
244
			return '';
245
		}
246
247
		$u = $this->httpAuth['user'];
248
		$p = $this->httpAuth['password'];
249
250
		return "<?php if (!isset(\$_SERVER['PHP_AUTH_USER']) || \$_SERVER['PHP_AUTH_USER'] !== '{$u}' || \$_SERVER['PHP_AUTH_PW'] !== '{$p}') {"
251
			. "	header('WWW-Authenticate: Basic realm=\"Api\"');"
252
			. "	header('HTTP/1.0 401 Unauthorized');"
253
			. "	die('Invalid authentication');"
254
			. '} ?>';
255
	}
256
}
257