Completed
Pull Request — develop (#227)
by Michiel
04:22 queued 02:14
created

SelfVetController   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 163
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 21

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 21
dl 0
loc 163
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 25 1
A selfVetAction() 0 44 3
B consumeSelfVetAssertionAction() 0 51 5
1
<?php
2
3
/**
4
 * Copyright 2021 SURF 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
 */
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\SecondFactorType;
32
use Surfnet\StepupSelfService\SelfServiceBundle\Command\SelfVetCommand;
33
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
34
use Surfnet\StepupSelfService\SelfServiceBundle\Service\TestSecondFactor\TestAuthenticationRequestFactory;
35
use Surfnet\StepupSelfService\SelfServiceBundle\Value\SelfVetRequestId;
36
use Symfony\Component\HttpFoundation\RedirectResponse;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpFoundation\Session\SessionInterface;
39
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
40
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
41
use Symfony\Component\Security\Core\Exception\AuthenticationException;
42
use function sprintf;
43
44
/**
45
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - Controllers are prone to higher coupling. This one is no exception
46
 */
47
class SelfVetController extends Controller
48
{
49
    public const SELF_VET_SESSION_ID = 'second_factor_self_vet_request_id';
50
51
    /** @var TestAuthenticationRequestFactory */
52
    public $authenticationRequestFactory;
53
54
    /** @var SecondFactorService */
55
    public $secondFactorService;
56
57
    /** @var SecondFactorTypeService */
58
    public $secondFactorTypeService;
59
60
    /** @var ServiceProvider */
61
    private $serviceProvider;
62
63
    /** @var IdentityProvider */
64
    private $identityProvider;
65
66
    /** @var RedirectBinding */
67
    public $redirectBinding;
68
69
    /** @var PostBinding */
70
    public $postBinding;
71
72
    /** @var LoaResolutionService */
73
    public $loaResolutionService;
74
75
    /** @var SamlAuthenticationLogger */
76
    public $samlLogger;
77
78
    /** @var SessionInterface */
79
    public $session;
80
81
    /** @var LoggerInterface */
82
    public $logger;
83
84
    /**
85
     * @@SuppressWarnings(PHPMD.ExcessiveParameterList)
86
     */
87
    public function __construct(
88
        TestAuthenticationRequestFactory $authenticationRequestFactory,
89
        SecondFactorService $secondFactorService,
90
        SecondFactorTypeService $secondFactorTypeService,
91
        ServiceProvider $serviceProvider,
92
        IdentityProvider $identityProvider,
93
        RedirectBinding $redirectBinding,
94
        PostBinding $postBinding,
95
        LoaResolutionService $loaResolutionService,
96
        SamlAuthenticationLogger $samlAuthenticationLogger,
97
        SessionInterface $session,
98
        LoggerInterface $logger
99
    ) {
100
        $this->authenticationRequestFactory = $authenticationRequestFactory;
101
        $this->secondFactorService = $secondFactorService;
102
        $this->secondFactorTypeService = $secondFactorTypeService;
103
        $this->serviceProvider = $serviceProvider;
104
        $this->identityProvider = $identityProvider;
105
        $this->redirectBinding = $redirectBinding;
106
        $this->postBinding = $postBinding;
107
        $this->loaResolutionService = $loaResolutionService;
108
        $this->samlLogger = $samlAuthenticationLogger;
109
        $this->session = $session;
110
        $this->logger = $logger;
111
    }
112
113
    public function selfVetAction(string $secondFactorId): RedirectResponse
114
    {
115
        $this->logger->notice('Starting self vet proof of possession using higher or equal LoA token');
116
117
        $identity = $this->getIdentity();
118
119
        $vettedSecondFactors = $this->secondFactorService->findVettedByIdentity($identity->id);
120
        if (!$vettedSecondFactors || $vettedSecondFactors->getTotalItems() === 0) {
121
            $this->logger->error(
122
                sprintf(
123
                    'Identity "%s" tried to self vet a second factor, but does not own a suitable vetted token.',
124
                    $identity->id
125
                )
126
            );
127
128
            throw new NotFoundHttpException();
129
        }
130
        $candidateSecondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
131
        $candidateSecondFactorLoa = $this->secondFactorTypeService->getLevel(
132
            new SecondFactorType($candidateSecondFactor->type)
133
        );
134
        $candidateSecondFactorLoa = $this->loaResolutionService->getLoaByLevel($candidateSecondFactorLoa);
135
136
        $this->logger->notice(
137
            sprintf(
138
                'Creating AuthNRequest requiring a LoA %s or higher token for self vetting.',
139
                $candidateSecondFactorLoa
140
            )
141
        );
142
        $authenticationRequest = $this->authenticationRequestFactory->createSecondFactorTestRequest(
143
            $identity->nameId,
144
            $candidateSecondFactorLoa
0 ignored issues
show
Bug introduced by
It seems like $candidateSecondFactorLoa defined by $this->loaResolutionServ...ndidateSecondFactorLoa) on line 134 can be null; however, Surfnet\StepupSelfServic...condFactorTestRequest() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
145
        );
146
147
        $this->session->set(
148
            self::SELF_VET_SESSION_ID,
149
            new SelfVetRequestId($authenticationRequest->getRequestId(), $secondFactorId)
150
        );
151
152
        $samlLogger = $this->samlLogger->forAuthentication($authenticationRequest->getRequestId());
153
        $samlLogger->notice('Sending authentication request to the second factor only IdP');
154
155
        return $this->redirectBinding->createRedirectResponseFor($authenticationRequest);
0 ignored issues
show
Deprecated Code introduced by
The method Surfnet\SamlBundle\Http\...teRedirectResponseFor() has been deprecated with message: Please use the `createResponseFor` method instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
156
    }
157
158
    public function consumeSelfVetAssertionAction(Request $httpRequest, string $secondFactorId)
159
    {
160
        if (!$this->session->has(self::SELF_VET_SESSION_ID)) {
161
            $this->logger->error(
162
                'Received an authentication response for self vetting a second factor, but no response was expected'
163
            );
164
            throw new AccessDeniedHttpException('Did not expect an authentication response');
165
        }
166
167
        $this->logger->notice('Received an authentication response for self vetting a second factor');
168
169
        /** @var SelfVetRequestId $initiatedRequestId */
170
        $initiatedRequestId = $this->session->get(self::SELF_VET_SESSION_ID);
171
172
        $samlLogger = $this->samlLogger->forAuthentication($initiatedRequestId->requestId());
173
174
        $this->session->remove(self::SELF_VET_SESSION_ID);
175
176
        try {
177
            $assertion = $this->postBinding->processResponse(
178
                $httpRequest,
179
                $this->identityProvider,
180
                $this->serviceProvider
181
            );
182
183
            if (!InResponseTo::assertEquals($assertion, $initiatedRequestId->requestId())) {
184
                $samlLogger->error(
185
                    sprintf(
186
                        'Expected a response to the request with ID "%s", but the SAMLResponse was a response to a different request',
187
                        $initiatedRequestId
188
                    )
189
                );
190
                throw new AuthenticationException('Unexpected InResponseTo in SAMLResponse');
191
            }
192
            $candidateSecondFactor = $this->secondFactorService->findOneVerified($secondFactorId);
193
            // Proof of possession of higher/equal LoA was successful, now apply the self vet command on Middleware
194
            $command = new SelfVetCommand();
195
            $command->identity = $this->getIdentity();
196
            $command->secondFactor = $candidateSecondFactor;
197
            $command->authoringLoa = $assertion->getAuthnContextClassRef();
198
199
            if ($this->secondFactorService->selfVet($command)) {
200
                $this->session->getFlashBag()->add('success', 'ss.second_factor.self_vet.alert.successful');
201
            } else {
202
                $this->session->getFlashBag()->add('error', 'ss.second_factor.self_vet.alert.failed');
203
            }
204
        } catch (Exception $exception) {
205
            $this->session->getFlashBag()->add('error', 'ss.self_vet_second_factor.verification_failed');
206
        }
207
        return $this->redirectToRoute('ss_second_factor_list');
208
    }
209
}
210