Passed
Pull Request — main (#308)
by Paul
16:16 queued 09:55
created

SelfVetController   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 149
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 82
dl 0
loc 149
rs 10
c 1
b 0
f 0
wmc 11

3 Methods

Rating   Name   Duplication   Size   Complexity  
B consumeSelfVetAssertion() 0 69 6
A selfVet() 0 55 4
A __construct() 0 17 1
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->requestStack
130
                    ->getSession()
131
                    ->getFlashBag()
132
                    ->add('success', 'ss.self_vet.second_factor.alert.successful');
133
            } else {
134
                $this->requestStack
135
                    ->getSession()
136
                    ->getFlashBag()
137
                    ->add('error', 'ss.self_vet.second_factor.alert.failed');
138
            }
139
        } catch (Exception) {
140
            $this->requestStack
141
                ->getSession()
142
                ->getFlashBag()
143
                ->add('error', 'ss.self_vet.second_factor.verification_failed');
144
        }
145
        return $this->redirectToRoute('ss_second_factor_list');
146
    }
147
148
    #[Route(
149
        path: '/second-factor/{secondFactorId}/self-vet',
150
        name: 'ss_second_factor_self_vet',
151
        methods: ['GET'],
152
    )]
153
    public function selfVet(string $secondFactorId): RedirectResponse
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function selfVet()
Loading history...
154
    {
155
        $this->logger->notice('Starting self vet proof of possession using higher or equal LoA token');
156
        $identity = $this->getIdentity();
157
158
        if (!$this->selfVetMarshaller->isAllowed($identity, $secondFactorId)) {
159
            throw $this->createNotFoundException();
160
        }
161
162
163
        // Start with some assumptions that are overwritten with the correct values in the code below
164
        $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

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