Passed
Pull Request — main (#308)
by Paul
12:52 queued 05:50
created

SelfVetController::consumeSelfVetAssertion()   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
declare(strict_types = 1);
4
5
/**
6
 * Copyright 2021 SURFnet B.V.
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\Entity\IdentityProvider;
26
use Surfnet\SamlBundle\Entity\ServiceProvider;
27
use Surfnet\SamlBundle\Http\PostBinding;
28
use Surfnet\SamlBundle\Http\RedirectBinding;
29
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
30
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
31
use Surfnet\StepupBundle\Service\LoaResolutionService;
32
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
33
use Surfnet\StepupBundle\Value\Loa;
34
use Surfnet\StepupBundle\Value\SecondFactorType;
35
use Surfnet\StepupBundle\Value\VettingType;
36
use Surfnet\StepupSelfService\SelfServiceBundle\Command\SelfVetCommand;
37
use Surfnet\StepupSelfService\SelfServiceBundle\Service\AuthorizationService;
38
use Surfnet\StepupSelfService\SelfServiceBundle\Service\InstitutionConfigurationOptionsService;
39
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
40
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfVetMarshaller;
41
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...
42
use Surfnet\StepupSelfService\SelfServiceBundle\Value\SelfVetRequestId;
43
use Symfony\Component\HttpFoundation\RedirectResponse;
44
use Symfony\Component\HttpFoundation\Request;
45
use Symfony\Component\HttpFoundation\RequestStack;
46
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
47
use Symfony\Component\Routing\Attribute\Route;
48
use Symfony\Component\Security\Core\Exception\AuthenticationException;
49
use function sprintf;
50
51
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
52
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - Controllers are prone to higher coupling. This one is no exception
53
 */
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...
54
class SelfVetController extends Controller
55
{
56
    final public const SELF_VET_SESSION_ID = 'second_factor_self_vet_request_id';
57
58
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
59
        private readonly LoggerInterface                  $logger,
60
        InstitutionConfigurationOptionsService            $configurationOptionsService,
61
        private readonly TestAuthenticationRequestFactory $authenticationRequestFactory,
62
        private readonly SecondFactorService      $secondFactorService,
63
        private readonly SecondFactorTypeService  $secondFactorTypeService,
64
        private readonly SelfVetMarshaller        $selfVetMarshaller,
65
        private readonly AuthorizationService     $authorizationService,
66
        private readonly ServiceProvider          $serviceProvider,
67
        private readonly IdentityProvider         $identityProvider,
68
        private readonly RedirectBinding          $redirectBinding,
69
        private readonly PostBinding              $postBinding,
70
        private readonly LoaResolutionService     $loaResolutionService,
71
        private readonly SamlAuthenticationLogger $samlAuthenticationLogger,
72
        private readonly RequestStack             $requestStack,
73
    ) {
74
        parent::__construct($logger, $configurationOptionsService);
75
    }
76
77
    #[Route(
78
        path: '/second-factor/{secondFactorId}/self-vet-consume-assertion',
79
        name: 'ss_second_factor_self_vet_consume_assertion',
80
        methods: ['POST'],
81
    )]
82
    public function consumeSelfVetAssertion(Request $httpRequest, string $secondFactorId): RedirectResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function consumeSelfVetAssertion()
Loading history...
83
    {
84
        $identity = $this->getIdentity();
85
        if (!$this->selfVetMarshaller->isAllowed($identity, $secondFactorId)) {
86
            throw $this->createNotFoundException();
87
        }
88
89
        if (!$this->requestStack->getSession()->has(self::SELF_VET_SESSION_ID)) {
90
            $this->logger->error(
91
                'Received an authentication response for self vetting a second factor, but no response was expected'
92
            );
93
            throw new AccessDeniedHttpException('Did not expect an authentication response');
94
        }
95
96
        $this->logger->notice('Received an authentication response for self vetting a second factor');
97
98
        /** @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...
99
        $initiatedRequestId = $this->requestStack->getSession()->get(self::SELF_VET_SESSION_ID);
100
101
        $samlLogger = $this->samlAuthenticationLogger->forAuthentication($initiatedRequestId->requestId());
102
103
        $this->requestStack->getSession()->remove(self::SELF_VET_SESSION_ID);
104
105
        try {
106
            $assertion = $this->postBinding->processResponse(
107
                $httpRequest,
108
                $this->identityProvider,
109
                $this->serviceProvider
110
            );
111
112
            if (!InResponseTo::assertEquals($assertion, $initiatedRequestId->requestId())) {
113
                $samlLogger->error(
114
                    sprintf(
115
                        'Expected a response to the request with ID "%s", but the SAMLResponse was a response to a different request',
116
                        $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

116
                        /** @scrutinizer ignore-type */ $initiatedRequestId
Loading history...
117
                    )
