Passed
Push — master ( 34eaf6...149dd5 )
by Charles
02:52
created

testV2EncryptedRequestAndResponse()   B

Complexity

Conditions 6
Paths 2

Size

Total Lines 62
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 42
dl 0
loc 62
rs 8.6257
c 0
b 0
f 0
cc 6
nc 2
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php declare(strict_types=1);
2
3
namespace ncryptf\Tests;
4
5
use DateTime;
6
use ncryptf\Token;
7
use ncryptf\Request;
8
use ncryptf\Response;
9
use ncryptf\Authorization;
10
use Middlewares\Utils\Factory;
11
use WildWolf\Psr16MemoryCache;
12
use ncryptf\Tests\AbstractTest;
13
use PHPUnit\Framework\TestCase;
14
15
use Middlewares\Utils\Dispatcher;
16
use ncryptf\Tests\mock\EchoResponse;
17
use ncryptf\middleware\RequestParser;
18
use ncryptf\Tests\mock\EncryptionKey;
19
use ncryptf\Tests\mock\Authentication;
20
use Psr\Http\Message\ResponseInterface;
21
use Psr\Http\Server\MiddlewareInterface;
22
use ncryptf\middleware\ResponseFormatter;
23
use Zend\Diactoros\Response\JsonResponse;
24
use Psr\Http\Message\ServerRequestInterface;
25
26
use Psr\Http\Server\RequestHandlerInterface;
27
use Lcobucci\ContentNegotiation\Formatter\Json;
0 ignored issues
show
Bug introduced by
The type Lcobucci\ContentNegotiation\Formatter\Json 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 Lcobucci\ContentNegotiation\Formatter\StringCast;
0 ignored issues
show
Bug introduced by
The type Lcobucci\ContentNegotiation\Formatter\StringCast 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
30
final class AuthenticationTest extends AbstractTest
31
{
32
    public function testSuccessfulLogin()
33
    {
34
        foreach ($this->testCases as $k => $params) {
35
            $auth = new Authorization($params[0], $params[1], $this->token, new DateTime, $params[2]);
36
            $response = Dispatcher::run(
37
                [
38
                    new Authentication,
39
                    function ($request, $next) {
40
                        $this->assertInstanceOf('\ncryptf\Token', $request->getAttribute('ncryptf-token'));
41
                        $this->assertEquals(true, \is_array($request->getAttribute('ncryptf-user')));
42
                        return $next->handle($request);
43
                    }
44
                ],
45
                Factory::createServerRequest($params[0], $params[1])
46
                    ->withHeader('Authorization', $auth->getHeader())
47
                    ->withHeader('Content-Type', 'application/json')
48
                    ->withHeader('Accept', 'application/json')
49
                    ->withBody((function () use ($params) {
50
                        $stream = fopen('php://memory', 'r+');
51
                        fwrite($stream, \is_array($params[2]) ? \json_encode($params[2]): $params[2]);
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

51
                        fwrite(/** @scrutinizer ignore-type */ $stream, \is_array($params[2]) ? \json_encode($params[2]): $params[2]);
Loading history...
52
                        rewind($stream);
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of rewind() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

52
                        rewind(/** @scrutinizer ignore-type */ $stream);
Loading history...
53
                        return new \Zend\Diactoros\Stream($stream);
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $stream of Zend\Diactoros\Stream::__construct() does only seem to accept resource|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

53
                        return new \Zend\Diactoros\Stream(/** @scrutinizer ignore-type */ $stream);
Loading history...
54
                    })())
55
            );
56
57
            $this->assertSame(200, $response->getStatusCode());
58
        }
59
    }
60
61
    public function testV2EncryptedRequestAndResponse()
62
    {
63
        foreach ($this->testCases as $k => $params) {
64
            $serverKey = EncryptionKey::generate();
65
            $myKey = EncryptionKey::generate();
66
            $cache = Psr16MemoryCache::instance();
67
            $cache->set($serverKey->getHashIdentifier(), $serverKey);
68
69
            $auth = new Authorization($params[0], $params[1], $this->token, new DateTime, $params[2]);
70
            $token = $this->token;
71
72
            $response = Dispatcher::run(
73
                [
74
                    new RequestParser($cache),
75
                    new Authentication,
76
                    function ($request, $next) use ($params) {
0 ignored issues
show
Unused Code introduced by
The import $params is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
77
                        $this->assertInstanceOf('\ncryptf\Token', $request->getAttribute('ncryptf-token'));
78
                        $this->assertEquals(true, \is_array($request->getAttribute('ncryptf-user')));
79
                        return $next->handle($request);
80
                    },
81
                    new ResponseFormatter(new EncryptionKey),
82
                    new EchoResponse,
83
                ],
84
                Factory::createServerRequest($params[0], $params[1])
85
                    ->withHeader('Authorization', $auth->getHeader())
86
                    ->withHeader('Content-Type', 'application/vnd.ncryptf+json')
87
                    ->withHeader('Accept', 'application/vnd.ncryptf+json')
88
                    ->withHeader('X-HashId', $serverKey->getHashIdentifier())
89
                    ->withHeader('X-PubKey', \base64_encode($myKey->getBoxPublicKey()))
90
                    ->withBody((function () use ($params, $serverKey, $myKey, $token) {
91
                        $data = \is_array($params[2]) ? \json_encode($params[2]): $params[2];
92
 
93
                        if (!empty($params[2])) {
94
                            $request = new Request(
95
                                $myKey->getBoxSecretKey(),
96
                                $token->signature
97
                            );
98
99
                            $encryptedData = $request->encrypt(
100
                                $data,
101
                                $serverKey->getBoxPublicKey()
102
                            );
103
                        }
104
                        $stream = fopen('php://memory', 'r+');
105
                        fwrite($stream, empty($params[2]) ? '' : \base64_encode($encryptedData));
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

105
                        fwrite(/** @scrutinizer ignore-type */ $stream, empty($params[2]) ? '' : \base64_encode($encryptedData));
Loading history...
Comprehensibility Best Practice introduced by
The variable $encryptedData does not seem to be defined for all execution paths leading up to this point.
Loading history...
106
                        rewind($stream);
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of rewind() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

106
                        rewind(/** @scrutinizer ignore-type */ $stream);
Loading history...
107
                        return new \Zend\Diactoros\Stream($stream);
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $stream of Zend\Diactoros\Stream::__construct() does only seem to accept resource|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

107
                        return new \Zend\Diactoros\Stream(/** @scrutinizer ignore-type */ $stream);
Loading history...
108
                    })())
109
            );
110
111
            $this->assertSame('application/vnd.ncryptf+json', $response->getHeaderLine('Content-Type'));
112
            $this->assertTrue($response->hasHeader('x-hashid'));
113
114
            $r = new Response(
115
                $myKey->getBoxSecretKey()
116
            );
117
118
            $plaintext = $r->decrypt(
119
                \base64_decode((string)$response->getBody())
120
            );
121
122
            $this->assertEquals(\is_array($params[2]) ? \json_encode($params[2]) : $params[2], $plaintext);
123
        }
124
    }
125
126
    public function testV1EncryptedRequestAndResponse()
127
    {
128
        foreach ($this->testCases as $k => $params) {
129
            $serverKey = EncryptionKey::generate();
130
            $myKey = EncryptionKey::generate();
131
            $nonce = \random_bytes(24);
132
            $cache = Psr16MemoryCache::instance();
133
            $cache->set($serverKey->getHashIdentifier(), $serverKey);
134
135
            $auth = new Authorization($params[0], $params[1], $this->token, new DateTime, $params[2]);
136
            $token = $this->token;
137
            $response = Dispatcher::run(
138
                [
139
                    new RequestParser($cache),
140
                    new Authentication,
141
                    function ($request, $next) {
142
                        $this->assertInstanceOf('\ncryptf\Token', $request->getAttribute('ncryptf-token'));
143
                        $this->assertEquals(true, \is_array($request->getAttribute('ncryptf-user')));
144
                        return $next->handle($request);
145
                    },
146
                    new ResponseFormatter(new EncryptionKey),
147
                    new EchoResponse,
148
                ],
149
                Factory::createServerRequest($params[0], $params[1])
150
                    ->withHeader('Authorization', $auth->getHeader())
151
                    ->withHeader('Content-Type', 'application/vnd.25519+json')
152
                    ->withHeader('Accept', 'application/vnd.25519+json')
153
                    ->withHeader('X-HashId', $serverKey->getHashIdentifier())
154
                    ->withHeader('X-Nonce', \base64_encode($nonce))
155
                    ->withHeader('X-PubKey', \base64_encode($myKey->getBoxPublicKey()))
156
                    ->withBody((function () use ($params, $serverKey, $myKey, $nonce, $token) {
157
                        $data = \is_array($params[2]) ? \json_encode($params[2]): $params[2];
158
159
                        $request = new Request(
160
                            $myKey->getBoxSecretKey(),
161
                            $token->signature
162
                        );
163
164
                        $encryptedData = $request->encrypt(
165
                            $data,
166
                            $serverKey->getBoxPublicKey(),
167
                            1,
168
                            $nonce
169
                        );
170
                        $stream = fopen('php://memory', 'r+');
171
                        fwrite($stream, $data === '' ? '' : \base64_encode($encryptedData));
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

171
                        fwrite(/** @scrutinizer ignore-type */ $stream, $data === '' ? '' : \base64_encode($encryptedData));
Loading history...
172
                        rewind($stream);
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $handle of rewind() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

172
                        rewind(/** @scrutinizer ignore-type */ $stream);
Loading history...
173
                        return new \Zend\Diactoros\Stream($stream);
0 ignored issues
show
Bug introduced by
It seems like $stream can also be of type false; however, parameter $stream of Zend\Diactoros\Stream::__construct() does only seem to accept resource|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

173
                        return new \Zend\Diactoros\Stream(/** @scrutinizer ignore-type */ $stream);
Loading history...
174
                    })())
175
            );
176
177
            $this->assertSame(200, $response->getStatusCode());
178
            $this->assertSame('application/vnd.ncryptf+json', $response->getHeaderLine('Content-Type'));
179
            if ($params[2] !== '') {
180
                $this->assertTrue($response->hasHeader('x-hashid'));
181
                $this->assertTrue($response->hasHeader('x-signature'));
182
                $this->assertTrue($response->hasHeader('x-sigpubkey'));
183
                $this->assertTrue($response->hasHeader('x-nonce'));
184
                $this->assertTrue($response->hasHeader('x-pubkey'));
185
                $this->assertTrue($response->hasHeader('x-public-key-expiration'));
186
            }
187
188
            $r = new Response(
189
                $myKey->getBoxSecretKey()
190
            );
191
192
            $plaintext = $r->decrypt(
193
                \base64_decode((string)$response->getBody()),
194
                \base64_decode($response->getHeaderLine('x-pubkey')),
195
                \base64_decode($response->getHeaderLine('x-nonce'))
196
            );
197
198
            $this->assertEquals(\is_array($params[2]) ? \json_encode($params[2]) : $params[2], $plaintext);
199
        }
200
    }
201
202
    public function testError()
203
    {
204
        $auth = new Authorization('GET', '/api/v1/user/index', $this->token, new DateTime, '{"foo":"bar"}');
205
        $response = Dispatcher::run(
206
            [
207
                new Authentication,
208
                function ($request, $next) {
0 ignored issues
show
Unused Code introduced by
The parameter $next is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

208
                function ($request, /** @scrutinizer ignore-unused */ $next) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

208
                function (/** @scrutinizer ignore-unused */ $request, $next) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
209
                    return new JsonResponse(['foo' => 'bar']);
210
                }
211
            ],
212
            Factory::createServerRequest('GET', '/api/v1/user/index')
213
                ->withHeader('Authorization', $auth->getHeader())
214
                ->withHeader('Content-Type', 'application/json')
215
                ->withHeader('Accept', 'application/json')
216
        );
217
218
        $this->assertSame(401, $response->getStatusCode());
219
    }
220
}
221