Passed
Push — master ( 63d167...fb60c6 )
by Rutger
03:11
created

Oauth2RevokeAction::run()   F

Complexity

Conditions 18
Paths 259

Size

Total Lines 80
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 45
CRAP Score 18.025

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 48
c 1
b 0
f 0
dl 0
loc 80
ccs 45
cts 47
cp 0.9574
rs 3.2958
cc 18
nc 259
nop 0
crap 18.025

How to fix   Long Method    Complexity   

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
2
3
namespace rhertogh\Yii2Oauth2Server\controllers\web\server;
4
5
use Defuse\Crypto\Crypto;
6
use Defuse\Crypto\Key;
7
use Lcobucci\JWT\Configuration;
8
use Lcobucci\JWT\Signer\Key\InMemory;
9
use Lcobucci\JWT\Signer\Rsa\Sha256;
10
use Lcobucci\JWT\Validation\Constraint\SignedWith;
11
use rhertogh\Yii2Oauth2Server\controllers\web\Oauth2ServerController;
12
use rhertogh\Yii2Oauth2Server\controllers\web\server\base\Oauth2BaseServerAction;
13
use rhertogh\Yii2Oauth2Server\helpers\Oauth2RequestHelper;
14
use rhertogh\Yii2Oauth2Server\interfaces\controllers\web\server\Oauth2RevokeActionInterface;
15
use rhertogh\Yii2Oauth2Server\Oauth2Module;
16
use Yii;
17
use yii\helpers\Json;
18
use yii\web\BadRequestHttpException;
19
use yii\web\ForbiddenHttpException;
20
use yii\web\NotFoundHttpException;
21
22
/**
23
 * @property Oauth2ServerController $controller
24
 */