118
                );
119
                throw new AuthenticationException('Unexpected InResponseTo in SAMLResponse');
120
            }
121
            $candidateSecondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
122
            // Proof of possession of higher/equal LoA was successful, now apply the self vet command on Middleware
123
            $command = new SelfVetCommand();
124
            $command->identity = $this->getIdentity();
125
            $command->secondFactor = $candidateSecondFactor;
126
            $command->authoringLoa = $assertion->getAuthnContextClassRef();
127
128
            if ($this->secondFactorService->selfVet($command)) {
129
                $this->addFlash('success', 'ss.self_vet.second_factor.alert.successful');
130
            } else {
131
                $this->addFlash('error', 'ss.self_vet.second_factor.alert.failed');
132
            }
133
        } catch (Exception) {
134
            $this->addFlash('error', 'ss.self_vet.second_factor.verification_failed');
135
        }
136
        return $this->redirectToRoute('ss_second_factor_list');
137
    }
138
139
    #[Route(
140
        path: '/second-factor/{secondFactorId}/self-vet',
141
        name: 'ss_second_factor_self_vet',
142
        methods: ['GET'],
143
    )]
144
    public function selfVet(string $secondFactorId): RedirectResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function selfVet()
Loading history...
145
    {
146
        $this->logger->notice('Starting self vet proof of possession using higher or equal LoA token');
147
        $identity = $this->getIdentity();
148
149
        if (!$this->selfVetMarshaller->isAllowed($identity, $secondFactorId)) {
150
            throw $this->createNotFoundException();
151
        }
152
153
154
        // Start with some assumptions that are overwritten with the correct values in the code below
155
        $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

155
        $candidateSecondFactorLoa = $this->loaResolutionService->getLoaByLevel(/** @scrutinizer ignore-type */ Loa::LOA_SELF_VETTED);
Loading history...
156
        $isSelfVetOfSatToken = false;
157
158
        // Determine if we are dealing with a SelfVet action of a SAT token
159
        if ($this->authorizationService->maySelfVetSelfAssertedTokens($identity)) {
160
            $this->logger->notice('Determined we are self vetting a token using a self-asserted token');
161
            $isSelfVetOfSatToken = true;
162
        }
163
164
        // When a regular self-vet action is performed grab the candidate second factor loa from the SF projection
165
        if (!$isSelfVetOfSatToken) {
166
            $this->logger->notice('Determined we are self vetting a token using an identity vetted token');
167
            $candidateSecondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
168
            $candidateSecondFactorLoa = $this->secondFactorTypeService->getLevel(
169
                new SecondFactorType($candidateSecondFactor->type),
170
                new VettingType(VettingType::TYPE_SELF_VET)
171
            );
172
            $candidateSecondFactorLoa = $this->loaResolutionService->getLoaByLevel($candidateSecondFactorLoa);
173
        }
174
        $this->logger->notice(
175
            sprintf(
176
                'Creating AuthNRequest requiring a LoA %s or higher token for self vetting.',
177
                $candidateSecondFactorLoa
178
            )
179
        );
180
        $authenticationRequest = $this->authenticationRequestFactory->createSecondFactorTestRequest(
181
            $identity->nameId,
182
            $candidateSecondFactorLoa
183
        );
184
185
        $this->requestStack->getSession()->set(
186
            self::SELF_VET_SESSION_ID,
187
            new SelfVetRequestId($authenticationRequest->getRequestId(), $secondFactorId)
188
        );
189
190
        $samlLogger = $this->samlAuthenticationLogger->forAuthentication($authenticationRequest->getRequestId());
191
        $samlLogger->notice('Sending authentication request to the second factor only IdP');
192
193
        return $this->redirectBinding->createResponseFor($authenticationRequest);
194
    }
195
}
196