Completed
Push — develop ( 3aad91...9c08ab )
by
unknown
17:26
created

GatewayController::respondAction()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 46
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 8.9411
c 0
b 0
f 0
cc 3
eloc 28
nc 4
nop 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
 */
18
19
namespace Surfnet\StepupGateway\GatewayBundle\Controller;
20
21
use Exception;
22
use SAML2_Const;
23
use SAML2_Response;
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 Symfony\Bundle\FrameworkBundle\Controller\Controller;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\HttpKernel\Exception\HttpException;
32
33
class GatewayController extends Controller
34
{
35
    const RESPONSE_CONTEXT_SERVICE_ID = 'gateway.proxy.response_context';
36
37
    public function ssoAction(Request $httpRequest)
38
    {
39
        /** @var \Psr\Log\LoggerInterface $logger */
40
        $logger = $this->get('logger');
41
        $logger->notice('Received AuthnRequest, started processing');
42
43
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
44
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
45
46
        try {
47
            $originalRequest = $redirectBinding->receiveSignedAuthnRequestFrom($httpRequest);
48
        } catch (Exception $e) {
49
            $logger->critical(sprintf('Could not process Request, error: "%s"', $e->getMessage()));
50
51
            return $this->render('unrecoverableError');
52
        }
53
54
        $originalRequestId = $originalRequest->getRequestId();
55
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
56
        $logger->notice(sprintf(
57
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
58
            $originalRequest->getServiceProvider(),
59
            $originalRequest->getRequestId()
60
        ));
61
62
        /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler $stateHandler */
63
        $stateHandler = $this->get('gateway.proxy.state_handler');
64
        $stateHandler
65
            ->setRequestId($originalRequestId)
66
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
67
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''))
68
            ->setResponseAction('SurfnetStepupGatewayGatewayBundle:Gateway:respond')
69
            ->setResponseContextServiceId(static::RESPONSE_CONTEXT_SERVICE_ID);
70
71
        // check if the requested Loa is supported
72
        $requiredLoa = $originalRequest->getAuthenticationContextClassRef();
73
        if ($requiredLoa && !$this->get('surfnet_stepup.service.loa_resolution')->hasLoa($requiredLoa)) {
74
            $logger->info(sprintf(
75
                'Requested required Loa "%s" does not exist, sending response with status Requester Error',
76
                $requiredLoa
77
            ));
78
79
            $response = $this->createRequesterFailureResponse();
80
81
            return $this->renderSamlResponse('consumeAssertion', $response);
82
        }
83
84
        $stateHandler->setRequiredLoaIdentifier($requiredLoa);
85
86
        $proxyRequest = AuthnRequestFactory::createNewRequest(
87
            $this->get('surfnet_saml.hosted.service_provider'),
88
            $this->get('surfnet_saml.remote.idp')
89
        );
90
91
        $proxyRequest->setScoping([$originalRequest->getServiceProvider()]);
92
        $stateHandler->setGatewayRequestId($proxyRequest->getRequestId());
93
94
        $logger->notice(sprintf(
95
            'Sending Proxy AuthnRequest with request ID: "%s" for original AuthnRequest "%s"',
96
            $proxyRequest->getRequestId(),
97
            $originalRequest->getRequestId()
98
        ));
99
100
        return $redirectBinding->createRedirectResponseFor($proxyRequest);
101
    }
102
103
    public function proxySsoAction()
104
    {
105
        throw new HttpException(418, 'Not Yet Implemented');
106
    }
107
108
    /**
109
     * @param Request $request
110
     * @return \Symfony\Component\HttpFoundation\Response
111
     */
112
    public function consumeAssertionAction(Request $request)
113
    {
114
        $responseContext = $this->getResponseContext();
115
        $originalRequestId = $responseContext->getInResponseTo();
116
117
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
118
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
119
        $logger->notice('Received SAMLResponse, attempting to process for Proxy Response');
120
121
        try {
122
            /** @var \SAML2_Assertion $assertion */
123
            $assertion = $this->get('surfnet_saml.http.post_binding')->processResponse(
124
                $request,
125
                $this->get('surfnet_saml.remote.idp'),
126
                $this->get('surfnet_saml.hosted.service_provider')
127
            );
128
        } catch (Exception $exception) {
129
            $logger->error(sprintf('Could not process received Response, error: "%s"', $exception->getMessage()));
130
131
            $response = $this->createResponseFailureResponse($responseContext);
132
133
            return $this->renderSamlResponse('unprocessableResponse', $response);
134
        }
135
136
        $adaptedAssertion = new AssertionAdapter($assertion);
137
        $expectedInResponseTo = $responseContext->getExpectedInResponseTo();
138 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...
139
            $logger->critical(sprintf(
140
                'Received Response with unexpected InResponseTo: "%s", %s',
141
                $adaptedAssertion->getInResponseTo(),
142
                ($expectedInResponseTo ? 'expected "' . $expectedInResponseTo . '"' : ' no response expected')
143
            ));
144
145
            return $this->render('unrecoverableError');
146
        }
147
148
        $logger->notice('Successfully processed SAMLResponse');
149
150
        $responseContext->saveAssertion($assertion);
151
152
        $logger->notice(sprintf('Forwarding to second factor controller for loa determination and handling'));
153
154
        return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:selectSecondFactorForVerification');
155
    }
156
157
    public function respondAction()
158
    {
159
        $responseContext = $this->getResponseContext();
160
        $originalRequestId = $responseContext->getInResponseTo();
161
162
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
163
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
164
        $logger->notice('Creating Response');
165
166
        $grantedLoa = null;
167
        if ($responseContext->isSecondFactorVerified()) {
168
            $secondFactor = $this->get('gateway.service.second_factor_service')->findByUuid(
169
                $responseContext->getSelectedSecondFactor()
170
            );
171
172
            $secondFactorTypeService = $this->get('surfnet_stepup.service.second_factor_type');
173
            $grantedLoa = $this->get('surfnet_stepup.service.loa_resolution')->getLoaByLevel(
174
                $secondFactor->getLoaLevel($secondFactorTypeService)
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