Completed
Push — master ( f48619...b2e6ed )
by Conrad
03:17 queued 01:58
created

GraphqlTest::setUp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 0
dl 0
loc 19
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
namespace AdvancedLearning\Oauth2Server\Tests;
4
5
use AdvancedLearning\Oauth2Server\Models\Client;
0 ignored issues
show
Bug introduced by
The type AdvancedLearning\Oauth2Server\Models\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use AdvancedLearning\Oauth2Server\Repositories\AccessTokenRepository;
0 ignored issues
show
Bug introduced by
The type AdvancedLearning\Oauth2S...s\AccessTokenRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use AdvancedLearning\Oauth2Server\Repositories\ClientRepository;
0 ignored issues
show
Bug introduced by
The type AdvancedLearning\Oauth2S...tories\ClientRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use AdvancedLearning\Oauth2Server\Repositories\RefreshTokenRepository;
0 ignored issues
show
Bug introduced by
The type AdvancedLearning\Oauth2S...\RefreshTokenRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use AdvancedLearning\Oauth2Server\Repositories\ScopeRepository;
0 ignored issues
show
Bug introduced by
The type AdvancedLearning\Oauth2S...itories\ScopeRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use AdvancedLearning\Oauth2Server\Repositories\UserRepository;
0 ignored issues
show
Bug introduced by
The type AdvancedLearning\Oauth2S...sitories\UserRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use GraphQL\Type\Definition\ObjectType;
0 ignored issues
show
Bug introduced by
The type GraphQL\Type\Definition\ObjectType was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use GraphQL\Type\Definition\Type;
0 ignored issues
show
Bug introduced by
The type GraphQL\Type\Definition\Type was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
13
use GuzzleHttp\Psr7\Response;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Psr7\Response was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use GuzzleHttp\Psr7\ServerRequest;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Psr7\ServerRequest was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use Lcobucci\JWT\Parser;
0 ignored issues
show
Bug introduced by
The type Lcobucci\JWT\Parser was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use League\OAuth2\Server\AuthorizationServer;
0 ignored issues
show
Bug introduced by
The type League\OAuth2\Server\AuthorizationServer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
17
use League\OAuth2\Server\CryptTrait;
0 ignored issues
show
Bug introduced by
The type League\OAuth2\Server\CryptTrait was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use League\OAuth2\Server\Grant\ClientCredentialsGrant;
0 ignored issues
show
Bug introduced by
The type League\OAuth2\Server\Grant\ClientCredentialsGrant was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
use League\OAuth2\Server\Grant\PasswordGrant;
0 ignored issues
show
Bug introduced by
The type League\OAuth2\Server\Grant\PasswordGrant was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use Riddler7\Oauth2GraphQL\Controller;
21
use Riddler7\Oauth2GraphQL\Tests\BlankMutation;
22
use Riddler7\Oauth2GraphQL\Tests\BlankQuery;
23
use Riddler7\Oauth2GraphQL\Tests\BlankType;
24
use SilverStripe\Control\HTTPRequest;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Control\HTTPRequest was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
25
use SilverStripe\Core\Config\Config;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Core\Config\Config was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
use SilverStripe\Core\Environment;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Core\Environment was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use SilverStripe\GraphQL\Manager;
0 ignored issues
show
Bug introduced by
The type SilverStripe\GraphQL\Manager was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
use SilverStripe\Dev\SapphireTest;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Dev\SapphireTest was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
29
use SilverStripe\Security\Member;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Security\Member was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
use SilverStripe\Security\Security;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Security\Security was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
use function file_get_contents;
32
use function file_put_contents;
33
use function sys_get_temp_dir;
34
35
class GraphqlTest extends SapphireTest
36
{
37
    use CryptTrait;
38
39
    protected static $fixture_file = 'tests/OAuthFixture.yml';
40
41
    protected static $privateKeyFile = 'private.key';
42
43
    protected static $publicKeyFile = 'public.key';
44
45
    /**
46
     * Setup test environment.
47
     */
48
    public function setUp()
49
    {
50
        parent::setUp();
51
52
        // copy private key so we can set correct permissions, file gets removed when tests finish
53
        $path = $this->getPrivateKeyPath();
54
        file_put_contents($path, file_get_contents(__DIR__ . '/' . self::$privateKeyFile));
55
        chmod($path, 0660);
56
        Environment::setEnv('OAUTH_PRIVATE_KEY_PATH', $path);
57
58
        // copy public key
59
        $path = $this->getPublicKeyPath();
60
        file_put_contents($path, file_get_contents(__DIR__ . '/' . self::$publicKeyFile));
61
        chmod($path, 0660);
62
        Environment::setEnv('OAUTH_PUBLIC_KEY_PATH', $path);
63
64
        Security::force_database_is_ready(true);
65
66
        $this->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');
67
    }
68
69
    public function testGraphQLMember()
70
    {
71
        $userRepository = new UserRepository();
72
        $refreshRepository = new RefreshTokenRepository();
73
74
        $server = $this->getAuthorisationServer();
75
        $server->enableGrantType(
76
            new PasswordGrant($userRepository, $refreshRepository),
77
            new \DateInterval('PT1H')
78
        );
79
80
        $client = $this->objFromFixture(Client::class, 'webapp');
81
        $member = $this->objFromFixture(Member::class, 'member1');
82
83
        $request = (new ServerRequest(
84
            'POST',
85
            '',
86
            ['Content-Type' => 'application/json']
87
        ))->withParsedBody([
88
            'grant_type' => 'password',
89
            'client_id' => $client->Identifier,
90
            'client_secret' => $client->Secret,
91
            'scope' => 'members',
92
            'username' => $member->Email,
93
            'password' => 'password1'
94
        ]);
95
96
        $response = new Response();
97
        $response = $server->respondToAccessTokenRequest($request, $response);
98
99
        $data = json_decode((string)$response->getBody(), true);
100
        $token = $data['access_token'];
101
102
        // check for fn/ln
103
        $decoded = (new Parser())->parse($token);
104
105
        $this->assertEquals('My', $decoded->getClaim('fn'), 'First name should be correctly set');
106
        $this->assertEquals('Test', $decoded->getClaim('ln'), 'Last name should be correctly set');
107
108
        // create request
109
        $request = new HTTPRequest('GET', '/');
110
        $request->addHeader('authorization', 'Bearer ' . $token);
111
        // fake server port
112
        $_SERVER['SERVER_PORT'] = 443;
113
114
        $authMember = (new \Riddler7\Oauth2GraphQL\Authenticator())->authenticate($request);
115
116
        $this->assertEquals($member->ID, $authMember->ID, 'Member should exist in DB');
117
    }
118
119
    public function testGraphQLContexts()
120
    {
121
        $userRepository = new UserRepository();
122
        $refreshRepository = new RefreshTokenRepository();
123
124
        $server = $this->getAuthorisationServer();
125
        $server->enableGrantType(
126
            new PasswordGrant($userRepository, $refreshRepository),
127
            new \DateInterval('PT1H')
128
        );
129
130
        $client = $this->objFromFixture(Client::class, 'webapp');
131
        $member = $this->objFromFixture(Member::class, 'member1');
132
133
        $request = (new ServerRequest(
134
            'POST',
135
            '',
136
            ['Content-Type' => 'application/json']
137
        ))->withParsedBody([
138
            'grant_type' => 'password',
139
            'client_id' => $client->Identifier,
140
            'client_secret' => $client->Secret,
141
            'scope' => 'members',
142
            'username' => $member->Email,
143
            'password' => 'password1'
144
        ]);
145
146
        $response = new Response();
147
        $response = $server->respondToAccessTokenRequest($request, $response);
148
149
        $data = json_decode((string)$response->getBody(), true);
150
        $token = $data['access_token'];
151
152
        // create request
153
        $request = new HTTPRequest('GET', '/grqphql');
154
        $request->addHeader('authorization', 'Bearer ' . $token);
155
        // fake server port
156
        $_SERVER['SERVER_PORT'] = 443;
157
158
        // var to store context
159
        $context = [];
160
161
        // setup blank schema
162
        Config::modify()->set(Manager::class, 'schemas', [
163
            'myschema' => [
164
                'types' => [
165
                    'Blank' => BlankType::class
166
                ],
167
                'queries' => [
168
                    'BlankQuery' => BlankQuery::class
169
                ],
170
                'mutations' => [
171
                    'BlankMutation' => BlankMutation::class
172
                ]
173
            ]
174
        ]);
175
176
        $manager = new Manager('myschema');
177
178
        // extract the context
179
        $manager->addMiddleware(new GraphQLSchemaExtractor(function($currentContext) use (&$context) {
180
            $context = $currentContext;
181
        }));
182
183
        $controller = new Controller($manager);
184
        $response = $controller->index($request);
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
185
186
        $this->assertEquals($client->Identifier, $context['oauthClientIdentifier']);
187
        $this->assertEquals(1, count($context['oauthScopes']));
188
        $this->assertEquals('members', $context['oauthScopes'][0]);
189
    }
190
191
    /**
192
     * Setup the Authorization Server.
193
     *
194
     * @return AuthorizationServer
195
     */
196
    protected function getAuthorisationServer()
197
    {
198
        // Init our repositories
199
        $clientRepository = new ClientRepository(); // instance of ClientRepositoryInterface
200
        $scopeRepository = new ScopeRepository(); // instance of ScopeRepositoryInterface
201
        $accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface
202
203
        // Path to public and private keys
204
        $privateKey = $this->getPrivateKeyPath();
205
        $encryptionKey = $this->encryptionKey;
206
207
        // Setup the authorization server
208
        $server = new AuthorizationServer(
209
            $clientRepository,
210
            $accessTokenRepository,
211
            $scopeRepository,
212
            $privateKey,
213
            $encryptionKey
214
        );
215
216
        return $server;
217
    }
218
219
    /**
220
     * Get the resource server.
221
     *
222
     * @return \League\OAuth2\Server\ResourceServer
223
     */
224
    protected function getResourceServer()
225
    {
226
        // Init our repositories
227
        $accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface
228
229
        // Path to authorization server's public key
230
        $publicKeyPath = $this->getPublicKeyPath();
231
232
        // Setup the authorization server
233
        $server = new \League\OAuth2\Server\ResourceServer(
0 ignored issues
show
Bug introduced by
The type League\OAuth2\Server\ResourceServer was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
234
            $accessTokenRepository,
235
            $publicKeyPath
236
        );
237
238
        return $server;
239
    }
240
241
    /**
242
     * Get the full path the private key.
243
     *
244
     * @return string
245
     */
246
    protected function getPrivateKeyPath()
247
    {
248
        return sys_get_temp_dir() . '/' . self::$privateKeyFile;
249
    }
250
251
    /**
252
     * Get the full path the public key.
253
     *
254
     * @return string
255
     */
256
    protected function getPublicKeyPath()
257
    {
258
        return sys_get_temp_dir() . '/' . self::$publicKeyFile;
259
    }
260
261
    /**
262
     * Cleanup test environment.
263
     */
264
    protected function tearDown()
265
    {
266
        parent::tearDown();
267
        // remove private key after tests have finished
268
        unlink($this->getPrivateKeyPath());
269
        // remove public key after tests have finished
270
        unlink($this->getPublicKeyPath());
271
    }
272
273
    /**
274
     * Generates a response with an access token using the client grant.
275
     *
276
     * @return \Psr\Http\Message\ResponseInterface
0 ignored issues
show
Bug introduced by
The type Psr\Http\Message\ResponseInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
277
     */
278
    protected function generateClientAccessToken()
279
    {
280
        $server = $this->getAuthorisationServer();
281
        // Enable the client credentials grant on the server
282
        $server->enableGrantType(
283
            new ClientCredentialsGrant(),
284
            new \DateInterval('PT1H') // access tokens will expire after 1 hour
285
        );
286
287
        $client = $this->objFromFixture(Client::class, 'webapp');
288
289
        $request = $this->getClientRequest($client);
290
291
        $response = new Response();
292
        return $server->respondToAccessTokenRequest($request, $response);
293
    }
294
295
    /**
296
     * Get PSR7 request object to be used for a client grant.
297
     *
298
     * @param Client $client
299
     *
300
     * @return ServerRequest
301
     */
302
    protected function getClientRequest(Client $client)
303
    {
304
        // setup server vars
305
        $_SERVER['SERVER_PORT'] = 80;
306
        $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
307
308
        return (new ServerRequest(
309
            'POST',
310
            '',
311
            ['Content-Type' => 'application/json']
312
        ))->withParsedBody([
313
            'grant_type' => 'client_credentials',
314
            'client_id' => $client->Identifier,
315
            'client_secret' => $client->Secret,
316
            'scope' => 'members'
317
        ]);
318
    }
319
320
}
321