Oauth2RevokeAction   A
last analyzed

Complexity

Total Complexity 27

Size/Duplication

Total Lines 151
Duplicated Lines 0 %

Test Coverage

Coverage 95.65%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 27
eloc 90
c 2
b 0
f 1
dl 0
loc 151
ccs 88
cts 92
cp 0.9565
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
F run() 0 80 18
B parseTokenAsRefreshToken() 0 41 6
A parseTokenAsAccessToken() 0 23 3
1
<?php
2
3
namespace rhertogh\Yii2Oauth2Server\controllers\web\server;
4
5
use Defuse\Crypto\Crypto;
6
use Defuse\Crypto\Key;
7
use rhertogh\Yii2Oauth2Server\controllers\web\Oauth2ServerController;
8
use rhertogh\Yii2Oauth2Server\controllers\web\server\base\Oauth2BaseServerAction;
9
use rhertogh\Yii2Oauth2Server\helpers\Oauth2RequestHelper;
10
use rhertogh\Yii2Oauth2Server\interfaces\controllers\web\server\Oauth2RevokeActionInterface;
11
use rhertogh\Yii2Oauth2Server\Oauth2Module;
12
use Yii;
13
use yii\helpers\Json;
14
use yii\web\BadRequestHttpException;
15
use yii\web\ForbiddenHttpException;
16
use yii\web\NotFoundHttpException;
17
18
/**
19
 * OAuth 2.0 Token Revocation (RFC 7009)
20
 *
21
 * @property Oauth2ServerController $controller
22
 * @see https://datatracker.ietf.org/doc/html/rfc7009
23
 */
24
class Oauth2RevokeAction extends Oauth2BaseServerAction implements Oauth2RevokeActionInterface
25
{
26 9
    public function run()
27
    {
28
        try {
29 9
            $module = $this->controller->module;
30
31 9
            if (!$module->enableTokenRevocation) {
32 1
                throw new NotFoundHttpException();
33
            }
34
35 8
            $tokenParsers = [
36 8
                'refresh_token' => [$this, 'parseTokenAsRefreshToken'],
37 8
                'access_token' => [$this, 'parseTokenAsAccessToken'],
38 8
            ];
39
40 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...
41
42 8
            $token = $request->getBodyParam('token');
43 8
            if (empty($token)) {
44 1
                throw new BadRequestHttpException('The `token` body parameter is required.');
45
            }
46 7
            $tokenTypeHint = $request->getBodyParam('token_type_hint');
47 7
            if (!empty($tokenTypeHint)) {
48
49 7
                if (in_array($tokenTypeHint, array_keys($tokenParsers))) {
50
                    // Move hinted type to beginning.
51 6
                    $tokenParsers = [$tokenTypeHint => $tokenParsers[$tokenTypeHint]] + $tokenParsers;
52
                } else {
53 1
                    Yii::getLogger()->log(
54 1
                        'The client specified an unknown `token_type_hint` "' . $tokenTypeHint . '".',
55 1
                        $module->getElaboratedHttpClientErrorsLogLevel(),
56 1
                        __METHOD__
57 1
                    );
58
                }
59
            }
60
61 7
            foreach ($tokenParsers as $tokenParser) {
62 7
                $parseResult = call_user_func($tokenParser, $module, $token, $tokenTypeHint);
63 7
                if ($parseResult) {
64 7
                    $clientIdentifier = $parseResult['clientIdentifier'] ?? null;
65 7
                    $refreshTokenIdentifier = $parseResult['refreshTokenIdentifier'] ?? null;
66 7
                    $accessTokenIdentifier = $parseResult['accessTokenIdentifier'] ?? null;
67 7
                    break;
68
                }
69
            }
70
71 7
            if (empty($clientIdentifier) || empty($accessTokenIdentifier)) {
72
                throw new BadRequestHttpException('Unable to resolve the `token` parameter to a valid token type.');
73
            }
74
75 7
            $client = $module->getClientRepository()->findModelByIdentifier($clientIdentifier);
76 7
            if (!$client) {
77
                throw new BadRequestHttpException('The `client_id` "' . $clientIdentifier . '" specified in the token is not valid.'); // phpcs:ignore Generic.Files.LineLength.TooLong
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 7
            if ($client->isConfidential()) {
81
                try {
82 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

82
                    [$credentialsClientIdentifier, $clientSecret] = Oauth2RequestHelper::getClientCredentials(/** @scrutinizer ignore-type */ $request);
Loading history...
83 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...
84
                }
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 4
        } catch (\Exception $e) {
105 4
            return $this->processException($e, __METHOD__);
106
        }
107
    }
108
109 6
    protected function parseTokenAsRefreshToken(Oauth2Module $module, string $token, string $tokenTypeHint)
110
    {
111
        try {
112 6
            $refreshTokenString = Crypto::decrypt($token, Key::loadFromAsciiSafeString($module->codesEncryptionKey));
113 5
            $refreshToken = Json::decode($refreshTokenString);
114 1
        } catch (\Throwable $e) {
115 1
            if ($tokenTypeHint === 'refresh_token') {
116 1
                Yii::getLogger()->log(
117 1
                    'The client specified the `token_type_hint` as "refresh_token",'
118 1
                        . ' 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 3
            $accessTokenClaims = $module->getAccessToken($token)->claims();
156 2
            $accessTokenIdentifier = $accessTokenClaims->get('jti');
157 2
            $clientIdentifier = $accessTokenClaims->get('client_id');
158
159 2
            return [
160 2
                'clientIdentifier' => $clientIdentifier,
161 2
                'accessTokenIdentifier' => $accessTokenIdentifier
162 2
            ];
163 1
        } catch (\Throwable $e) {
164 1
            if ($tokenTypeHint === 'access_token') {
165 1
                Yii::getLogger()->log(
166 1
                    'The client specified the `token_type_hint` as "access_token",'
167 1
                        . ' however the server is unable to parse the `token` as such: ' . $e,
168 1
                    $module->getElaboratedHttpClientErrorsLogLevel(),
169 1
                    __METHOD__
170 1
                );
171
            }
172 1
            unset($e);
173
        }
174 1
        return null;
175
    }
176
}
177