Passed
Push — feature/symfony6-upgrade ( 166417...86e2b9 )
by Paul
06:45
created

SelfVetController::consumeSelfVetAssertionAction()   B

Complexity

Conditions 6
Paths 15

Size

Total Lines 60
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 38
c 1
b 0
f 0
nc 15
nop 2
dl 0
loc 60
rs 8.6897

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
/**
4
 * Copyright 2021 SURFnet B.V.
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
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...
18
19
namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;
20
21
use Exception;
22
use Psr\Log\LoggerInterface;
23
use Surfnet\SamlBundle\Entity\IdentityProvider;
24
use Surfnet\SamlBundle\Entity\ServiceProvider;
25
use Surfnet\SamlBundle\Http\PostBinding;
26
use Surfnet\SamlBundle\Http\RedirectBinding;
27
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
28
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
29
use Surfnet\StepupBundle\Service\LoaResolutionService;
30
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
31
use Surfnet\StepupBundle\Value\Loa;
32
use Surfnet\StepupBundle\Value\SecondFactorType;
33
use Surfnet\StepupBundle\Value\VettingType;
34
use Surfnet\StepupSelfService\SelfServiceBundle\Command\SelfVetCommand;
35
use Surfnet\StepupSelfService\SelfServiceBundle\Service\AuthorizationService;
36
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
37
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfVetMarshaller;
38
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...
39
use Surfnet\StepupSelfService\SelfServiceBundle\Value\SelfVetRequestId;
40
use Symfony\Component\HttpFoundation\RedirectResponse;
41
use Symfony\Component\HttpFoundation\Request;
42
use Symfony\Component\HttpFoundation\RequestStack;
43
use Symfony\Component\HttpFoundation\Session\SessionInterface;
44
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
45
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
46
use Symfony\Component\Routing\Annotation\Route;
47
use Symfony\Component\Security\Core\Exception\AuthenticationException;
48
use function sprintf;
49
50
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
51
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - Controllers are prone to higher coupling. This one is no exception
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 SelfVetController extends Controller
54
{
55
    final public const SELF_VET_SESSION_ID = 'second_factor_self_vet_request_id';
56
57
    /** @var TestAuthenticationRequestFactory */
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...
58
    public $authenticationRequestFactory;
59
60
    /** @var SecondFactorService */
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...
61
    public $secondFactorService;
62
63
    /** @var SecondFactorTypeService */
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...
64
    public $secondFactorTypeService;
65
66
    /** @var RedirectBinding */
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...
67
    public $redirectBinding;
68
69
    /** @var PostBinding */
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...
70
    public $postBinding;
71
72
    /** @var LoaResolutionService */
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...
73
    public $loaResolutionService;
74
75
    /** @var SamlAuthenticationLogger */
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...
76
    public $samlLogger;
77
78
    /** @var SessionInterface */
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...
79
    public $session;
80
81
    /** @var LoggerInterface */
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...
82
    public $logger;
83
84
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $authenticationRequestFactory should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $secondFactorService should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $secondFactorTypeService should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $selfVetMarshaller should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $authorizationService should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $serviceProvider should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $identityProvider should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $redirectBinding should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $postBinding should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $loaResolutionService should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $samlAuthenticationLogger should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $requestStack should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $logger should have a doc-comment as per coding-style.
Loading history...
85
     * @@SuppressWarnings(PHPMD.ExcessiveParameterList)
86
     */
87
    public function __construct(
88
        TestAuthenticationRequestFactory $authenticationRequestFactory,
89
        SecondFactorService $secondFactorService,
90
        SecondFactorTypeService $secondFactorTypeService,
91
        private readonly SelfVetMarshaller $selfVetMarshaller,
92
        private readonly AuthorizationService $authorizationService,
93
        private readonly ServiceProvider $serviceProvider,
94
        private readonly IdentityProvider $identityProvider,
95
        RedirectBinding $redirectBinding,
96
        PostBinding $postBinding,
97
        LoaResolutionService $loaResolutionService,
98
        SamlAuthenticationLogger $samlAuthenticationLogger,
99
        RequestStack $requestStack,
100
        LoggerInterface $logger
101
    ) {
102
        $this->authenticationRequestFactory = $authenticationRequestFactory;
103
        $this->secondFactorService = $secondFactorService;
104
        $this->secondFactorTypeService = $secondFactorTypeService;
105
        $this->redirectBinding = $redirectBinding;
106
        $this->postBinding = $postBinding;
107
        $this->loaResolutionService = $loaResolutionService;
108
        $this->samlLogger = $samlAuthenticationLogger;
109
        $this->session = $requestStack->getSession();
110
        $this->logger = $logger;
111
    }
112
113
    #[Route(
114
        path: '/second-factor/{secondFactorId}/self-vet',
115
        name: 'ss_second_factor_self_vet',
116
        methods: ['GET'],
117
    )]
118
    public function selfVet(string $secondFactorId): RedirectResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function selfVet()
