Passed
Pull Request — main (#308)
by Paul
14:48 queued 07:30
created

SamlController::consumeAssertionAction()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 63
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 6
eloc 36
nc 9
nop 1
dl 0
loc 63
rs 8.7217
c 5
b 0
f 0

How to fix   Long Method   

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
declare(strict_types = 1);
4
5
/**
6
 * Copyright 2014 SURFnet bv
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
Coding Style introduced by
Missing @link tag in file comment
Loading history...
20
21
namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;
22
23
use Exception;
24
use Psr\Log\LoggerInterface;
25
use Surfnet\SamlBundle\Http\PostBinding;
26
use Surfnet\SamlBundle\Http\RedirectBinding;
27
use Surfnet\SamlBundle\Http\XMLResponse;
28
use Surfnet\SamlBundle\Metadata\MetadataFactory;
29
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
30
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
31
use Surfnet\StepupBundle\Service\LoaResolutionService;
32
use Surfnet\StepupBundle\Value\Loa;
33
use Surfnet\StepupSelfService\SelfServiceBundle\Controller\SelfVet\SelfVetController;
34
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
35
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenState;
36
use Surfnet\StepupSelfService\SelfServiceBundle\Service\TestSecondFactor\TestAuthenticationRequestFactory;
0 ignored issues
show
Bug introduced by
The type Surfnet\StepupSelfServic...nticationRequestFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
37
use Surfnet\StepupSelfService\SelfServiceBundle\Value\SelfVetRequestId;
38
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
39
use Symfony\Component\HttpFoundation\RedirectResponse;
40
use Symfony\Component\HttpFoundation\Request;
41
use Symfony\Component\HttpFoundation\RequestStack;
42
use Symfony\Component\HttpFoundation\Response;
43
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
44
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
45
use Symfony\Component\Routing\Attribute\Route;
46
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
47
use Symfony\Component\Security\Core\Exception\AuthenticationException;
48
49
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
50
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) -- Hard to reduce due to different commands and queries used.
51
 * TODO: Split op in smaller controllers
52
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
53
class SamlController extends AbstractController
54
{
55
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
56
        private readonly LoggerInterface                  $logger,
57
        private readonly SecondFactorService              $secondFactorService,
58
        private readonly RequestStack                     $requestStack,
59
        private readonly LoaResolutionService             $loaResolutionService,
60
        private readonly MetadataFactory                  $metadataFactory,
61
        private readonly SamlAuthenticationLogger         $samlAuthenticationLogger,
62
        private readonly TestAuthenticationRequestFactory $testAuthenticationRequestFactory,
63
        private readonly RedirectBinding                  $redirectBinding,
64
        private readonly PostBinding                      $postBinding,
65
    ) {
66
    }
67
68
    /**
69
     * A SelfService user is able to test it's token in this endpoint
70
     *
71
     * @throws NotFoundHttpException
72
     * @throws AccessDeniedException
73
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
74
    #[Route(path: '/second-factor/test', name: 'ss_second_factor_test', methods: ['GET'])]
75
    public function testSecondFactor(): RedirectResponse
76
    {
77
        $this->logger->notice('Starting second factor test');
78
79
        $identity = $this->getUser()->getIdentity();
0 ignored issues
show
Bug introduced by
The method getIdentity() does not exist on Symfony\Component\Security\Core\User\UserInterface. It seems like you code against a sub-type of Symfony\Component\Security\Core\User\UserInterface such as Surfnet\StepupSelfServic...n\AuthenticatedIdentity. ( Ignorable by Annotation )

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

79
        $identity = $this->getUser()->/** @scrutinizer ignore-call */ getIdentity();
Loading history...
80
81
        $vettedSecondFactors = $this->secondFactorService->findVettedByIdentity($identity->id);
82
        if (!$vettedSecondFactors || $vettedSecondFactors->getTotalItems() === 0) {
83
            $this->logger->error(
84
                sprintf(
85
                    'Identity "%s" tried to test a second factor, but does not own a suitable vetted token.',
86
                    $identity->id,
87
                ),
88
            );
89
90
            throw new NotFoundHttpException();
91
        }
92
93
94
        // By requesting LoA 1.5 any relevant token can be tested (LoA 2 and 3)
95
        $authenticationRequest = $this->testAuthenticationRequestFactory->createSecondFactorTestRequest(
96
            $identity->nameId,
97
            $this->loaResolutionService->getLoaByLevel(Loa::LOA_SELF_VETTED),
0 ignored issues
show
Bug introduced by
Surfnet\StepupBundle\Value\Loa::LOA_SELF_VETTED of type double is incompatible with the type integer expected by parameter $loaLevel of Surfnet\StepupBundle\Ser...ervice::getLoaByLevel(). ( Ignorable by Annotation )

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

97
            $this->loaResolutionService->getLoaByLevel(/** @scrutinizer ignore-type */ Loa::LOA_SELF_VETTED),
Loading history...
98
        );
99
100
        $this->requestStack->getSession()->set('second_factor_test_request_id', $authenticationRequest->getRequestId());
101
102
        $samlLogger = $this->samlAuthenticationLogger->forAuthentication($authenticationRequest->getRequestId());
103
        $samlLogger->notice('Sending authentication request to the second factor test IDP');
104
105
        return $this->redirectBinding->createResponseFor($authenticationRequest);
106
    }
