Completed
Push — feature/catch-missing-epti ( 56ca6b...34b6bc )
by
unknown
02:59
created

GatewayController   B

Complexity

Total Complexity 21

Size/Duplication

Total Lines 316
Duplicated Lines 23.1 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 16
dl 73
loc 316
rs 8.4614
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
B ssoAction() 0 65 4
A proxySsoAction() 0 4 1
B consumeAssertionAction() 9 44 4
B respondAction() 0 45 3
B sendLoaCannotBeGivenAction() 25 25 1
B sendAuthenticationCancelledByUserAction() 29 29 1
A renderSamlResponse() 10 10 1
A render() 0 8 1
A getResponseContext() 0 11 2
A getResponseAsXML() 0 4 1
A createRequesterFailureResponse() 0 14 1
A createResponseFailureResponse() 0 12 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
 */
18
19
namespace Surfnet\StepupGateway\GatewayBundle\Controller;
20
21
use Exception;
22
use SAML2_Assertion;
23
use SAML2_Const;
24
use SAML2_Response;
25
use Surfnet\SamlBundle\SAML2\AuthnRequest;
26
use Surfnet\SamlBundle\SAML2\AuthnRequestFactory;
27
use Surfnet\StepupGateway\GatewayBundle\Exception\RuntimeException;
28
use Surfnet\StepupGateway\GatewayBundle\Saml\AssertionAdapter;
29
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
30
use Symfony\Component\HttpFoundation\Request;
31
use Symfony\Component\HttpFoundation\Response;
32
use Symfony\Component\HttpKernel\Exception\HttpException;
33
34
class GatewayController extends Controller
35
{
36
    const RESPONSE_CONTEXT_SERVICE_ID = 'gateway.proxy.response_context';
37
38
    public function ssoAction(Request $httpRequest)
39
    {
40
        /** @var \Psr\Log\LoggerInterface $logger */
41
        $logger = $this->get('logger');
42
        $logger->notice('Received AuthnRequest, started processing');
43
44
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
45
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
46
47
        try {
48
            $originalRequest = $redirectBinding->receiveSignedAuthnRequestFrom($httpRequest);
49
        } catch (Exception $e) {
50
            $logger->critical(sprintf('Could not process Request, error: "%s"', $e->getMessage()));
51
52
            return $this->render('unrecoverableError');
53
        }
54
55
        $originalRequestId = $originalRequest->getRequestId();
56
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
57
        $logger->notice(sprintf(
58
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
59
            $originalRequest->getServiceProvider(),
60
            $originalRequest->getRequestId()
61
        ));
62
63
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler $stateHandler */
64
        $stateHandler = $this->get('gateway.proxy.state_handler');
65
        $stateHandler
66
            ->setRequestId($originalRequestId)
67
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
68
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''))
69
            ->setResponseAction('SurfnetStepupGatewayGatewayBundle:Gateway:respond')
70
            ->setResponseContextServiceId(static::RESPONSE_CONTEXT_SERVICE_ID);
71
72
        // check if the requested Loa is supported
73
        $requiredLoa = $originalRequest->getAuthenticationContextClassRef();
74
        if ($requiredLoa && !$this->get('surfnet_stepup.service.loa_resolution')->hasLoa($requiredLoa)) {
75
            $logger->info(sprintf(
76
                'Requested required Loa "%s" does not exist, sending response with status Requester Error',
77
                $requiredLoa
78
            ));
79
80
            $response = $this->createRequesterFailureResponse();
81
82
            return $this->renderSamlResponse('consumeAssertion', $response);
83
        }
84
85
        $stateHandler->setRequiredLoaIdentifier($requiredLoa);
86
87
        $proxyRequest = AuthnRequestFactory::createNewRequest(
88
            $this->get('surfnet_saml.hosted.service_provider'),
89
            $this->get('surfnet_saml.remote.idp')
90
        );
91
92
        $proxyRequest->setScoping([$originalRequest->getServiceProvider()]);
93
        $stateHandler->setGatewayRequestId($proxyRequest->getRequestId());
94
95
        $logger->notice(sprintf(
96
            'Sending Proxy AuthnRequest with request ID: "%s" for original AuthnRequest "%s"',
97
            $proxyRequest->getRequestId(),
98
            $originalRequest->getRequestId()
99
        ));
