Passed
Push — master ( dd7374...ca8f73 )
by Rutger
03:04
created

Oauth2AuthorizeAction   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 324
Duplicated Lines 0 %

Test Coverage

Coverage 90.4%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 48
eloc 190
c 2
b 0
f 0
dl 0
loc 324
ccs 179
cts 198
cp 0.904
rs 8.5599

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getRequestParam() 0 3 1
F run() 0 311 47

How to fix   Complexity   

Complex Class

Complex classes like Oauth2AuthorizeAction often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Oauth2AuthorizeAction, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace rhertogh\Yii2Oauth2Server\controllers\web\server;
4
5
use rhertogh\Yii2Oauth2Server\controllers\web\Oauth2ServerController;
6
use rhertogh\Yii2Oauth2Server\controllers\web\server\base\Oauth2BaseServerAction;
7
use rhertogh\Yii2Oauth2Server\exceptions\Oauth2OidcServerException;
8
use rhertogh\Yii2Oauth2Server\exceptions\Oauth2ServerException;
9
use rhertogh\Yii2Oauth2Server\helpers\Psr7Helper;
10
use rhertogh\Yii2Oauth2Server\helpers\UrlHelper;
11
use rhertogh\Yii2Oauth2Server\interfaces\components\authorization\Oauth2ClientAuthorizationRequestInterface;
12
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\request\Oauth2OidcAuthenticationRequestInterface;
13
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\scope\Oauth2OidcScopeInterface;
14
use rhertogh\Yii2Oauth2Server\interfaces\components\openidconnect\user\Oauth2OidcUserComponentInterface;
15
use rhertogh\Yii2Oauth2Server\interfaces\models\external\user\Oauth2UserAuthenticatedAtInterface;
16
use rhertogh\Yii2Oauth2Server\interfaces\models\Oauth2ClientInterface;
17
use rhertogh\Yii2Oauth2Server\Oauth2Module;
18
use Yii;
19
use yii\base\InvalidConfigException;
20
use yii\web\BadRequestHttpException;
21
use yii\web\HttpException;
22
use yii\web\Request;
23
use yii\web\Response;
24
use yii\web\UnauthorizedHttpException;
25
26
/**
27
 * @property Oauth2ServerController $controller
28
 */
