Passed
Push — feature/symfony6-upgrade ( 949a66...647b90 )
by Paul
07:17
created

SamlController::metadata()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
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
 */
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...
18
19
namespace Surfnet\StepupSelfService\SelfServiceBundle\Controller;
20
21
use Exception;
22
use Surfnet\SamlBundle\Metadata\MetadataFactory;
23
use Surfnet\StepupBundle\Service\LoaResolutionService;
24
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SecondFactorService;
25
use Psr\Log\LoggerInterface;
26
use Surfnet\SamlBundle\Http\XMLResponse;
27
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
28
use Surfnet\StepupBundle\Value\Loa;
29
use Surfnet\StepupSelfService\SelfServiceBundle\Service\InstitutionConfigurationOptionsService;
30
use Surfnet\StepupSelfService\SelfServiceBundle\Service\SelfAssertedTokens\RecoveryTokenState;
31
use Surfnet\StepupSelfService\SelfServiceBundle\Value\SelfVetRequestId;
32
use Symfony\Component\HttpFoundation\RedirectResponse;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\RequestStack;
35
use Symfony\Component\HttpFoundation\Response;
36
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
37
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
38
use Symfony\Component\Routing\Annotation\Route;
39
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
40
use Symfony\Component\Security\Core\Exception\AuthenticationException;
41
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
42
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...
43
use Surfnet\SamlBundle\Http\RedirectBinding;
44
use Surfnet\SamlBundle\Http\PostBinding;
45
46
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
47
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects) -- Hard to reduce due to different commands and queries used.
48
 */
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...
49
class SamlController extends Controller
50
{
51
52
    public function __construct(
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
53
        private readonly LoggerInterface                  $logger,
54
        InstitutionConfigurationOptionsService            $configurationOptionsService,
55
        private readonly SecondFactorService              $secondFactorService,
56
        private readonly RequestStack                     $requestStack,
57
        private readonly LoaResolutionService             $loaResolutionService,
58
        private readonly MetadataFactory                  $metadataFactory,
59
        private readonly SamlAuthenticationLogger         $samlAuthenticationLogger,
60
        private readonly TestAuthenticationRequestFactory $testAuthenticationRequestFactory,
61
        private readonly RedirectBinding                  $redirectBinding,
62
        private readonly PostBinding                      $postBinding,
63
    ) {
64
        parent::__construct($logger, $configurationOptionsService);
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
79
        $identity = $this->getIdentity();
80
81
        $vettedSecondFactors = $this->secondFactorService->findVettedByIdentity($identity->id);
0 ignored issues
show
Bug introduced by
It seems like $identity->id can also be of type null; however, parameter $identityId of Surfnet\StepupSelfServic...:findVettedByIdentity() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

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

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