100
101
        return $redirectBinding->createRedirectResponseFor($proxyRequest);
102
    }
103
104
    public function proxySsoAction()
105
    {
106
        throw new HttpException(418, 'Not Yet Implemented');
107
    }
108
109
    /**
110
     * @param Request $request
111
     * @return \Symfony\Component\HttpFoundation\Response
112
     */
113
    public function consumeAssertionAction(Request $request)
114
    {
115
        $responseContext = $this->getResponseContext();
116
        $originalRequestId = $responseContext->getInResponseTo();
117
118
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
119
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
120
        $logger->notice('Received SAMLResponse, attempting to process for Proxy Response');
121
122
        try {
123
            /** @var \SAML2_Assertion $assertion */
124
            $assertion = $this->get('surfnet_saml.http.post_binding')->processResponse(
125
                $request,
126
                $this->get('surfnet_saml.remote.idp'),
127
                $this->get('surfnet_saml.hosted.service_provider')
128
            );
129
        } catch (Exception $exception) {
130
            $logger->error(sprintf('Could not process received Response, error: "%s"', $exception->getMessage()));
131
132
            $response = $this->createResponseFailureResponse($responseContext);
133
134
            return $this->renderSamlResponse('unprocessableResponse', $response);
135
        }
136
137
        $adaptedAssertion = new AssertionAdapter($assertion);
138
        $expectedInResponseTo = $responseContext->getExpectedInResponseTo();
139 View Code Duplication
        if (!$adaptedAssertion->inResponseToMatches($expectedInResponseTo)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
140
            $logger->critical(sprintf(
141
                'Received Response with unexpected InResponseTo: "%s", %s',
142
                $adaptedAssertion->getInResponseTo(),
143
                ($expectedInResponseTo ? 'expected "' . $expectedInResponseTo . '"' : ' no response expected')
144
            ));
145
146
            return $this->render('unrecoverableError');
147
        }
148
149
        $logger->notice('Successfully processed SAMLResponse');
150
151
        $responseContext->saveAssertion($assertion);
152
153
        $logger->notice(sprintf('Forwarding to second factor controller for loa determination and handling'));
154
155
        return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:selectSecondFactorForVerification');
156
    }
157
158
    public function respondAction()
159
    {
160
        $responseContext = $this->getResponseContext();
161
        $originalRequestId = $responseContext->getInResponseTo();
162
163
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
164
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
165
        $logger->notice('Creating Response');
166
167
        $grantedLoa = null;
168
        if ($responseContext->isSecondFactorVerified()) {
169
            $secondFactor = $this->get('gateway.service.second_factor_service')->findByUuid(
170
                $responseContext->getSelectedSecondFactor()
171
            );
172
173
            $grantedLoa = $this->get('surfnet_stepup.service.loa_resolution')->getLoaByLevel(
174
                $secondFactor->getLoaLevel()
175
            );
176
        }
177
178
        /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ProxyResponseService $proxyResponseService */
179
        $proxyResponseService = $this->get('gateway.service.response_proxy');
180
        try {
181
            $response = $proxyResponseService->createProxyResponse(
182
                $responseContext->reconstituteAssertion(),
183
                $responseContext->getServiceProvider(),
0 ignored issues
show
Bug introduced by
It seems like $responseContext->getServiceProvider() can be null; however, createProxyResponse() 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...
184
                (string)$grantedLoa
185
            );
186
        } catch (RuntimeException $e) {
187
            $logger->error($e->getMessage());
188
            return $this->render('unrecoverableError', [
189
                'message' => $e->getMessage()
190
            ]);
191
        }
192
193
        $responseContext->responseSent();
194
195
        $logger->notice(sprintf(
196
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
197
            $responseContext->getInResponseTo(),
198
            $response->getId()
199
        ));
200
201
        return $this->renderSamlResponse('consumeAssertion', $response);
202
    }
203
204 View Code Duplication
    public function sendLoaCannotBeGivenAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
