Issues (286)

Security Analysis    not enabled

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.

TestsTraits/PhpUnit/TestsRequestHelperTrait.php (6 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
namespace Apiato\Core\Traits\TestsTraits\PhpUnit;
4
5
use Illuminate\Support\Arr;
6
use App;
7
use App\Ship\Exceptions\MissingTestEndpointException;
8
use App\Ship\Exceptions\UndefinedMethodException;
9
use App\Ship\Exceptions\WrongEndpointFormatException;
10
use Illuminate\Support\Facades\Config;
11
use Illuminate\Support\Str;
12
use Vinkla\Hashids\Facades\Hashids;
13
14
/**
15
 * Class TestsRequestHelperTrait
16
 *
17
 * Tests helper for making HTTP requests.
18
 *
19
 * @author  Mahmoud Zalt  <[email protected]>
20
 */
21
trait TestsRequestHelperTrait
22
{
23
24
    /**
25
     * property to be set on the user test class
26
     *
27
     * @var  string
28
     */
29
    protected $endpoint = '';
30
31
    /**
32
     * property to be set on the user test class
33
     *
34
     * @var  bool
35
     */
36
    protected $auth = true;
37
38
    /**
39
     * Http response
40
     *
41
     * @var  \Illuminate\Foundation\Testing\TestResponse
42
     */
43
    protected $response;
44
45
    /**
46
     * @var string
47
     */
48
    protected $responseContent;
49
50
    /**
51
     * @var array
52
     */
53
    protected $responseContentArray;
54
55
    /**
56
     * @var \stdClass
57
     */
58
    protected $responseContentObject;
59
60
    /**
61
     * Allows users to override the default class property `endpoint` directly before calling the `makeCall` function.
62
     *
63
     * @var string
64
     */
65
    protected $overrideEndpoint;
66
67
    /**
68
     * Allows users to override the default class property `auth` directly before calling the `makeCall` function.
69
     *
70
     * @var string
71
     */
72
    protected $overrideAuth;
73
74
    /**
75
     * @param array $data
76
     * @param array $headers
77
     *
78
     * @throws \App\Ship\Exceptions\UndefinedMethodException
79
     * 
80
     * @return \Illuminate\Foundation\Testing\TestResponse
81
     */
82
    public function makeCall(array $data = [], array $headers = [])
83
    {
84
        // Get or create a testing user. It will get your existing user if you already called this function from your
85
        // test. Or create one if you never called this function from your tests "Only if the endpoint is protected".
86
        $this->getTestingUser();
0 ignored issues
show
It seems like getTestingUser() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
87
88
        // read the $endpoint property from the test and set the verb and the uri as properties on this trait
89
        $endpoint = $this->parseEndpoint();
90
        $verb = $endpoint['verb'];
91
        $url = $endpoint['url'];
92
93
        // validating user http verb input + converting `get` data to query parameter
94
        switch ($verb) {
95
            case 'get':
96
                $url = $this->dataArrayToQueryParam($data, $url);
97
                break;
98
            case 'post':
99
            case 'put':
100
            case 'patch':
101
            case 'delete':
102
                break;
103
            default:
104
                throw new UndefinedMethodException('Unsupported HTTP Verb (' . $verb . ')!');
105
        }
106
107
        $httpResponse = $this->json($verb, $url, $data, $headers);
0 ignored issues
show
It seems like json() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
108
109
        return $this->setResponseObjectAndContent($httpResponse);
110
    }
111
112
    /**
113
     * @param $httpResponse
114
     *
115
     * @return  \Illuminate\Foundation\Testing\TestResponse
116
     */
117
    public function setResponseObjectAndContent($httpResponse)
118
    {
119
        $this->setResponseContent($httpResponse);
120
121
        return $this->response = $httpResponse;
122
    }
123
124
    /**
125
     * @param $httpResponse
126
     *
127
     * @return  mixed
128
     */
129
    public function setResponseContent($httpResponse)
130
    {
131
        return $this->responseContent = $httpResponse->getContent();
132
    }
133
134
    /**
135
     * @return  string
136
     */
137
    public function getResponseContent()
138
    {
139
        return $this->responseContent;
140
    }
141
142
    /**
143
     * @return  mixed
144
     */
145
    public function getResponseContentArray()
146
    {
147
        return $this->responseContentArray ? : $this->responseContentArray = json_decode($this->getResponseContent(),
148
            true);
149
    }
150
151
    /**
152
     * @return  mixed
153
     */
154
    public function getResponseContentObject()
155
    {
156
        return $this->responseContentObject ? : $this->responseContentObject = json_decode($this->getResponseContent(),
157
            false);
158
    }
159
160
    /**
161
     * Inject the ID in the Endpoint URI before making the call by
162
     * overriding the `$this->endpoint` property
163
     *
164
     * Example: you give it ('users/{id}/stores', 100) it returns 'users/100/stores'
165
     *
166
     * @param        $id
167
     * @param bool   $skipEncoding
168
     * @param string $replace
169
     *
170
     * @return  $this
171
     */
172
    public function injectId($id, $skipEncoding = false, $replace = '{id}')
173
    {
174
        // In case Hash ID is enabled it will encode the ID first
175
        $id = $this->hashEndpointId($id, $skipEncoding);
176
        $this->endpoint = str_replace($replace, $id, $this->endpoint);
177
178
        return $this;
179
    }
180
181
    /**
182
     * Override the default class endpoint property before making the call
183
     *
184
     * to be used as follow: $this->endpoint('[email protected]')->makeCall($data);
185
     *
186
     * @param $endpoint
187
     *
188
     * @return  $this
189
     */
190
    public function endpoint($endpoint)
191
    {
192
        $this->overrideEndpoint = $endpoint;
193
194
        return $this;
195
    }
196
197
    /**
198
     * @return  string
199
     */
200
    public function getEndpoint()
201
    {
202
        return !is_null($this->overrideEndpoint) ? $this->overrideEndpoint : $this->endpoint;
203
    }
204
205
    /**
206
     * Override the default class auth property before making the call
207
     *
208
     * to be used as follow: $this->auth('false')->makeCall($data);
209
     *
210
     * @param bool $auth
211
     *
212
     * @return  $this
213
     */
214
    public function auth(bool $auth)
215
    {
216
        $this->overrideAuth = $auth;
0 ignored issues
show
Documentation Bug introduced by Mahmoud Zalt
The property $overrideAuth was declared of type string, but $auth is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
217
218
        return $this;
219
    }
220
221
    /**
222
     * @return  bool
223
     */
224
    public function getAuth()
225
    {
226
        return !is_null($this->overrideAuth) ? $this->overrideAuth : $this->auth;
227
    }
228
229
    /**
230
     * @param $uri
231
     *
232
     * @return  string
233
     */
234
    private function buildUrlForUri($uri)
235
    {
236
        // add `/` at the beginning in case it doesn't exist
237
        if (!Str::startsWith($uri, '/')) {
238
            $uri = '/' . $uri;
239
        }
240
241
        return Config::get('apiato.api.url') . $uri;
242
    }
243
244
    /**
245
     * Attach Authorization Bearer Token to the request headers
246
     * if it does not exist already and the authentication is required
247
     * for the endpoint `$this->auth = true`.
248
     *
249
     * @param $headers
250
     *
251
     * @return  mixed
252
     */
253
    private function injectAccessToken(array $headers = [])
254
    {
255
        // if endpoint is protected (requires token to access it's functionality)
256
        if ($this->getAuth() && !$this->headersContainAuthorization($headers)) {
257
            // append the token to the header
258
            $headers['Authorization'] = 'Bearer ' . $this->getTestingUser()->token;
0 ignored issues
show
It seems like getTestingUser() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
259
        }
260
261
        return $headers;
262
    }
263
264
    /**
265
     * just check if headers array has an `Authorization` as key.
266
     *
267
     * @param $headers
268
     *
269
     * @return  bool
270
     */
271
    private function headersContainAuthorization($headers)
272
    {
273
        return Arr::has($headers, 'Authorization');
274
    }
275
276
    /**
277
     * @param $data
278
     * @param $url
279
     *
280
     * @return  string
281
     */
282
    private function dataArrayToQueryParam($data, $url)
283
    {
284
        return $data ? $url . '?' . http_build_query($data) : $url;
285
    }
286
287
    /**
288
     * @param $text
289
     *
290
     * @return  string
291
     */
292
    private function getJsonVerb($text)
293
    {
294
        return Str::replaceFirst('json:', '', $text);
295
    }
296
297
298
    /**
299
     * @param      $id
300
     * @param bool $skipEncoding
301
     *
302
     * @return  mixed
303
     */
304
    private function hashEndpointId($id, $skipEncoding = false)
305
    {
306
        return (Config::get('apiato.hash-id') && !$skipEncoding) ? Hashids::encode($id) : $id;
307
    }
308
309
    /**
310
     * read `$this->endpoint` property from the test class (`[email protected]`) and convert it to usable data
311
     *
312
     * @return  array
313
     */
314
    private function parseEndpoint()
315
    {
316
        $this->validateEndpointExist();
317
318
        $separator = '@';
319
320
        $this->validateEndpointFormat($separator);
321
322
        // convert the string to array
323
        $asArray = explode($separator, $this->getEndpoint(), 2);
324
325
        // get the verb and uri values from the array
326
        extract(array_combine(['verb', 'uri'], $asArray));
0 ignored issues
show
array_combine(array('verb', 'uri'), $asArray) cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
327
        /** @var TYPE_NAME $verb */
328
        /** @var TYPE_NAME $uri */
329
330
        return [
331
            'verb' => $verb,
332
            'uri'  => $uri,
333
            'url'  => $this->buildUrlForUri($uri),
334
        ];
335
    }
336
337
    /**
338
     * @void
339
     */
340
    private function validateEndpointExist()
341
    {
342
        if (!$this->getEndpoint()) {
343
            throw new MissingTestEndpointException();
344
        }
345
    }
346
347
    /**
348
     * @param $separator
349
     *
350
     * @throws WrongEndpointFormatException
351
     */
352
    private function validateEndpointFormat($separator)
353
    {
354
        // check if string contains the separator
355
        if (!strpos($this->getEndpoint(), $separator)) {
356
            throw new WrongEndpointFormatException();
357
        }
358
    }
359
360
    /**
361
     * Transform headers array to array of $_SERVER vars with HTTP_* format.
362
     *
363
     * @param  array $headers
364
     *
365
     * @return array
366
     */
367
    protected function transformHeadersToServerVars(array $headers)
368
    {
369
        return collect($headers)->mapWithKeys(function ($value, $name) {
370
            $name = strtr(strtoupper($name), '-', '_');
371
372
            return [$this->formatServerHeaderKey($name) => $value];
0 ignored issues
show
It seems like formatServerHeaderKey() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
373
        })->all();
374
    }
375
376
}
377