Completed
Push — feature/generic-error-pages ( 9248b8 )
by
unknown
03:54
created

GatewayController::ssoAction()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 59
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 59
rs 9.597
cc 3
eloc 36
nc 2
nop 1

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
/**
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\Constants;
23
use SAML2\Response as SAMLResponse;
24
use Surfnet\SamlBundle\SAML2\AuthnRequest;
25
use Surfnet\SamlBundle\SAML2\AuthnRequestFactory;
26
use Surfnet\StepupGateway\GatewayBundle\Exception\RuntimeException;
27
use Surfnet\StepupGateway\GatewayBundle\Saml\AssertionAdapter;
28
use Surfnet\StepupGateway\GatewayBundle\Saml\Exception\UnknownInResponseToException;
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
        $originalRequest = $redirectBinding->receiveSignedAuthnRequestFrom($httpRequest);
48
49
        $originalRequestId = $originalRequest->getRequestId();
50
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
51
        $logger->notice(sprintf(
52
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
53
            $originalRequest->getServiceProvider(),
54
            $originalRequest->getRequestId()
55
        ));
56
57
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler $stateHandler */
58
        $stateHandler = $this->get('gateway.proxy.state_handler');
59
        $stateHandler
60
            ->setRequestId($originalRequestId)
61
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
0 ignored issues
show
Bug introduced by
It seems like $originalRequest->getServiceProvider() targeting Surfnet\SamlBundle\SAML2...t::getServiceProvider() can also be of type null or object<SAML2\XML\saml\Issuer>; however, Surfnet\StepupGateway\Ga...equestServiceProvider() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
62
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''))
63
            ->setResponseAction('SurfnetStepupGatewayGatewayBundle:Gateway:respond')
64
            ->setResponseContextServiceId(static::RESPONSE_CONTEXT_SERVICE_ID);
65
66
        // check if the requested Loa is supported
67
        $requiredLoa = $originalRequest->getAuthenticationContextClassRef();
68
        if ($requiredLoa && !$this->get('surfnet_stepup.service.loa_resolution')->hasLoa($requiredLoa)) {
69
            $logger->info(sprintf(
70
                'Requested required Loa "%s" does not exist, sending response with status Requester Error',
71
                $requiredLoa
72
            ));
73
74
            $response = $this->createRequesterFailureResponse();
75
76
            return $this->renderSamlResponse('consumeAssertion', $response);
77
        }
78
79
        $stateHandler->setRequiredLoaIdentifier($requiredLoa);
80
81
        $proxyRequest = AuthnRequestFactory::createNewRequest(
82
            $this->get('surfnet_saml.hosted.service_provider'),
83
            $this->get('surfnet_saml.remote.idp')
84
        );
85
86
        $proxyRequest->setScoping([$originalRequest->getServiceProvider()]);
87
        $stateHandler->setGatewayRequestId($proxyRequest->getRequestId());
88
89
        $logger->notice(sprintf(
90
            'Sending Proxy AuthnRequest with request ID: "%s" for original AuthnRequest "%s"',
91
            $proxyRequest->getRequestId(),
92
            $originalRequest->getRequestId()
93
        ));
94
95
        return $redirectBinding->createResponseFor($proxyRequest);
96
    }
97
98
    public function proxySsoAction()
99
    {
100
        throw new HttpException(418, 'Not Yet Implemented');
101
    }
102
103
    /**
104
     * @param Request $request
105
     * @return \Symfony\Component\HttpFoundation\Response
106
     */
107
    public function consumeAssertionAction(Request $request)
108
    {
109
        $responseContext = $this->getResponseContext();
110
        $originalRequestId = $responseContext->getInResponseTo();
111
112
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
113
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
114
        $logger->notice('Received SAMLResponse, attempting to process for Proxy Response');
115
116
        try {
117
            /** @var \SAML2\Assertion $assertion */
118
            $assertion = $this->get('surfnet_saml.http.post_binding')->processResponse(
119
                $request,
120
                $this->get('surfnet_saml.remote.idp'),
121
                $this->get('surfnet_saml.hosted.service_provider')
122
            );
123
        } catch (Exception $exception) {
124
            $logger->error(sprintf('Could not process received Response, error: "%s"', $exception->getMessage()));
125
126
            $response = $this->createResponseFailureResponse($responseContext);
127
128
            return $this->renderSamlResponse('unprocessableResponse', $response);
129
        }
130
131
        $adaptedAssertion = new AssertionAdapter($assertion);
132
        $expectedInResponseTo = $responseContext->getExpectedInResponseTo();
133
        if (!$adaptedAssertion->inResponseToMatches($expectedInResponseTo)) {
134
            throw new UnknownInResponseToException(
135
                $adaptedAssertion->getInResponseTo(),
136
                $expectedInResponseTo
137
            );
138
        }
139
140
        $logger->notice('Successfully processed SAMLResponse');
141
142
        $responseContext->saveAssertion($assertion);
143
144
        $logger->notice(sprintf('Forwarding to second factor controller for loa determination and handling'));
145
146
        return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:selectSecondFactorForVerification');
147
    }
148
149
    public function respondAction()
