Issues (10)

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.

tests/services/ApiAuthServiceTest.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
namespace Craft;
4
5
use \PHPUnit_Framework_MockObject_MockObject as mock;
6
7
/**
8
 * @author    Nerds & Company
9
 * @copyright Copyright (c) 2015, Nerds & Company
10
 * @license   MIT
11
 *
12
 * @link      http://www.nerds.company
13
 *
14
 * @coversDefaultClass Craft\ApiAuthService
15
 * @covers ::<!public>
16
 */
17
class ApiAuthServiceTest extends BaseTest
18
{
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public static function setUpBeforeClass()
23
    {
24
        parent::setUpBeforeClass();
25
        //Plugin classes
26
        require_once __DIR__ . '/../../services/ApiAuthService.php';
27
        require_once __DIR__ . '/../../models/ApiAuth_UserKeyModel.php';
28
        require_once __DIR__ . '/../../records/ApiAuth_UserKeyRecord.php';
29
    }
30
31
    //==============================================================================================================
32
    //=================================================  TESTS  ====================================================
33
    //==============================================================================================================
34
35
    /**
36
     * @covers ::generateKey
37
     */
38
    public function testGenerateKeyShouldReturnRandomKey()
39
    {
40
        $service = new ApiAuthService();
41
        $token1 = $service->generateKey();
42
        $token2 = $service->generateKey();
43
44
        $this->assertNotSame($token1, $token2);
45
    }
46
47
    /**
48
     * @covers ::authenticateKey
49
     * @dataProvider provideInvalidUserKeyModelAttributes
50
     *
51
     * @param string $key
52
     * @param int $userId
53
     * @param DateTime $expires
54
     */
55
    public function testAuthenticateKeyShouldReturnFalseWhenKeyExpired($key, $userId, DateTime $expires)
56
    {
57
        $mockUserKeyModel = $this->getMockUserKeyModel();
58
        $mockUserKeyModel->expects($this->exactly(1))
59
            ->method('__get')
60
            ->willReturnMap(array(
61
                array('expires', $expires),
62
            ));
63
64
        $service = $this->setMockApiAuthService('getUserKeyModelByKey', $key, $mockUserKeyModel);
65
66
        $result = $service->authenticateKey($key);
67
        $this->assertFalse($result);
68
    }
69
70
    /**
71
     * @covers ::authenticateKey
72
     * @dataProvider provideValidUserKeyModelAttributes
73
     *
74
     * @param string $key
75
     */
76
    public function testAuthenticateKeyShouldReturnFalseWhenKeyNotFound($key)
77
    {
78
        $service = $this->setMockApiAuthService('getUserKeyModelByKey', $key);
79
80
        $result = $service->authenticateKey($key);
81
        $this->assertFalse($result);
82
    }
83
84
    /**
85
     * @covers ::authenticateKey
86
     * @dataProvider provideValidUserKeyModelAttributes
87
     *
88
     * @param string $key
89
     * @param int $userId
90
     * @param DateTime $expires
91
     */
92
    public function testAuthenticateKeyShouldLoginUserWhenKeyValid($key, $userId, DateTime $expires)
93
    {
94
        $mockUserKeyModel = $this->getMockUserKeyModel();
95
        $mockUserKeyModel->expects($this->exactly(2))
96
            ->method('__get')
97
            ->willReturnMap(array(
98
                array('expires', $expires),
99
                array('userId', $userId)
100
            ));
101
102
        $this->setMockUserSessionService($userId);
103
104
        $service = $this->setMockApiAuthService('getUserKeyModelByKey', $key, $mockUserKeyModel);
105
106
        $result = $service->authenticateKey($key);
107
        $this->assertTrue($result);
108
    }
109
110
    /**
111
     * @covers ::saveKey
112
     * @dataProvider provideValidUserKeyModelAttributes
113
     *
114
     * @param string $key
115
     * @param int $userId
116
     */
117 View Code Duplication
    public function testSaveKeyShouldReturnTrueWhenSavingSucceeds($key, $userId)
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...
118
    {
119
        $mockUser = $this->getMockUser($userId);
120
        $mockUserKeyModel = $this->setMockUserKeyModelSaveExpectation(true);
121
        $service = $this->setMockApiAuthService('getNewUserKeyModel', 'skip', $mockUserKeyModel);
122
123
        $result = $service->saveKey($mockUser, $key);
124
125
        $this->assertTrue($result);
126
    }
127
128
    /**
129
     * @covers ::saveKey
130
     * @dataProvider provideInvalidUserKeyModelAttributes
131
     *
132
     * @param string $key
133
     * @param int $userId
134
     */
135 View Code Duplication
    public function testSaveKeyShouldReturnFalseWhenSavingFails($key, $userId)
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...
136
    {
137
        $mockUser = $this->getMockUser($userId);
138
        $mockUserKeyModel = $this->setMockUserKeyModelSaveExpectation(false);
139
        $service = $this->setMockApiAuthService('getNewUserKeyModel', 'skip', $mockUserKeyModel);
140
141
        $result = $service->saveKey($mockUser, $key);
142
143
        $this->assertFalse($result);
144
    }
145
146
    /**
147
     * @covers ::isOptionsRequest
148
     */
149
    public function testIsOptionsRequestShouldReturnFalseByDefault()
150
    {
151
        $service = new ApiAuthService();
152
153
        $result = $service->isOptionsRequest();
154
155
        $this->assertFalse($result);
156
    }
157
158
    /**
159
     * @covers ::isOptionsRequest
160
     */
161
    public function testIsOptionsRequestShouldReturnTrueWhenOptionsRequest()
162
    {
163
        $_SERVER['REQUEST_METHOD'] = 'OPTIONS';
164
165
        $service = new ApiAuthService();
166
167
        $result = $service->isOptionsRequest();
168
169
        $this->assertTrue($result);
170
    }
171
172
    /**
173
     * @covers ::setCorsHeaders
174
     */
175
    public function testSetCorsHeaderShouldSetCorsHeaders()
176
    {
177
        /** @var ApiAuthService|mock $service */
178
        $service = $this->getMock('Craft\ApiAuthService', array('setHeader'));
179
180
        $service->expects($this->exactly(2))
181
            ->method('setHeader')
182
            ->withConsecutive(
183
                array('Access-Control-Allow-Headers', 'Authorization'),
184
                array('Access-Control-Allow-Origin', '*')
185
            );
186
187
        $service->setCorsHeaders();
188
    }
189
190
    //==============================================================================================================
191
    //==============================================  PROVIDERS  ===================================================
192
    //==============================================================================================================
193
194
    /**
195
     * @return array
196
     */
197
    public function provideValidUserKeyModelAttributes()
198
    {
199
        return array(
200
            'valid key' => array(
201
                'key' => 'test123',
202
                'userId' => 1,
203
                'expires' => new DateTime('+ 1 minute'),
204
            )
205
        );
206
    }
207
208
    /**
209
     * @return array
210
     */
211
    public function provideInvalidUserKeyModelAttributes()
212
    {
213
        return array(
214
            'invalid key' => array(
215
                'key' => 'anotherkey',
216
                'userId' => 2,
217
                'expires' => new DateTime('- 1 minute'),
218
            )
219
        );
220
    }
221
222
    //==============================================================================================================
223
    //=================================================  MOCKS  ====================================================
224
    //==============================================================================================================
225
226
    /**
227
     * @param int $userId
228
     * @param bool $success
229
     * @return UserSessionService|mock
230
     */
231 View Code Duplication
    private function setMockUserSessionService($userId, $success = true)
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...
232
    {
233
        $mockUserSessionService = $this->getMockBuilder('Craft\UserSessionService')
234
            ->disableOriginalConstructor()
235
            ->getMock();
236
237
        $mockUserSessionService->expects($this->exactly(1))
238
            ->method('loginByUserId')
239
            ->with($userId)
240
            ->willReturn($success);
241
242
        $this->setComponent(craft(), 'userSession', $mockUserSessionService);
243
244
        return $mockUserSessionService;
245
    }
246
247
    /**
248
     * @return ApiAuth_UserKeyModel|mock
249
     */
250
    private function getMockUserKeyModel()
251
    {
252
        $mockUserKeyModel = $this->getMockBuilder('Craft\ApiAuth_UserKeyModel')
253
            ->disableOriginalConstructor()
254
            ->getMock();
255
256
        return $mockUserKeyModel;
257
    }
258
259
    /**
260
     * @param int $userId
261
     * @return UserModel|mock
262
     */
263
    private function getMockUser($userId)
264
    {
265
        $mockUser = $this->getMockBuilder('Craft\UserModel')
266
            ->disableOriginalConstructor()
267
            ->getMock();
268
269
        $mockUser->expects($this->exactly(1))
270
            ->method('getAttribute')
271
            ->with('id')
272
            ->willReturn($userId);
273
274
        return $mockUser;
275
    }
276
277
    /**
278
     * @param array $methodName
279
     * @param mixed $param
280
     * @param ApiAuth_UserKeyModel $mockUserKeyModel
281
     * @return ApiAuthService|mock
282
     */
283
    private function setMockApiAuthService($methodName, $param, ApiAuth_UserKeyModel $mockUserKeyModel = null)
284
    {
285
        $service = $this->getMock('Craft\ApiAuthService', array($methodName));
286
287
        $method = $service->expects($this->exactly(1))->method($methodName);
288
        if ($param !== 'skip') {
289
            $method->with($param);
290
        }
291
        $method->willReturn($mockUserKeyModel);
292
293
        return $service;
294
    }
295
296
    /**
297
     * @param $success
298
     * @return ApiAuth_UserKeyModel|mock
299
     */
300
    private function setMockUserKeyModelSaveExpectation($success)
301
    {
302
        $mockUserKeyModel = $this->getMockUserKeyModel();
303
        $mockUserKeyModel->expects($this->exactly(1))
304
            ->method('save')
305
            ->willReturn($success);
306
        return $mockUserKeyModel;
307
    }
308
}
309