Completed
Pull Request — develop (#91)
by Boy
02:58
created

ProxyResponseService::createNewAuthnResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 11
loc 11
rs 9.4285
cc 1
eloc 8
nc 1
nop 2
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 Exception;
22
use SAML2_Assertion;
23
use Surfnet\SamlBundle\Entity\IdentityProvider;
24
use Surfnet\SamlBundle\Entity\ServiceProvider;
25
use Surfnet\SamlBundle\SAML2\Attribute\AttributeDefinition;
26
use Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary;
27
use Surfnet\SamlBundle\SAML2\AuthnRequest;
28
use Surfnet\SamlBundle\SAML2\Response\AssertionAdapter;
29
use Surfnet\StepupBundle\Value\Loa;
30
use Surfnet\StepupGateway\GatewayBundle\Saml\AssertionSigningService;
31
use Surfnet\StepupGateway\GatewayBundle\Saml\Exception\RuntimeException;
32
use Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler;
33
34
/**
35
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
36
 */
37
class ProxyResponseService
38
{
39
    /**
40
     * @var \Surfnet\SamlBundle\Entity\IdentityProvider
41
     */
42
    private $hostedIdentityProvider;
43
44
    /**
45
     * @var \Surfnet\StepupGateway\GatewayBundle\Saml\Proxy\ProxyStateHandler
46
     */
47
    private $proxyStateHandler;
48
49
    /**
50
     * @var \Surfnet\SamlBundle\SAML2\Attribute\AttributeDictionary
51
     */
52
    private $attributeDictionary;
53
54
    /**
55
     * @var \Surfnet\SamlBundle\SAML2\Attribute\AttributeDefinition
56
     */
57
    private $eptiAttribute;
58
59
    /**
60
     * @var \DateTime
61
     */
62
    private $currentTime;
63
64
    /**
65
     * @var \Surfnet\StepupGateway\GatewayBundle\Saml\AssertionSigningService
66
     */
67
    private $assertionSigningService;
68
69
    /**
70
     * @var \Surfnet\StepupBundle\Value\Loa
71
     */
72
    private $intrinsicLoa;
73
74
    public function __construct(
75
        IdentityProvider $hostedIdentityProvider,
76
        ProxyStateHandler $proxyStateHandler,
77
        AssertionSigningService $assertionSigningService,
78
        AttributeDictionary $attributeDictionary,
79
        AttributeDefinition $eptiAttribute,
80
        Loa $intrinsicLoa
81
    ) {
82
        $this->hostedIdentityProvider    = $hostedIdentityProvider;
83
        $this->proxyStateHandler         = $proxyStateHandler;
84
        $this->assertionSigningService   = $assertionSigningService;
85
        $this->attributeDictionary       = $attributeDictionary;
86
        $this->eptiAttribute             = $eptiAttribute;
87
        $this->intrinsicLoa              = $intrinsicLoa;
88
        $this->currentTime = new \DateTime('now', new \DateTimeZone('UTC'));
89
    }
90
91
    /**
92
     * @param SAML2_Assertion $assertion
0 ignored issues
show
Bug introduced by
There is no parameter named $assertion. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
93
     * @param ServiceProvider $targetServiceProvider
94
     * @param string|null $authnContextClassRef
95
     * @return \SAML2_Response
96
     */
97
    public function createSecondFactorOnlyResponse(
98
      $nameId,
99
      ServiceProvider $targetServiceProvider,
100
      $authnContextClassRef
101
    ) {
102
        $newAssertion = new SAML2_Assertion();
103
        $newAssertion->setNotBefore($this->currentTime->getTimestamp());
104
        $newAssertion->setNotOnOrAfter($this->getTimestamp('PT5M'));
105
        $newAssertion->setIssuer($this->hostedIdentityProvider->getEntityId());
106
        $newAssertion->setIssueInstant($this->getTimestamp());
107
108
        $this->assertionSigningService->signAssertion($newAssertion);
109
        $this->addSubjectConfirmationFor($newAssertion, $targetServiceProvider);
110
111
        $newAssertion->setNameId([
112
            'Format' => \SAML2_Const::NAMEID_UNSPECIFIED,
113
            'Value' => $nameId,
114
        ]);
115
116
        $newAssertion->setValidAudiences([$this->proxyStateHandler->getRequestServiceProvider()]);
117
118
        $this->addAuthenticationStatementTo($newAssertion, $newAssertion);
119
120
        $newAssertion->setAuthnContextClassRef($authnContextClassRef);
121
122
        return $this->createNewAuthnResponse($newAssertion, $targetServiceProvider);
123
    }
124
125
    /**
126
     * @param SAML2_Assertion $assertion
127
     * @param ServiceProvider $targetServiceProvider
128
     * @param string|null $loa
129
     * @return \SAML2_Response
130
     */
131
    public function createProxyResponse(SAML2_Assertion $assertion, ServiceProvider $targetServiceProvider, $loa = null)
132
    {
133
        $newAssertion = new SAML2_Assertion();
134
        $newAssertion->setNotBefore($this->currentTime->getTimestamp());
135
        $newAssertion->setNotOnOrAfter($this->getTimestamp('PT5M'));
136
        $newAssertion->setAttributes($assertion->getAttributes());
137
        $newAssertion->setIssuer($this->hostedIdentityProvider->getEntityId());
138
        $newAssertion->setIssueInstant($this->getTimestamp());
139
140
        $this->assertionSigningService->signAssertion($newAssertion);
141
        $this->addSubjectConfirmationFor($newAssertion, $targetServiceProvider);
142
143
        $translatedAssertion = $this->attributeDictionary->translate($assertion);
144
        $eptiNameId = $this->parseEptiNameId($translatedAssertion);
145
        $newAssertion->setNameId($eptiNameId);
146
147
        $newAssertion->setValidAudiences([$this->proxyStateHandler->getRequestServiceProvider()]);
148
149
        $this->addAuthenticationStatementTo($newAssertion, $assertion);
150
151
        if ($loa) {
152
            $newAssertion->setAuthnContextClassRef($loa);
153
        }
154
155
        return $this->createNewAuthnResponse($newAssertion, $targetServiceProvider);
156
    }
157
158
    /**
159
     * @param SAML2_Assertion $newAssertion
160
     * @param ServiceProvider $targetServiceProvider
161
     */
162 View Code Duplication
    private function addSubjectConfirmationFor(SAML2_Assertion $newAssertion, ServiceProvider $targetServiceProvider)
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...
163
    {
164
        $confirmation         = new \SAML2_XML_saml_SubjectConfirmation();
165
        $confirmation->Method = \SAML2_Const::CM_BEARER;
166
167
        $confirmationData                      = new \SAML2_XML_saml_SubjectConfirmationData();
168
        $confirmationData->InResponseTo        = $this->proxyStateHandler->getRequestId();
169
        $confirmationData->Recipient           = $targetServiceProvider->getAssertionConsumerUrl();
170
        $confirmationData->NotOnOrAfter        = $this->getTimestamp('PT8H');
171
172
        $confirmation->SubjectConfirmationData = $confirmationData;
173
174
        $newAssertion->setSubjectConfirmation([$confirmation]);
175
    }
176
177
    /**
178
     * @param SAML2_Assertion $newAssertion
179
     * @param SAML2_Assertion $assertion
180
     */
181
    private function addAuthenticationStatementTo(SAML2_Assertion $newAssertion, SAML2_Assertion $assertion)
182
    {
183
        $newAssertion->setAuthnInstant($assertion->getAuthnInstant());
184
        $newAssertion->setAuthnContextClassRef((string) $this->intrinsicLoa);
185
186
        $authority = $assertion->getAuthenticatingAuthority();
187
        $newAssertion->setAuthenticatingAuthority(
188
            array_merge(
189
                (empty($authority) ? [] : $authority),
190
                [$this->hostedIdentityProvider->getEntityId()]
191
            )
192
        );
193
    }
194
195
    /**
196
     * @param SAML2_Assertion $newAssertion
197
     * @param ServiceProvider $targetServiceProvider
198
     * @return \SAML2_Response
199
     */
200 View Code Duplication
    private function createNewAuthnResponse(SAML2_Assertion $newAssertion, ServiceProvider $targetServiceProvider)
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...
201
    {
202
        $response = new \SAML2_Response();
203
        $response->setAssertions([$newAssertion]);
204
        $response->setIssuer($this->hostedIdentityProvider->getEntityId());
205
        $response->setIssueInstant($this->getTimestamp());
206
        $response->setDestination($targetServiceProvider->getAssertionConsumerUrl());
207
        $response->setInResponseTo($this->proxyStateHandler->getRequestId());
208
209
        return $response;
210
    }
211
212
    /**
213
     * @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...
214
     * @return int
215
     */
216 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...
217
    {
218
        $time = clone $this->currentTime;
219
220
        if ($interval) {
221
            $time->add(new \DateInterval($interval));
222
        }
223
224
        return $time->getTimestamp();
225
    }
226
227
    /**
228
     * @param AssertionAdapter $translatedAssertion
229
     * @return array
230
     */
231
    private function parseEptiNameId(AssertionAdapter $translatedAssertion)
232
    {
233
        /** @var \DOMNodeList[] $eptiValues */
234
        $eptiValues      = $translatedAssertion->getAttributeValue('eduPersonTargetedID');
235
        $eptiDomNodeList = $eptiValues[0];
236
237
        if (!$eptiDomNodeList instanceof \DOMNodeList || $eptiDomNodeList->length !== 1) {
238
            throw new RuntimeException(
239
                'EPTI attribute must contain exactly one NameID element as value:::: ' . print_r($eptiValues, true)
240
            );
241
        }
242
243
        $eptiValue  = $eptiDomNodeList->item(0);
244
        $eptiNameId = \SAML2_Utils::parseNameId($eptiValue);
0 ignored issues
show
Compatibility introduced by
$eptiValue of type object<DOMNode> is not a sub-type of object<DOMElement>. It seems like you assume a child class of the class DOMNode to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
245
246
        return $eptiNameId;
247
    }
248
}
249