Passed
Pull Request — main (#308)
by Paul
18:42 queued 09:10
created

SamlController   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 60
c 4
b 0
f 0
dl 0
loc 126
rs 10
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A testSecondFactor() 0 32 3
B consumeAssertion() 0 59 6
A metadata() 0 8 1
A __construct() 0 13 1
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\Entity\IdentityProvider;
26
use Surfnet\SamlBundle\Entity\ServiceProvider;
27
use Surfnet\SamlBundle\Http\PostBinding;
28
use Surfnet\SamlBundle\Http\RedirectBinding;
29
use Surfnet\SamlBundle\Http\XMLResponse;
30
use Surfnet\SamlBundle\Metadata\MetadataFactory;
31
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
32
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
33
use Surfnet\StepupBundle\Service\LoaResolutionService;
34
use Surfnet\StepupBundle\Value\Loa;
35
use Surfnet\StepupSelfService\SelfServiceBundle\Controller\SelfVet\SelfVetController;
36
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
37
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenState;
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\Bundle\FrameworkBundle\Controller\AbstractController;
41
use Symfony\Component\HttpFoundation\RedirectResponse;
42
use Symfony\Component\HttpFoundation\Request;
43
use Symfony\Component\HttpFoundation\RequestStack;
44
use Symfony\Component\HttpFoundation\Response;
45
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
46
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
47
use Symfony\Component\Routing\Attribute\Route;
48
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
49
use Symfony\Component\Security\Core\Exception\AuthenticationException;
50
51
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
52
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) -- Hard to reduce due to different commands and queries used.
53
 * @SuppressWarnings(PHPMD.ExcessiveParameterList) -- Many fields/dependencies are required in controllers.
54
 * Previously they were yanked from the container via $this->get(),
55
 * implicit coupling has been made explicit with this change
56
 */
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...
57
class SamlController extends AbstractController
58
{
59
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
60
        private readonly LoggerInterface                  $logger,
61
        private readonly SecondFactorService              $secondFactorService,
62
        private readonly RequestStack                     $requestStack,
63
        private readonly LoaResolutionService             $loaResolutionService,
64
        private readonly MetadataFactory                  $metadataFactory,
65
        private readonly SamlAuthenticationLogger         $samlAuthenticationLogger,
66
        private readonly TestAuthenticationRequestFactory $testAuthenticationRequestFactory,
67
        private readonly RedirectBinding                  $redirectBinding,
68
        private readonly PostBinding                      $postBinding,
69
        private readonly ServiceProvider $serviceProvider,
70
        private readonly IdentityProvider $testIdentityProvider,
71
    ) {
72
    }
73
74
    /**
75
     * A SelfService user is able to test it's token in this endpoint
76
     *
77
     * @throws NotFoundHttpException
78
     * @throws AccessDeniedException
79
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
80
    #[Route(path: '/second-factor/test', name: 'ss_second_factor_test', methods: ['GET'])]
81
    public function testSecondFactor(): RedirectResponse
82
    {
83
        $this->logger->notice('Starting second factor test');
84
85
        $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

85
        $identity = $this->getUser()->/** @scrutinizer ignore-call */ getIdentity();
Loading history...
86
87
        $vettedSecondFactors = $this->secondFactorService->findVettedByIdentity($identity->id);
88
        if (!$vettedSecondFactors || $vettedSecondFactors->getTotalItems() === 0) {
89
            $this->logger->error(
90
                sprintf(
91
                    'Identity "%s" tried to test a second factor, but does not own a suitable vetted token.',
92
                    $identity->id,
93
                ),
94
            );
95
96
            throw new NotFoundHttpException();
97
        }
98
99
100
        // By requesting LoA 1.5 any relevant token can be tested (LoA 2 and 3)
101
        $authenticationRequest = $this->testAuthenticationRequestFactory->createSecondFactorTestRequest(
102
            $identity->nameId,
103
            $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

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