Passed
Pull Request — main (#308)
by Paul
29:45 queued 20:02
created

SamlController::consumeAssertion()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 58
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 36
c 2
b 0
f 0
nc 9
nop 1
dl 0
loc 58
rs 8.7217

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 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 Surfnet\SamlBundle\Metadata\MetadataFactory;
25
use Surfnet\StepupBundle\Service\LoaResolutionService;
26
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
27
use Psr\Log\LoggerInterface;
28
use Surfnet\SamlBundle\Http\XMLResponse;
29
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
30
use Surfnet\StepupBundle\Value\Loa;
31
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenState;
32
use Surfnet\StepupSelfService\SelfServiceBundle\Value\SelfVetRequestId;
33
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
34
use Symfony\Component\HttpFoundation\RedirectResponse;
35
use Symfony\Component\HttpFoundation\Request;
36
use Symfony\Component\HttpFoundation\RequestStack;
37
use Symfony\Component\HttpFoundation\Response;
38
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
39
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
40
use Symfony\Component\Routing\Attribute\Route;
41
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
42
use Symfony\Component\Security\Core\Exception\AuthenticationException;
43
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
44
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...
45
use Surfnet\SamlBundle\Http\RedirectBinding;
46
use Surfnet\SamlBundle\Http\PostBinding;
47
48
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
49
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) -- Hard to reduce due to different commands and queries used.
50
 * TODO: Split op in smaller controllers
51
 */
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...
52
class SamlController extends AbstractController
53
{
54
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
55
        private readonly LoggerInterface                  $logger,
56
        private readonly SecondFactorService              $secondFactorService,
57
        private readonly RequestStack                     $requestStack,
58
        private readonly LoaResolutionService             $loaResolutionService,
59
        private readonly MetadataFactory                  $metadataFactory,
60
        private readonly SamlAuthenticationLogger         $samlAuthenticationLogger,
61
        private readonly TestAuthenticationRequestFactory $testAuthenticationRequestFactory,
62
        private readonly RedirectBinding                  $redirectBinding,
63
        private readonly PostBinding                      $postBinding,
64
    ) {
65
    }
66
67
    /**
68
     * A SelfService user is able to test it's token in this endpoint
69
     *
70
     * @throws NotFoundHttpException
71
     * @throws AccessDeniedException
72
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
73
    #[Route(path:'/second-factor/test', name:'ss_second_factor_test', methods:  ['GET'])]
74
    public function testSecondFactor(): RedirectResponse
75
    {
76
        $this->logger->notice('Starting second factor test');
77
78
        $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

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

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