Passed
Push — master ( a721e7...5904cd )
by Rutger
13:40
created

Oauth2RevokeAction::parseTokenAsAccessToken()   A

Complexity

Conditions 3
Paths 19

Size

Total Lines 40
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 40
ccs 32
cts 32
cp 1
rs 9.488
cc 3
nc 19
nop 3
crap 3
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
 * OAuth 2.0 Token Revocation (RFC 7009)
24
 *
25
 * @property Oauth2ServerController $controller
26
 * @see https://datatracker.ietf.org/doc/html/rfc7009
27
 */
28
class Oauth2RevokeAction extends Oauth2BaseServerAction implements Oauth2RevokeActionInterface
29
{
30 9
    public function run()
31
    {
32
        try {
33 9
            $module = $this->controller->module;
34
35 9
            if (!$module->enableTokenRevocation) {
36 1
                throw new NotFoundHttpException();
37
            }
38
39 8
            $tokenParsers = [
40 8
                'refresh_token' => [$this, 'parseTokenAsRefreshToken'],
41 8
                'access_token' => [$this, 'parseTokenAsAccessToken'],
42 8
            ];
43
44 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...
45
46 8
            $token = $request->getBodyParam('token');
47 8
            if (empty($token)) {
48 1
                throw new BadRequestHttpException('The `token` body parameter is required.');
49
            }
50 7
            $tokenTypeHint = $request->getBodyParam('token_type_hint');
51 7
            if (!empty($tokenTypeHint)) {
52
53 7
                if (in_array($tokenTypeHint, array_keys($tokenParsers))) {
54
                    // Move hinted type to beginning.
55 6
                    $tokenParsers = [$tokenTypeHint => $tokenParsers[$tokenTypeHint]] + $tokenParsers;
56
                } else {
57 1
                    Yii::getLogger()->log(
58 1
                        'The client specified an unknown `token_type_hint` "' . $tokenTypeHint . '".',
59 1
                        $module->getElaboratedHttpClientErrorsLogLevel(),
60 1
                        __METHOD__
61 1
                    );
62
                }
63
            }
64
65 7
            foreach ($tokenParsers as $tokenParser) {
66 7
                $parseResult = call_user_func($tokenParser, $module, $token, $tokenTypeHint);
67 7
                if ($parseResult) {
68 7
                    $clientIdentifier = $parseResult['clientIdentifier'] ?? null;
69 7
                    $refreshTokenIdentifier = $parseResult['refreshTokenIdentifier'] ?? null;
70 7
                    $accessTokenIdentifier = $parseResult['accessTokenIdentifier'] ?? null;
71 7
                    break;
72
                }
73
            }
74
75 7
            if (empty($clientIdentifier) || empty($accessTokenIdentifier)) {
76
                throw new BadRequestHttpException('Unable to resolve the `token` parameter to a valid token type.');
77
            }
78
79 7
            $client = $module->getClientRepository()->findModelByIdentifier($clientIdentifier);
80 7
            if (!$client) {
81
                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...
82
            }
83
84 7
            if ($client->isConfidential()) {
85
                try {
86 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

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