Loading history...
119
    {
120
        $this->logger->notice('Starting self vet proof of possession using higher or equal LoA token');
121
        $identity = $this->getIdentity();
122
123
        if (!$this->selfVetMarshaller->isAllowed($identity, $secondFactorId)) {
124
            throw new NotFoundHttpException();
125
        }
126
127
128
        // Start with some assumptions that are overwritten with the correct values in the code below
129
        $candidateSecondFactorLoa = $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

129
        $candidateSecondFactorLoa = $this->loaResolutionService->getLoaByLevel(/** @scrutinizer ignore-type */ Loa::LOA_SELF_VETTED);
Loading history...
130
        $isSelfVetOfSatToken = false;
131
132
        // Determine if we are dealing with a SelfVet action of a SAT token
133
        if ($this->authorizationService->maySelfVetSelfAssertedTokens($identity)) {
134
            $this->logger->notice('Determined we are self vetting a token using a self-asserted token');
135
            $isSelfVetOfSatToken = true;
136
        }
137
138
        // When a regular self-vet action is performed grab the candidate second factor loa from the SF projection
139
        if (!$isSelfVetOfSatToken) {
140
            $this->logger->notice('Determined we are self vetting a token using an identity vetted token');
141
            $candidateSecondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
142
            $candidateSecondFactorLoa = $this->secondFactorTypeService->getLevel(
143
                new SecondFactorType($candidateSecondFactor->type),
144
                new VettingType(VettingType::TYPE_SELF_VET)
145
            );
146
            $candidateSecondFactorLoa = $this->loaResolutionService->getLoaByLevel($candidateSecondFactorLoa);
147
        }
148
        $this->logger->notice(
149
            sprintf(
150
                'Creating AuthNRequest requiring a LoA %s or higher token for self vetting.',
151
                $candidateSecondFactorLoa
152
            )
153
        );
154
        $authenticationRequest = $this->authenticationRequestFactory->createSecondFactorTestRequest(
155
            $identity->nameId,
156
            $candidateSecondFactorLoa
157
        );
158
159
        $this->session->set(
160
            self::SELF_VET_SESSION_ID,
161
            new SelfVetRequestId($authenticationRequest->getRequestId(), $secondFactorId)
162
        );
163
164
        $samlLogger = $this->samlLogger->forAuthentication($authenticationRequest->getRequestId());
165
        $samlLogger->notice('Sending authentication request to the second factor only IdP');
166
167
        return $this->redirectBinding->createRedirectResponseFor($authenticationRequest);
0 ignored issues
show
Bug introduced by
The method createRedirectResponseFor() does not exist on Surfnet\SamlBundle\Http\RedirectBinding. ( Ignorable by Annotation )

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

167
        return $this->redirectBinding->/** @scrutinizer ignore-call */ createRedirectResponseFor($authenticationRequest);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
168
    }
169
170
    #[Route(
171
        path: '/second-factor/{secondFactorId}/self-vet-consume-assertion',
172
        name: 'ss_second_factor_self_vet_consume_assertion',
173
        methods: ['POST'],
174
    )]
175
    public function consumeSelfVetAssertion(Request $httpRequest, string $secondFactorId): \Symfony\Component\HttpFoundation\RedirectResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function consumeSelfVetAssertion()
Loading history...
176
    {
177
        $identity = $this->getIdentity();
178
        if (!$this->selfVetMarshaller->isAllowed($identity, $secondFactorId)) {
179
            throw new NotFoundHttpException();
180
        }
181
182
        if (!$this->session->has(self::SELF_VET_SESSION_ID)) {
183
            $this->logger->error(
184
                'Received an authentication response for self vetting a second factor, but no response was expected'
185
            );
186
            throw new AccessDeniedHttpException('Did not expect an authentication response');
187
        }
188
189
        $this->logger->notice('Received an authentication response for self vetting a second factor');
190
191
        /** @var SelfVetRequestId $initiatedRequestId */
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...
192
        $initiatedRequestId = $this->session->get(self::SELF_VET_SESSION_ID);
193
194
        $samlLogger = $this->samlLogger->forAuthentication($initiatedRequestId->requestId());
195
196
        $this->session->remove(self::SELF_VET_SESSION_ID);
197
198
        try {
199
            $assertion = $this->postBinding->processResponse(
200
                $httpRequest,
201
                $this->identityProvider,
202
                $this->serviceProvider
203
            );
204
205
            if (!InResponseTo::assertEquals($assertion, $initiatedRequestId->requestId())) {
206
                $samlLogger->error(
207
                    sprintf(
208
                        'Expected a response to the request with ID "%s", but the SAMLResponse was a response to a different request',
209
                        $initiatedRequestId
0 ignored issues
show
Bug introduced by
$initiatedRequestId of type Surfnet\StepupSelfServic...\Value\SelfVetRequestId is incompatible with the type double|integer|string expected by parameter $values of sprintf(). ( Ignorable by Annotation )

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

209
                        /** @scrutinizer ignore-type */ $initiatedRequestId
Loading history...
210
                    )
211
                );
212
                throw new AuthenticationException('Unexpected InResponseTo in SAMLResponse');
213
            }
214
            $candidateSecondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
215
            // Proof of possession of higher/equal LoA was successful, now apply the self vet command on Middleware
216
            $command = new SelfVetCommand();
217
            $command->identity = $this->getIdentity();
218
            $command->secondFactor = $candidateSecondFactor;
219
            $command->authoringLoa = $assertion->getAuthnContextClassRef();
220
221
            if ($this->secondFactorService->selfVet($command)) {
222
                $this->session->getFlashBag()->add('success', 'ss.self_vet.second_factor.alert.successful');
223
            } else {
224
                $this->session->getFlashBag()->add('error', 'ss.self_vet.second_factor.alert.failed');
225
            }
226
        } catch (Exception) {
227
            $this->session->getFlashBag()->add('error', 'ss.self_vet.second_factor.verification_failed');
228
        }
229
        return $this->redirectToRoute('ss_second_factor_list');
230
    }
231
}
232