Completed
Push — feature/implement-state-handli... ( bd5ae0 )
by Michiel
01:52
created

ProxyResponseService::createProxyResponse()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 9.0168
c 0
b 0
f 0
cc 5
nc 4
nop 3
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\Service;
20
21
use DateTime;
22
use DateTimeZone;
23
use SAML2\Assertion;
24
use SAML2\Constants;
25
use SAML2\Response;
26
use SAML2\XML\saml\SubjectConfirmation;
27
use SAML2\XML\saml\SubjectConfirmationData;
28
use Surfnet\SamlBundle\Entity\IdentityProvider;
29
use Surfnet\SamlBundle\SAML2\Attribute\AttributeDefinition;
30
use Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary;
31
use Surfnet\StepupBundle\Value\Loa;
32
use Surfnet\StepupGateway\GatewayBundle\Exception\RuntimeException;
33
use Surfnet\StepupGateway\GatewayBundle\Saml\AssertionSigningService;
34
use Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler;
35
36
/**
37
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
38
 */
39
class ProxyResponseService
40
{
41
    /**
42
     * @var \Surfnet\SamlBundle\Entity\IdentityProvider
43
     */
44
    private $hostedIdentityProvider;
45
46
    /**
47
     * @var \Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler
48
     */
49
    private $proxyStateHandler;
50
51
    /**
52
     * @var \Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary
53
     */
54
    private $attributeDictionary;
55
56
    /**
57
     * @var \Surfnet\SamlBundle\SAML2\Attribute\AttributeDefinition
58
     */
59
    private $eptiAttribute;
60
61
    /**
62
     * @var \DateTime
63
     */
64
    private $currentTime;
65
66
    /**
67
     * @var \Surfnet\StepupGateway\GatewayBundle\Saml\AssertionSigningService
68
     */
69
    private $assertionSigningService;
70
71
    /**
72
     * @var \Surfnet\StepupBundle\Value\Loa
73
     */
74
    private $intrinsicLoa;
75
76
    public function __construct(
77
        IdentityProvider $hostedIdentityProvider,
78
        ProxyStateHandler $proxyStateHandler,
79
        AssertionSigningService $assertionSigningService,
80
        AttributeDictionary $attributeDictionary,
81
        AttributeDefinition $eptiAttribute,
82
        Loa $intrinsicLoa,
83
        DateTime $now = null
84
    ) {
85
        $this->hostedIdentityProvider    = $hostedIdentityProvider;
86
        $this->proxyStateHandler         = $proxyStateHandler;
87
        $this->assertionSigningService   = $assertionSigningService;
88
        $this->attributeDictionary       = $attributeDictionary;
89
        $this->eptiAttribute             = $eptiAttribute;
90
        $this->intrinsicLoa              = $intrinsicLoa;
91
        $this->currentTime = is_null($now) ? new DateTime('now', new DateTimeZone('UTC')): $now;
92
    }
93
94
    /**
95
     * @param Assertion $assertion
96
     * @param string $destination ACS URL
97
     * @param string|null $loa
98
     * @return Response
99
     */
100
    public function createProxyResponse(Assertion $assertion, $destination, $loa = null)
101
    {
102
103
        $newAssertion = new Assertion();
104
        $newAssertion->setNotBefore($this->currentTime->getTimestamp());
105
        $newAssertion->setNotOnOrAfter($this->getTimestamp('PT5M'));
106
        $newAssertion->setAttributes($assertion->getAttributes());
107
        $newAssertion->setIssuer($this->hostedIdentityProvider->getEntityId());
108
        $newAssertion->setIssueInstant($this->getTimestamp());
109
110
        $this->assertionSigningService->signAssertion($newAssertion);
111
        $this->addSubjectConfirmationFor($newAssertion, $destination);
112
113
        $translatedAssertion = $this->attributeDictionary->translate($assertion);
114
        $eptiNameId = $translatedAssertion->getAttributeValue('eduPersonTargetedID');
115
116
        // Perform some input validation on the eptiNameId that was received.
117
        if (is_null($eptiNameId)) {
118
            throw new RuntimeException('The "urn:mace:dir:attribute-def:eduPersonTargetedID" is not present.');
119
        } elseif (!array_key_exists(0, $eptiNameId) || !$eptiNameId[0]->value) {
120
            throw new RuntimeException(
121
                'The "urn:mace:dir:attribute-def:eduPersonTargetedID" attribute does not contain a NameID with a value.'
122
            );
123
        }
124
125
        $newAssertion->setNameId($eptiNameId[0]);
126
127
        $newAssertion->setValidAudiences([$this->proxyStateHandler->getRequestServiceProvider()]);
128
129
        $this->addAuthenticationStatementTo($newAssertion, $assertion);
130
131
        if ($loa) {
132
            $newAssertion->setAuthnContextClassRef($loa);
133
        }
134
135
        return $this->createNewAuthnResponse($newAssertion, $destination);
136
    }
137
138
    /**
139
     * @param Assertion $newAssertion
140
     * @param string $destination ACS URL
141
     */
142 View Code Duplication
    private function addSubjectConfirmationFor(Assertion $newAssertion, $destination)
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...
143
    {
144
        $confirmation         = new SubjectConfirmation();
145
        $confirmation->Method = Constants::CM_BEARER;
146
147
        $confirmationData                      = new SubjectConfirmationData();
148
        $confirmationData->InResponseTo        = $this->proxyStateHandler->getRequestId();
149
        $confirmationData->Recipient           = $destination;
150
        $confirmationData->NotOnOrAfter        = $newAssertion->getNotOnOrAfter();
151
152
        $confirmation->SubjectConfirmationData = $confirmationData;
153
154
        $newAssertion->setSubjectConfirmation([$confirmation]);
155
    }
156
157
    /**
158
     * @param Assertion $newAssertion
159
     * @param Assertion $assertion
160
     */
161
    private function addAuthenticationStatementTo(Assertion $newAssertion, Assertion $assertion)
162
    {
163
        $newAssertion->setAuthnInstant($assertion->getAuthnInstant());
164
        $newAssertion->setAuthnContextClassRef((string) $this->intrinsicLoa);
165
166
        $authority = $assertion->getAuthenticatingAuthority();
167
        $newAssertion->setAuthenticatingAuthority(
168
            array_merge(
169
                (empty($authority) ? [] : $authority),
170
                [$assertion->getIssuer()]
171
            )
172
        );
173
    }
174
175
    /**
176
     * @param Assertion $newAssertion
177
     * @param string $destination ACS URL
178
     * @return Response
179
     */
180 View Code Duplication
    private function createNewAuthnResponse(Assertion $newAssertion, $destination)
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...
181
    {
182
        $response = new Response();
183
        $response->setAssertions([$newAssertion]);
184
        $response->setIssuer($this->hostedIdentityProvider->getEntityId());
185
        $response->setIssueInstant($this->getTimestamp());
186
        $response->setDestination($destination);
187
        $response->setInResponseTo($this->proxyStateHandler->getRequestId());
188
189
        return $response;
190
    }
191
192
    /**
193
     * @param string $interval a \DateInterval compatible interval to skew the time with
0 ignored issues
show
Documentation introduced by
Should the type for parameter $interval not be string|null?

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...
194
     * @return int
195
     */
196 View Code Duplication
    private function getTimestamp($interval = null)
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...
197
    {
198
        $time = clone $this->currentTime;
199
200
        if ($interval) {
201
            $time->add(new \DateInterval($interval));
202
        }
203
204
        return $time->getTimestamp();
205
    }
206
}
207