29
class Oauth2AuthorizeAction extends Oauth2BaseServerAction
30
{
31 39
    public function run($clientAuthorizationRequestId = null)
32
    {
33
        try {
34 39
            $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...
35 39
            $user = Yii::$app->user;
36 39
            $module = $this->controller->module;
37
38 39
            if ($module->enableOpenIdConnect) {
39 39
                if (!($user instanceof Oauth2OidcUserComponentInterface)) {
40 1
                    throw new InvalidConfigException(
41 1
                        'OpenId Connect is enabled but user component does not implement '
42 1
                        . Oauth2OidcUserComponentInterface::class
43 1
                    );
44
                }
45
46 38
                $oidcRequest = $this->getRequestParam(
47 38
                    $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...tion::getRequestParam() 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

47
                    /** @scrutinizer ignore-type */ $request,
Loading history...
48 38
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_REQUEST
49 38
                );
50 38
                if ($oidcRequest !== null) {
51 1
                    throw Oauth2OidcServerException::requestParameterNotSupported();
52
                }
53
54 37
                $oidcRequestUri = $this->getRequestParam(
55 37
                    $request,
56 37
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_REQUEST_URI
57 37
                );
58 37
                if ($oidcRequestUri !== null) {
59 1
                    throw Oauth2OidcServerException::requestUriParameterNotSupported();
60
                }
61
            }
62
63 36
            $server = $module->getAuthorizationServer();
64 34
            $psr7Request = Psr7Helper::yiiToPsr7Request($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...per::yiiToPsr7Request() 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

64
            $psr7Request = Psr7Helper::yiiToPsr7Request(/** @scrutinizer ignore-type */ $request);
Loading history...
65 34
            $authRequest = $server->validateAuthorizationRequest($psr7Request);
66
67 33
            $requestedScopeIdentifiers = array_map(fn($scope) => $scope->getIdentifier(), $authRequest->getScopes());
68
69
            /** @var Oauth2ClientInterface $client */
70 33
            $client = $authRequest->getClient();
71
72 33
            if (!$client->validateAuthRequestScopes($requestedScopeIdentifiers, $unauthorizedScopes)) {
73 1
                throw Oauth2ServerException::scopeNotAllowedForClient(
74 1
                    array_shift($unauthorizedScopes),
75 1
                    $authRequest->getRedirectUri()
76 1
                );
77
            }
78
79
            if (
80 32
                !$client->isAuthCodeWithoutPkceAllowed()
81
                // PKCE is not supported in the implicit flow.
82 32
                && $authRequest->getGrantTypeId() != Oauth2Module::GRANT_TYPE_IDENTIFIER_IMPLICIT
83
            ) {
84 31
                if (empty($request->get('code_challenge'))) {
85 2
                    throw new BadRequestHttpException(
86 2
                        'PKCE is required for this client when using grant type "'
87 2
                            . $authRequest->getGrantTypeId() . '".'
88 2
                    );
89 29
                } elseif ($request->get('code_challenge_method', 'plain') === 'plain') {
90 1
                    throw new BadRequestHttpException('PKCE code challenge mode "plain" is not allowed.');
91
                }
92
            }
93
94 29
            if ($clientAuthorizationRequestId) {
95 11
                $clientAuthorizationRequest = $module->getClientAuthReqSession($clientAuthorizationRequestId);
96
                if (
97 11
                    $clientAuthorizationRequest
98 11
                    && $clientAuthorizationRequest->getState()
99 11
                    && !Yii::$app->security->compareString(
100 11
                        $clientAuthorizationRequest->getState(),
101 11
                        $authRequest->getState()
102 11
                    )
103
                ) {
104 1
                    throw new UnauthorizedHttpException('Invalid state.');
105
                }
106
            }
107
108 28
            if (empty($clientAuthorizationRequest)) {
109 24
                $prompts = explode(
110 24
                    ' ',
111 24
                    (string)$this->getRequestParam(
112 24
                        $request,
113 24
                        Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT
114 24
                    )
115 24
                )
116 24
                    ?? [];
117
118
                if (
119 24
                    in_array(Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE, $prompts)
120 24
                    && (count($prompts) > 1)
121
                ) {
122 1
                    throw new BadRequestHttpException(
123 1
                        'When the "prompt" parameter contains "none" other values are not allowed.'
124 1
                    );
125
                }
126
127
                // Ignore `offline_access` scope if prompt doesn't contain 'consent' (or pre-approved via config).
128
                // See https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess.
129
                if (
130 23
                    in_array(Oauth2OidcScopeInterface::OPENID_CONNECT_SCOPE_OFFLINE_ACCESS, $requestedScopeIdentifiers)
131 23
                    && !in_array(Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_CONSENT, $prompts)
132 23
                    && !$client->getOpenIdConnectAllowOfflineAccessWithoutConsent()
133
                ) {
134 1
                    $requestedScopeIdentifiers = array_diff(
135 1
                        $requestedScopeIdentifiers,
136 1
                        [Oauth2OidcScopeInterface::OPENID_CONNECT_SCOPE_OFFLINE_ACCESS]
137 1
                    );
138
                }
139
140 23
                $maxAge = $this->getRequestParam(
141 23
                    $request,
142 23
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_MAX_AGE
143 23
                );
144 23
                if ($maxAge === '') {
145 1
                    $maxAge = null;
146 22
                } elseif ($maxAge !== null) {
147 4
                    $maxAge = (int)$maxAge;
148
                }
149
150
                /** @var Oauth2ClientAuthorizationRequestInterface $clientAuthorizationRequest */
151 23
                $clientAuthorizationRequest = Yii::createObject([
152 23
                    'class' => Oauth2ClientAuthorizationRequestInterface::class,
153 23
                    'module' => $module,
154 23
                    'userAuthenticatedBeforeRequest' => !$user->isGuest,
155 23
                    'clientIdentifier' => $authRequest->getClient()->getIdentifier(),
156 23
                    'state' => $authRequest->getState(),
157 23
                    'requestedScopeIdentifiers' => $requestedScopeIdentifiers,
158 23
                    'grantType' => $authRequest->getGrantTypeId(),
159 23
                    'authorizeUrl' => $request->absoluteUrl,
160 23
                    'redirectUri' => $authRequest->getRedirectUri(),
161 23
                    'prompts' => $prompts,
162 23
                    'maxAge' => $maxAge,
163 23
                ]);
164
            }
165
166 27
            if ($user->isGuest) {
167
                if (
168 4
                    in_array(
169 4
                        Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE,
170 4
                        $clientAuthorizationRequest->getPrompts()
171 4
                    )
172
                ) {
173
                    // User authentication disallowed by OpenID Connect.
174 1
                    throw Oauth2OidcServerException::loginRequired($authRequest->getRedirectUri());
175
                }
176
177 3
                $module->setClientAuthReqSession($clientAuthorizationRequest);
178 3
                $user->setReturnUrl($clientAuthorizationRequest->getAuthorizationRequestUrl());
179
//                $user->setReturnUrl(UrlHelper::addQueryParams($request->absoluteUrl, [
180
//                    'clientAuthorizationRequestId' => $clientAuthorizationRequest->getRequestId(),
181
//                ]));
182
183 3
                return Yii::$app->response->redirect($user->loginUrl);
184
            }
185
186
            // Check if reauthentication is required.
187 25
            $reauthenticationRequired = false;
188 25
            if (!$clientAuthorizationRequest->wasUserAthenticatedDuringRequest()) {
189
                if (
190
                    (// true in case user was authenticated before request and oidc prompt requires login.
191 25
                        in_array(
192 25
                            Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_LOGIN,
193 25
                            $clientAuthorizationRequest->getPrompts()
194 25
                        )
195 25
                        && $clientAuthorizationRequest->wasUserAuthenticatedBeforeRequest()
196
                    )
197
                ) {
198 2
                    $reauthenticationRequired = true;
199
                }
200
201
                if (
202 25
                    !$reauthenticationRequired // Prevent unnecessary checking.
203 25
                    && $clientAuthorizationRequest->getMaxAge() !== null
204
                ) {
205 4
                    $appUserIdentity = $module->getUserIdentity();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $appUserIdentity is correct as $module->getUserIdentity() targeting rhertogh\Yii2Oauth2Serve...dule::getUserIdentity() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
206 4
                    if (!($appUserIdentity instanceof Oauth2UserAuthenticatedAtInterface)) {
207
                        throw new InvalidConfigException(
208
                            'The authorization request max age is set, but ' . get_class($appUserIdentity)
0 ignored issues
show
Bug introduced by
$appUserIdentity of type null is incompatible with the type object expected by parameter $object of get_class(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

208
                            'The authorization request max age is set, but ' . get_class(/** @scrutinizer ignore-type */ $appUserIdentity)
Loading history...
209
                            . ' does not implement ' . Oauth2UserAuthenticatedAtInterface::class
210
                        );
211
                    }
212 4
                    $latestAuthenticatedAt = $appUserIdentity->getLatestAuthenticatedAt();
213
                    if (
214 4
                        ($latestAuthenticatedAt === null)
215
                        || ( // if $latestAuthenticatedAt is not null, check if it's before the max time allowed.
216 4
                            (time() - $latestAuthenticatedAt->getTimestamp()) > $clientAuthorizationRequest->getMaxAge()
217
                        )
218
                    ) {
219 3
                        $reauthenticationRequired = true;
220
                    }
221
                }
222
            }
223
224 25
            if ($reauthenticationRequired) {
225
                // Prevent redirect loop.
226 4
                $redirectAttempt = (int)$request->get('redirectAttempt', 0);
227 4
                if ($redirectAttempt > 3) {
228
                    // This error most likely occurs if the User Controller does not correctly performs
229
                    // user reauthentication and redirect back to this action without calling
230
                    // `setUserAuthenticatedDuringRequest(true)` on the $clientAuthorizationRequest.
231
                    throw new HttpException(
232
                        501,
233
                        'Reauthentication not correctly implemented, aborting due to redirect loop.'
234
                    );
235
                }
236
237 4
                $module->setClientAuthReqSession($clientAuthorizationRequest);
238 4
                $user->setReturnUrl(
239 4
                    UrlHelper::addQueryParams($clientAuthorizationRequest->getAuthorizationRequestUrl(), [
240 4
                        'redirectAttempt' => $redirectAttempt + 1,
241 4
                    ])
242 4
                );
243 4
                return $user->reauthenticationRequired($clientAuthorizationRequest);
244
            }
245
246 22
            $userAccountSelection = $client->getUserAccountSelection() ?? $module->defaultUserAccountSelection;
247
248 22
            if (empty($clientAuthorizationRequest->getUserIdentity())) {
249
                if (
250 18
                    ($userAccountSelection === Oauth2Module::USER_ACCOUNT_SELECTION_ALWAYS)
251
                    || (
252 18
                        $userAccountSelection === Oauth2Module::USER_ACCOUNT_SELECTION_UPON_CLIENT_REQUEST
253 18
                        && in_array(
254 18
                            Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_SELECT_ACCOUNT,
255 18
                            $clientAuthorizationRequest->getPrompts()
256 18
                        )
257
                    )
258
                ) {
259
                    if (
260 4
                        in_array(
261 4
                            Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE,
262 4
                            $clientAuthorizationRequest->getPrompts()
263 4
                        )
264
                    ) {
265 2
                        throw Oauth2OidcServerException::accountSelectionRequired(
266 2
                            'User account selection is required but the "prompt" parameter is set to "none".',
267 2
                            $authRequest->getRedirectUri()
268 2
                        );
269
                    }
270 2
                    $accountSelectionRequiredResponse = $user->accountSelectionRequired($clientAuthorizationRequest);
271 2
                    if ($accountSelectionRequiredResponse === false) {
272
                        throw Oauth2OidcServerException::accountSelectionRequired(
273
                            'User account selection is not supported by the server.',
274
                            $authRequest->getRedirectUri(),
275
                        );
276
                    }
277 2
                    $module->setClientAuthReqSession($clientAuthorizationRequest);
278 2
                    $user->setReturnUrl($clientAuthorizationRequest->getAuthorizationRequestUrl());
279 2
                    return $accountSelectionRequiredResponse;
280
                } else {
281 14
                    $clientAuthorizationRequest->setUserIdentity($module->getUserIdentity());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $module->getUserIdentity() targeting rhertogh\Yii2Oauth2Serve...dule::getUserIdentity() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
282
                }
283
            }
284
285
            if (
286 19
                $clientAuthorizationRequest->getUserIdentity()->isOauth2ClientAllowed(
287 19
                    $client,
288 19
                    $clientAuthorizationRequest->getGrantType()
289 19
                ) !== true
290
            ) {
291
                throw Oauth2ServerException::accessDenied(
292
                    Yii::t('oauth2', 'User {user_id} is not allowed to use client {client_identifier}.', [
293
                        'user_id' => $user->getId(),
294
                        'client_identifier' => $client->getIdentifier(),
295
                    ])
296
                );
297
            }
298
299
            if (
300 19
                $clientAuthorizationRequest->isAuthorizationNeeded()
301 19
                || in_array(
302 19
                    Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_CONSENT,
303 19
                    $clientAuthorizationRequest->getPrompts()
304 19
                )
305
            ) {
306 18
                if (!$clientAuthorizationRequest->isAuthorizationAllowed()) {
307
                    throw Oauth2ServerException::authorizationNotAllowed();
308
                }
309
310
                if (
311 18
                    in_array(
312 18
                        Oauth2OidcAuthenticationRequestInterface::REQUEST_PARAMETER_PROMPT_NONE,
313 18
                        $clientAuthorizationRequest->getPrompts()
314 18
                    )
315
                ) {
316
                    // User consent is disallowed by OpenID Connect.
317 1
                    throw Oauth2OidcServerException::consentRequired($authRequest->getRedirectUri());
318
                }
319
320 17
                if ($clientAuthorizationRequest->isCompleted()) {
321 6
                    $authorizationApproved = $clientAuthorizationRequest->isApproved();
322
                    // Cleanup session data.
323 6
                    $module->removeClientAuthReqSession($clientAuthorizationRequest->getRequestId());
324
                } else {
325 17
                    return $module->generateClientAuthReqRedirectResponse($clientAuthorizationRequest);
326
                }
327
            } else {
328
                // All scopes are already approved (or are default).
329 2
                $authorizationApproved = true;
330
            }
331
332 8
            $authRequest->setUser($clientAuthorizationRequest->getUserIdentity());
333 8
            $authRequest->setAuthorizationApproved($authorizationApproved);
334
335 8
            $psr7Response = Psr7Helper::yiiToPsr7Response(Yii::$app->response);
0 ignored issues
show
Bug introduced by
It seems like Yii::app->response can also be of type yii\console\Response; however, parameter $response of rhertogh\Yii2Oauth2Serve...er::yiiToPsr7Response() does only seem to accept yii\web\Response, 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

335
            $psr7Response = Psr7Helper::yiiToPsr7Response(/** @scrutinizer ignore-type */ Yii::$app->response);
Loading history...
336 8
            $psr7Response = $server->completeAuthorizationRequest($authRequest, $psr7Response);
337
338 7
            return Psr7Helper::psr7ToYiiResponse($psr7Response);
339 17
        } catch (\Exception $e) {
340 17
            Yii::error((string)$e, __METHOD__);
341 17
            return $this->processException($e);
342
        }
343
    }
344
345
    /**
346
     * @param Request $request
347
     * @param string $name
348
     * @return mixed
349
     */
350 38
    protected function getRequestParam($request, $name, $defaultValue = null)
351
    {
352 38
        return $request->post($name) ?? $request->get($name, $defaultValue);
353
    }
354
}
355