150
    {
151
        $responseContext = $this->getResponseContext();
152
        $originalRequestId = $responseContext->getInResponseTo();
153
154
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
155
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
156
        $logger->notice('Creating Response');
157
158
        $grantedLoa = null;
159
        if ($responseContext->isSecondFactorVerified()) {
160
            $secondFactor = $this->get('gateway.service.second_factor_service')->findByUuid(
161
                $responseContext->getSelectedSecondFactor()
162
            );
163
164
            $secondFactorTypeService = $this->get('surfnet_stepup.service.second_factor_type');
165
            $grantedLoa = $this->get('surfnet_stepup.service.loa_resolution')->getLoaByLevel(
166
                $secondFactor->getLoaLevel($secondFactorTypeService)
167
            );
168
        }
169
170
        /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ProxyResponseService $proxyResponseService */
171
        $proxyResponseService = $this->get('gateway.service.response_proxy');
172
173
        $response = $proxyResponseService->createProxyResponse(
174
            $responseContext->reconstituteAssertion(),
175
            $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...
176
            (string)$grantedLoa
177
        );
178
179
        $responseContext->responseSent();
180
181
        $logger->notice(sprintf(
182
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
183
            $responseContext->getInResponseTo(),
184
            $response->getId()
185
        ));
186
187
        return $this->renderSamlResponse('consumeAssertion', $response);
188
    }
189
190 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...
191
    {
192
        $responseContext = $this->getResponseContext();
193
        $originalRequestId = $responseContext->getInResponseTo();
194
195
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
196
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
197
        $logger->notice('Loa cannot be given, creating Response with NoAuthnContext status');
198
199
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
200
        $responseBuilder = $this->get('gateway.proxy.response_builder');
201
202
        $response = $responseBuilder
203
            ->createNewResponse($responseContext)
204
            ->setResponseStatus(Constants::STATUS_RESPONDER, Constants::STATUS_NO_AUTHN_CONTEXT)
205
            ->get();
206
207
        $logger->notice(sprintf(
208
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
209
            $responseContext->getInResponseTo(),
210
            $response->getId()
211
        ));
212
213
        return $this->renderSamlResponse('consumeAssertion', $response);
214
    }
215
216 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...
217
    {
218
        $responseContext = $this->getResponseContext();
219
        $originalRequestId = $responseContext->getInResponseTo();
220
221
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
222
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
223
        $logger->notice('Authentication was cancelled by the user, creating Response with AuthnFailed status');
224
225
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
226
        $responseBuilder = $this->get('gateway.proxy.response_builder');
227
228
        $response = $responseBuilder
229
            ->createNewResponse($responseContext)
230
            ->setResponseStatus(
231
                Constants::STATUS_RESPONDER,
232
                Constants::STATUS_AUTHN_FAILED,
233
                'Authentication cancelled by user'
234
            )
235
            ->get();
236
237
        $logger->notice(sprintf(
238
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
239
            $responseContext->getInResponseTo(),
240
            $response->getId()
241
        ));
242
243
        return $this->renderSamlResponse('consumeAssertion', $response);
244
    }
245
246
    /**
247
     * @param string         $view
248
     * @param SAMLResponse $response
249
     * @return Response
250
     */
251 View Code Duplication
    public function renderSamlResponse($view, SAMLResponse $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...
252
    {
253
        $responseContext = $this->getResponseContext();
254
255
        return $this->render($view, [
256
            'acu'        => $responseContext->getDestination(),
257
            'response'   => $this->getResponseAsXML($response),
258
            'relayState' => $responseContext->getRelayState()
259
        ]);
260
    }
261
262
    /**
263
     * @param string   $view
264
     * @param array    $parameters
265
     * @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...
266
     * @return Response
267
     */
268
    public function render($view, array $parameters = array(), Response $response = null)
269
    {
270
        return parent::render(
271
            'SurfnetStepupGatewayGatewayBundle:Gateway:' . $view . '.html.twig',
272
            $parameters,
273
            $response
274
        );
275
    }
276
277
    /**
278
     * @return \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext
279
     */
280
    public function getResponseContext()
281
    {
282
        $stateHandler = $this->get('gateway.proxy.state_handler');
283
        $responseContextServiceId = $stateHandler->getResponseContextServiceId();
284
285
        if (!$responseContextServiceId) {
286
            return $this->get(static::RESPONSE_CONTEXT_SERVICE_ID);
287
        }
288
289
        return $this->get($responseContextServiceId);
290
    }
291
292
    /**
293
     * @param SAMLResponse $response
294
     * @return string
295
     */
296
    private function getResponseAsXML(SAMLResponse $response)
297
    {
298
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
299
    }
300
301
    /**
302
     * @return SAMLResponse
303
     */
304
    private function createRequesterFailureResponse()
305
    {
306
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
307
        $responseBuilder = $this->get('gateway.proxy.response_builder');
308
        $context = $this->getResponseContext();
309
310
        $response = $responseBuilder
311
            ->createNewResponse($context)
312
            ->setResponseStatus(Constants::STATUS_REQUESTER, Constants::STATUS_REQUEST_UNSUPPORTED)
313
            ->get();
314
315
        return $response;
316
317
    }
318
319
    /**
320
     * @param $context
321
     * @return SAMLResponse
322
     */
323
    private function createResponseFailureResponse($context)
324
    {
325
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseBuilder $responseBuilder */
326
        $responseBuilder = $this->get('gateway.proxy.response_builder');
327
328
        $response = $responseBuilder
329
            ->createNewResponse($context)
330
            ->setResponseStatus(Constants::STATUS_RESPONDER)
331
            ->get();
332
333
        return $response;
334
    }
335
}
336