25
class Oauth2RevokeAction extends Oauth2BaseServerAction implements Oauth2RevokeActionInterface
26
{
27 9
    public function run()
28
    {
29
        try {
30 9
            $module = $this->controller->module;
31
32 9
            if (!$module->enableTokenRevocation) {
33 1
                throw new NotFoundHttpException();
34
            }
35
36 8
            $tokenParsers = [
37 8
                'refresh_token' => [$this, 'parseTokenAsRefreshToken'],
38 8
                'access_token' => [$this, 'parseTokenAsAccessToken'],
39 8
            ];
40
41 8
            $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...
42
43 8
            $token = $request->getBodyParam('token');
44 8
            if (empty($token)) {
45 1
                throw new BadRequestHttpException('The `token` body parameter is required.');
46
            }
47 7
            $tokenTypeHint = $request->getBodyParam('token_type_hint');
48 7
            if (!empty($tokenTypeHint)) {
49
50 7
                if (in_array($tokenTypeHint, array_keys($tokenParsers))) {
51
                    // Move hinted type to beginning
0 ignored issues
show
Coding Style introduced by
Inline comments must end in full-stops, exclamation marks, or question marks
Loading history...
52 6
                    $tokenParsers = [$tokenTypeHint => $tokenParsers[$tokenTypeHint]] + $tokenParsers;
53
                } else {
54 1
                    Yii::getLogger()->log(
55 1
                        'The client specified an unknown `token_type_hint` "' . $tokenTypeHint . '".',
56 1
                        $module->getElaboratedHttpClientErrorsLogLevel(),
57 1
                        __METHOD__
58 1
                    );
59
                }
60
            }
61
62 7
            foreach ($tokenParsers as $tokenParser) {
63 7
                $parseResult = call_user_func($tokenParser, $module, $token, $tokenTypeHint);
64 7
                if ($parseResult) {
65 7
                    $clientIdentifier = $parseResult['clientIdentifier'] ?? null;
66 7
                    $refreshTokenIdentifier = $parseResult['refreshTokenIdentifier'] ?? null;
67 7
                    $accessTokenIdentifier = $parseResult['accessTokenIdentifier'] ?? null;
68 7
                    break;
69
                }
70
            }
71
72 7
            if (empty($clientIdentifier) || empty($accessTokenIdentifier)) {
73
                throw new BadRequestHttpException('Unable to resolve the `token` parameter to a valid token type.');
74
            }
75
76 7
            $client = $module->getClientRepository()->findModelByIdentifier($clientIdentifier);
77 7
            if (!$client) {
78
                throw new BadRequestHttpException('The `client_id` "' . $clientIdentifier . '" specified in the token is not valid.');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $clientIdentifier does not seem to be defined for all execution paths leading up to this point.
Loading history...
79
            }
80
81 7
            if ($client->isConfidential()) {
82
                try {
83 7
                    [$credentialsClientIdentifier, $clientSecret] = Oauth2RequestHelper::getClientCredentials($request);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type yii\console\Request; however, parameter $request of rhertogh\Yii2Oauth2Serve...:getClientCredentials() does only seem to accept yii\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

83
                    [$credentialsClientIdentifier, $clientSecret] = Oauth2RequestHelper::getClientCredentials(/** @scrutinizer ignore-type */ $request);
Loading history...
84 1
                } catch (\Exception $exception) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
85
86 7
                if (empty($credentialsClientIdentifier) || empty($clientSecret)) {
87 1
                    throw new ForbiddenHttpException('Client authentication is required for confidential clients.');
88
                }
89
90
                if (
91 6
                    !Yii::$app->security->compareString($client->getIdentifier(), $credentialsClientIdentifier)
92 6
                    || !$client->validateSecret($clientSecret, $module->getCryptographer())
93
                ) {
94 1
                    throw new ForbiddenHttpException('Invalid client authentication.');
95
                }
96
            }
97
98 5
            if (!empty($refreshTokenIdentifier)) {
99 3
                $module->getRefreshTokenRepository()->revokeRefreshToken($refreshTokenIdentifier);
100
            }
101 5
            $module->getAccessTokenRepository()->revokeAccessToken($accessTokenIdentifier);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $accessTokenIdentifier does not seem to be defined for all execution paths leading up to this point.
Loading history...
102
103 5
            return Yii::$app->response;
104
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
105 4
        } catch (\Exception $e) {
106 4
            return $this->processException($e, __METHOD__);
107
        }
108
    }
109
110 6
    protected function parseTokenAsRefreshToken(Oauth2Module $module, string $token, string $tokenTypeHint)
111
    {
112
        try {
113 6
            $refreshTokenString = Crypto::decrypt($token, Key::loadFromAsciiSafeString($module->codesEncryptionKey));
114 5
            $refreshToken = Json::decode($refreshTokenString);
115 1
        } catch (\Throwable $e) {
116 1
            if ($tokenTypeHint === 'refresh_token') {
117 1
                Yii::getLogger()->log(
118 1
                    'The client specified the `token_type_hint` as "refresh_token", however the server is unable to parse the `token` as such: ' . $e,
119 1
                    $module->getElaboratedHttpClientErrorsLogLevel(),
120 1
                    __METHOD__
121 1
                );
122
            }
123 1
            unset($e);
124
        }
125
126 6
        if (!empty($refreshToken['refresh_token_id'])) {
127 5
            Yii::debug('Found refresh token: ' . $refreshTokenString, __METHOD__);
128 5
            $refreshTokenIdentifier = $refreshToken['refresh_token_id'];
129
130 5
            if (empty($refreshToken['access_token_id'])) {
131
                throw new BadRequestHttpException('The `access_token_id` must be specified in the refresh token.');
132
            }
133
134 5
            $accessTokenIdentifier = $refreshToken['access_token_id'];
135
136 5
            if (empty($refreshToken['client_id'])) {
137
                throw new BadRequestHttpException('The `client_id` must be specified in the refresh token.');
138
            }
139
140 5
            $clientIdentifier = $refreshToken['client_id'];
141
142 5
            return [
143 5
                'clientIdentifier' => $clientIdentifier,
144 5
                'refreshTokenIdentifier' => $refreshTokenIdentifier,
145 5
                'accessTokenIdentifier' => $accessTokenIdentifier
146 5
            ];
147
        }
148
149 1
        return null;
150
    }
151
152 3
    protected function parseTokenAsAccessToken(Oauth2Module $module, string $token, string $tokenTypeHint)
153
    {
154
        try {
155
            // Based on \League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator::initJwtConfiguration().
156 3
            $jwtConfiguration = Configuration::forSymmetricSigner(
157 3
                new Sha256(),
158 3
                InMemory::plainText('empty', 'empty')
159 3
            );
160
161 3
            $publicKey = $module->getPublicKey();
162 3
            $jwtConfiguration->setValidationConstraints(
163 3
                new SignedWith(
164 3
                    new Sha256(),
165 3
                    InMemory::plainText($publicKey->getKeyContents(), $publicKey->getPassPhrase() ?? '')
166 3
                )
167 3
            );
168
169 3
            $accessToken = $jwtConfiguration->parser()->parse($token);
170 2
            $jwtConfiguration->validator()->assert($accessToken, ...$jwtConfiguration->validationConstraints());
171 2
            Yii::debug('Found access token: ' . $token, __METHOD__);
172 2
            $accessTokenClaims = $accessToken->claims();
173 2
            $accessTokenIdentifier = $accessTokenClaims->get('jti');
174 2
            $clientIdentifier = $accessTokenClaims->get('client_id');
175
176 2
            return [
177 2
                'clientIdentifier' => $clientIdentifier,
178 2
                'accessTokenIdentifier' => $accessTokenIdentifier
179 2
            ];
180 1
        } catch (\Throwable $e) {
181 1
            if ($tokenTypeHint === 'access_token') {
182 1
                Yii::getLogger()->log(
183 1
                    'The client specified the `token_type_hint` as "access_token", however the server is unable to parse the `token` as such: ' . $e,
184 1
                    $module->getElaboratedHttpClientErrorsLogLevel(),
185 1
                    __METHOD__
186 1
                );
187
            }
188 1
            unset($e);
189
        }
190 1
        return null;
191
    }
192
}
193