JsonParser::decryptRequest()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 19
nc 5
nop 4
dl 0
loc 32
rs 9.3222
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace yrc\web\ncryptf;
4
5
use InvalidArgumentException;
6
use ncryptf\Request;
7
use ncryptf\Response;
8
use ncryptf\exceptions\DecryptionFailedException;
9
use ncryptf\exceptions\InvalidSignatureException;
10
use ncryptf\exceptions\InvalidChecksumException;
11
use ncryptf\middleware\EncryptionKeyInterface;
0 ignored issues
show
Bug introduced by
The type ncryptf\middleware\EncryptionKeyInterface 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 yrc\models\redis\EncryptionKey;
13
use yrc\web\Request as YiiRequest;
14
use yii\base\Exception;
15
use yii\base\InvalidParamException;
16
use yii\helpers\Json;
17
use yii\web\BadRequestHttpException;
18
use Yii;
19
20
/**
21
 * Parses vnd.ncryptf+json
22
 * @class Ncryptf JsonParser
23
 */
24
class JsonParser extends \yii\web\JsonParser
25
{
26
    private $decryptedBody;
27
28
    /**
29
     * Returns the decrypted response
30
     *
31
     * @return string
32
     */
33
    public function getDecryptedBody() :? string
34
    {
35
        return $this->decryptedBody;
36
    }
37
38
    /**
39
     * Parses vnd.ncryptf+json
40
     *
41
     * @param string  $rawBody
42
     * @param string $contentType
43
     * @return mixed
44
     */
45
    public function parse($rawBody, $contentType)
46
    {
47
        if ($contentType === 'application/vnd.25519+json') {
48
            Yii::warning([
49
                'message' => '`application/vnd.25519+json` content type is deprecated. Migrate to `application/vnd.ncryptf+json'
50
            ]);
51
        }
52
53
        if ($rawBody === '') {
54
            $this->decryptedBody = '';
55
            return [];
56
        }
57
58
        $request = Yii::$app->request;
0 ignored issues
show
Documentation Bug introduced by
It seems like Yii::app->request can also be of type yii\web\Request. However, the property $request is declared as type yii\console\Request. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
59
        $version = Response::getVersion(\base64_decode($rawBody));
60
        $key = $this->getEncryptionKey($request);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type yii\console\Request; however, parameter $request of yrc\web\ncryptf\JsonParser::getEncryptionKey() does only seem to accept yrc\web\Request, 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

60
        $key = $this->getEncryptionKey(/** @scrutinizer ignore-type */ $request);
Loading history...
61
62
        try {
63
            $this->decryptedBody = $this->decryptRequest($key, $request, $rawBody, $version);
64
        } catch (DecryptionFailedException | InvalidArgumentException | InvalidSignatureException | InvalidChecksumException $e) {
65
            throw new BadRequestHttpException(Yii::t('yrc', 'Unable to decrypt response.'));
66
        } catch (\Exception $e) {
67
            Yii::warning([
68
                'message' => 'An unexpected error occured when decryption the response. See attached exception',
69
                'exception' => $e
70
            ]);
71
72
            throw new BadRequestHttpException(Yii::t('yrc', 'Unable to decrypt response.'));
73
        }
74
75
        try {
76
            $parameters = Json::decode($this->decryptedBody, $this->asArray);
77
            return $parameters ?? [];
78
        } catch (InvalidParamException $e) {
79
            if ($this->throwException) {
80
                throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage());
81
            }
82
            return [];
83
        }
84
    }
85
86
    /**
87
     * Decrypts the request using a given encryption key and request parameters
88
     *
89
     * @param EncryptionKeyInterface $key
90
     * @param \yrc\web\Request $request
91
     * @param string $rawBody
92
     * @param string $version
93
     * @return string
94
     */
95
    private function decryptRequest(EncryptionKeyInterface $key, \yrc\web\Request $request, string $rawBody, int $version)
96
    {
97
        static $response = null;
98
        static $nonce = null;
99
        static $publicKey = null;
100
101
        $response = new Response(
102
            $key->getBoxSecretKey()
103
        );
104
105
        if ($version === 1) {
106
            $publicKey = $request->headers->get('x-pubkey', null);
107
            $nonce = $request->headers->get('x-nonce', null);
108
109
            if ($publicKey === null || $nonce === null) {
0 ignored issues
show
introduced by
The condition $nonce === null is always false.
Loading history...
110
                throw new Exception(Yii::t('yrc', 'Missing nonce or public key header. Unable to decrypt request.'));
111
            }
112
            $nonce = \base64_decode($nonce);
0 ignored issues
show
Bug introduced by
It seems like $nonce can also be of type array; however, parameter $data of base64_decode() does only seem to accept 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

112
            $nonce = \base64_decode(/** @scrutinizer ignore-type */ $nonce);
Loading history...
113
            $publicKey = \base64_decode($publicKey);
114
        }
115
116
        $decryptedRequest = $response->decrypt(
117
            \base64_decode($rawBody),
118
            $publicKey,
119
            $nonce
120
        );
121
122
        if ($key->isEphemeral()) {
123
            $key->delete();
124
        }
125
126
        return $decryptedRequest;
127
    }
128
129
    /**
130
     * Fetches the local encryption key from the data provided in the request
131
     *
132
     * @param \yrc\web\Request $request
133
     * @param string $rawBody
134
     * @param integer $version
135
     * @return EncryptionKey
136
     */
137
    private function getEncryptionKey(\yrc\web\Request $request) : EncryptionKey
138
    {
139
        $lookup = $request->headers->get('x-hashid', null);
140
        if ($lookup === null) {
0 ignored issues
show
introduced by
The condition $lookup === null is always false.
Loading history...
141
            Yii::warning([
142
                'message' => 'X-HashId missing on request. Unable to decrypt response.'
143
            ]);
144
            throw new Exception(Yii::t('yrc', 'Unable to decrypt response.'));
145
        }
146
147
        $key = EncryptionKey::find()->where([
148
            'hash' => $lookup
149
        ])->one();
150
151
        if ($key === null) {
152
            throw new Exception(Yii::t('yrc', 'Unable to decrypt response.'));
153
        }
154
155
        return $key;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $key returns the type array which is incompatible with the type-hinted return yrc\models\redis\EncryptionKey.
Loading history...
156
    }
157
}
158