205
    {
206
        $responseContext = $this->getResponseContext();
207
        $originalRequestId = $responseContext->getInResponseTo();
208
209
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
210
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
211
        $logger->notice('Loa cannot be given, creating Response with NoAuthnContext status');
212
213
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
214
        $responseBuilder = $this->get('gateway.proxy.response_builder');
215
216
        $response = $responseBuilder
217
            ->createNewResponse($responseContext)
218
            ->setResponseStatus(SAML2_Const::STATUS_RESPONDER, SAML2_Const::STATUS_NO_AUTHN_CONTEXT)
219
            ->get();
220
221
        $logger->notice(sprintf(
222
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
223
            $responseContext->getInResponseTo(),
224
            $response->getId()
225
        ));
226
227
        return $this->renderSamlResponse('consumeAssertion', $response);
228
    }
229
230 View Code Duplication
    public function sendAuthenticationCancelledByUserAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
231
    {
232
        $responseContext = $this->getResponseContext();
233
        $originalRequestId = $responseContext->getInResponseTo();
234
235
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
236
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
237
        $logger->notice('Authentication was cancelled by the user, creating Response with AuthnFailed status');
238
239
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
240
        $responseBuilder = $this->get('gateway.proxy.response_builder');
241
242
        $response = $responseBuilder
243
            ->createNewResponse($responseContext)
244
            ->setResponseStatus(
245
                SAML2_Const::STATUS_RESPONDER,
246
                SAML2_Const::STATUS_AUTHN_FAILED,
247
                'Authentication cancelled by user'
248
            )
249
            ->get();
250
251
        $logger->notice(sprintf(
252
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
253
            $responseContext->getInResponseTo(),
254
            $response->getId()
255
        ));
256
257
        return $this->renderSamlResponse('consumeAssertion', $response);
258
    }
259
260
    /**
261
     * @param string         $view
262
     * @param SAML2_Response $response
263
     * @return Response
264
     */
265 View Code Duplication
    public function renderSamlResponse($view, SAML2_Response $response)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
266
    {
267
        $responseContext = $this->getResponseContext();
268
269
        return $this->render($view, [
270
            'acu'        => $responseContext->getDestination(),
271
            'response'   => $this->getResponseAsXML($response),
272
            'relayState' => $responseContext->getRelayState()
273
        ]);
274
    }
275
276
    /**
277
     * @param string   $view
278
     * @param array    $parameters
279
     * @param Response $response
0 ignored issues
show
Documentation introduced by
Should the type for parameter $response not be null|Response?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
280
     * @return Response
281
     */
282
    public function render($view, array $parameters = array(), Response $response = null)
283
    {
284
        return parent::render(
285
            'SurfnetStepupGatewayGatewayBundle:Gateway:' . $view . '.html.twig',
286
            $parameters,
287
            $response
288
        );
289
    }
290
291
    /**
292
     * @return \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext
293
     */
294
    public function getResponseContext()
295
    {
296
        $stateHandler = $this->get('gateway.proxy.state_handler');
297
        $responseContextServiceId = $stateHandler->getResponseContextServiceId();
298
299
        if (!$responseContextServiceId) {
300
            return $this->get(static::RESPONSE_CONTEXT_SERVICE_ID);
301
        }
302
303
        return $this->get($responseContextServiceId);
304
    }
305
306
    /**
307
     * @param SAML2_Response $response
308
     * @return string
309
     */
310
    private function getResponseAsXML(SAML2_Response $response)
311
    {
312
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
313
    }
314
315
    /**
316
     * @return SAML2_Response
317
     */
318
    private function createRequesterFailureResponse()
319
    {
320
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
321
        $responseBuilder = $this->get('gateway.proxy.response_builder');
322
        $context = $this->getResponseContext();
323
324
        $response = $responseBuilder
325
            ->createNewResponse($context)
326
            ->setResponseStatus(SAML2_Const::STATUS_REQUESTER, SAML2_Const::STATUS_REQUEST_UNSUPPORTED)
327
            ->get();
328
329
        return $response;
330
331
    }
332
333
    /**
334
     * @param $context
335
     * @return SAML2_Response
336
     */
337
    private function createResponseFailureResponse($context)
338
    {
339
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
340
        $responseBuilder = $this->get('gateway.proxy.response_builder');
341
342
        $response = $responseBuilder
343
            ->createNewResponse($context)
344
            ->setResponseStatus(SAML2_Const::STATUS_RESPONDER)
345
            ->get();
346
347
        return $response;
348
    }
349
}
350