107
108
    #[Route(
109
        path: '/authentication/consume-assertion',
110
        name: 'selfservice_serviceprovider_consume_assertion',
111
        methods: ['POST'],
112
    )]
113
    public function consumeAssertion(Request $httpRequest): Response
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function consumeAssertion()
Loading history...
114
    {
115
        $session = $this->requestStack->getSession();
116
        if ($session->has(SelfVetController::SELF_VET_SESSION_ID)) {
117
            // The test authentication IdP is also used for self vetting, a different session id is
118
            // used to mark a self vet command
119
            /** @var SelfVetRequestId $selfVetRequestId */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
120
            $selfVetRequestId = $session->get(SelfVetController::SELF_VET_SESSION_ID);
121
            $secondFactorId = $selfVetRequestId->vettingSecondFactorId();
122
            return $this->forward(
123
                'Surfnet\StepupSelfService\SelfServiceBundle\Controller\SelfVetController::consumeSelfVetAssertion',
124
                ['secondFactorId' => $secondFactorId],
125
            );
126
        }
127
        if ($session->has(RecoveryTokenState::RECOVERY_TOKEN_STEP_UP_REQUEST_ID_IDENTIFIER)) {
128
            // The test authentication IdP is also used for self-asserted recovery token
129
            // verification a different session id is used to mark the authentication.
130
            return $this->forward('Surfnet\StepupSelfService\SelfServiceBundle\Controller\RecoveryTokenController::stepUpConsumeAssertion');
131
        }
132
        if (!$session->has('second_factor_test_request_id')) {
133
            $this->logger->error(
134
                'Received an authentication response for testing a second factor, but no second factor test response was expected',
135
            );
136
137
            throw new AccessDeniedHttpException('Did not expect an authentication response');
138
        }
139
        $this->logger->notice('Received an authentication response for testing a second factor');
140
        $initiatedRequestId = $session->get('second_factor_test_request_id');
141
        $samlLogger = $this->samlAuthenticationLogger->forAuthentication($initiatedRequestId);
142
        $session->remove('second_factor_test_request_id');
143
        try {
144
            $assertion = $this->postBinding->processResponse(
145
                $httpRequest,
146
                $this->container->get('self_service.second_factor_test_idp'),
147
                $this->container->get('surfnet_saml.hosted.service_provider'),
148
            );
149
150
            if (!InResponseTo::assertEquals($assertion, $initiatedRequestId)) {
151
                $samlLogger->error(
152
                    sprintf(
153
                        'Expected a response to the request with ID "%s", but the SAMLResponse was a response to a different request',
154
                        $initiatedRequestId,
155
                    ),
156
                );
157
158
                throw new AuthenticationException('Unexpected InResponseTo in SAMLResponse');
159
            }
160
161
            $this->addFlash('success', 'ss.test_second_factor.verification_successful');
162
        } catch (Exception) {
163
            $this->addFlash('error', 'ss.test_second_factor.verification_failed');
164
        }
165
        return $this->redirectToRoute('ss_second_factor_list');
166
    }
167
168
    #[Route(
169
        path: '/authentication/metadata',
170
        name: 'selfservice_saml_metadata',
171
        methods: ['GET'],
172
    )]
173
    public function metadata(): XMLResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function metadata()
Loading history...
174
    {
175
        return new XMLResponse($this->metadataFactory->generate()->__toString());
176
    }
177
}
178