Passed
Push — master ( 2b2d6e...305862 )
by Rutger
13:36
created

Oauth2RevokeAction   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 27
eloc 99
c 1
b 0
f 0
dl 0
loc 166
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B parseTokenAsRefreshToken() 0 40 6
A parseTokenAsAccessToken() 0 39 3
F run() 0 80 18
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\Oauth2Module;
15
use Yii;
16
use yii\helpers\Json;
17
use yii\web\BadRequestHttpException;
18
use yii\web\ForbiddenHttpException;
19
use yii\web\NotFoundHttpException;
20
21
/**
22
 * @property Oauth2ServerController $controller
23
 */
24
class Oauth2RevokeAction extends Oauth2BaseServerAction
25
{
26
    public function run()
27
    {
28
        try {
29
            $module = $this->controller->module;
30
31
            if (!$module->enableTokenRevocation) {
32
                throw new NotFoundHttpException();
33
            }
34
35
            $tokenParsers = [
36
                'refresh_token' => [$this, 'parseTokenAsRefreshToken'],
37
                'access_token' => [$this, 'parseTokenAsAccessToken'],
38
            ];
39
40
            $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...
41
42
            $token = $request->getBodyParam('token');
43
            if (empty($token)) {
44
                throw new BadRequestHttpException('The `token` body parameter is required.');
45
            }
46
            $tokenTypeHint = $request->getBodyParam('token_type_hint');
47
            if (!empty($tokenTypeHint)) {
48
49
                if (in_array($tokenTypeHint, array_keys($tokenParsers))) {
50
                    // 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...
51
                    $tokenParsers = [$tokenTypeHint => $tokenParsers[$tokenTypeHint]] + $tokenParsers;
52
                } else {
53
                    Yii::getLogger()->log(
54
                        'The client specified an unknown `token_type_hint` "' . $tokenTypeHint . '".',
55
                        $module->getElaboratedHttpClientErrorsLogLevel(),
56
                        __METHOD__
57
                    );
58
                }
59
            }
60
61
            foreach ($tokenParsers as $tokenParser) {
62
                $parseResult = call_user_func($tokenParser, $module, $token, $tokenTypeHint);
63
                if ($parseResult) {
64
                    $clientIdentifier = $parseResult['clientIdentifier'] ?? null;
65
                    $refreshTokenIdentifier = $parseResult['refreshTokenIdentifier'] ?? null;
66
                    $accessTokenIdentifier = $parseResult['accessTokenIdentifier'] ?? null;
67
                    break;
68
                }
69
            }
70
71
            if (empty($clientIdentifier) || empty($accessTokenIdentifier)) {
72
                throw new BadRequestHttpException('Unable to resolve the `token` parameter to a valid token type.');
73
            }
74
75
            $client = $module->getClientRepository()->findModelByIdentifier($clientIdentifier);
76
            if (!$client) {
77
                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...
78
            }
79
80
            if ($client->isConfidential()) {
81
                try {
82
                    [$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

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