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

ServiceProviderContext::loadPrivateKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * Copyright 2020 SURFnet B.V.
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\Behat;
20
21
use Behat\Behat\Context\Context;
22
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
23
use Behat\Symfony2Extension\Context\KernelAwareContext;
24
use RobRichards\XMLSecLibs\XMLSecurityKey;
25
use SAML2\AuthnRequest;
26
use SAML2\Certificate\Key;
27
use SAML2\Certificate\KeyLoader;
28
use SAML2\Certificate\PrivateKeyLoader;
29
use SAML2\Configuration\PrivateKey;
30
use SAML2\Constants;
31
use SAML2\XML\saml\NameID;
32
use Surfnet\SamlBundle\Entity\IdentityProvider;
33
use Surfnet\SamlBundle\SAML2\AuthnRequest as Saml2AuthnRequest;
34
use Surfnet\StepupGateway\Behat\Repository\SamlEntityRepository;
35
use Surfnet\StepupGateway\Behat\Service\FixtureService;
36
use Symfony\Component\HttpFoundation\Request;
37
use Symfony\Component\HttpFoundation\RequestStack;
38
use Symfony\Component\HttpKernel\KernelInterface;
39
40
class ServiceProviderContext implements Context, KernelAwareContext
41
{
42
    const SFO_ENDPOINT_URL = 'https://gateway.stepup.example.com/second-factor-only/single-sign-on';
43
    const SSO_ENDPOINT_URL = 'https://gateway.stepup.example.com/authentication/single-sign-on';
44
45
    /**
46
     * @var array
47
     */
48
    private $currentSp;
49
50
    /**
51
     * @var array
52
     */
53
    private $currentSfoSp;
54
55
    /**
56
     * @var array
57
     */
58
    private $currentIdP;
59
60
    /**
61
     * @var FixtureService
62
     */
63
    private $fixtureService;
64
65
    /**
66
     * @var KernelInterface
67
     */
68
    private $kernel;
69
70
    /**
71
     * @var MinkContext
72
     */
73
    private $minkContext;
74
75
    public function __construct(FixtureService $fixtureService)
76
    {
77
        $this->fixtureService = $fixtureService;
78
    }
79
80
    public function setKernel(KernelInterface $kernel)
81
    {
82
        $this->kernel = $kernel;
83
    }
84
85
    /**
86
     * @BeforeScenario
87
     */
88
    public function gatherContexts(BeforeScenarioScope $scope)
89
    {
90
        $environment = $scope->getEnvironment();
91
        $this->minkContext = $environment->getContext(MinkContext::class);
92
    }
93
94
    /**
95
     * @Given /^an SFO enabled SP with EntityID ([^\']*)$/
96
     */
97
    public function anSFOEnabledSPWithEntityID($entityId)
98
    {
99
        $this->registerSp($entityId, true);
100
    }
101
102
    /**
103
     * @Given /^an SP with EntityID ([^\']*)$/
104
     */
105
    public function anSPWithEntityID($entityId)
106
    {
107
        $this->registerSp($entityId, false);
108
    }
109
    /**
110
     * @Given /^an IdP with EntityID ([^\']*)$/
111
     */
112
    public function anIdPWithEntityID($entityId)
113
    {
114
        $this->registerIdp($entityId, false);
0 ignored issues
show
Unused Code introduced by
The call to ServiceProviderContext::registerIdP() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
115
    }
116
117
    private function registerSp($entityId, $sfoEnabled)
118
    {
119
        $publicKeyLoader = new KeyLoader();
120
        // todo: use from services_test.yml
121
        $publicKeyLoader->loadCertificateFile('/var/www/ci/certificates/sp.crt');
122
        $keys = $publicKeyLoader->getKeys();
123
        /** @var Key $cert */
124
        $cert = $keys->first();
125
126
        $spEntity = $this->fixtureService->registerSP($entityId, $cert['X509Certificate'], $sfoEnabled);
127
128
        $spEntity['configuration'] = json_decode($spEntity['configuration'], true);
129
        if ($sfoEnabled) {
130
            $this->currentSfoSp = $spEntity;
131
        } else {
132
            $this->currentSp = $spEntity;
133
        }
134
    }
135
136
    private function registerIdP($entityId)
137
    {
138
        $publicKeyLoader = new KeyLoader();
139
        // todo: use from services_test.yml
140
        $publicKeyLoader->loadCertificateFile('/var/www/ci/certificates/idp.crt');
141
        $keys = $publicKeyLoader->getKeys();
142
        /** @var Key $cert */
143
        $cert = $keys->first();
144
145
        $idpEntity = $this->fixtureService->registerIdP($entityId, $cert['X509Certificate']);
146
147
        $idpEntity['configuration'] = json_decode($idpEntity['configuration'], true);
148
        $this->currentIdP = $idpEntity;
149
    }
150
151
    /**
152
     * @When /^([^\']*) starts an SFO authentication$/
153
     */
154
    public function iStartAnSFOAuthentication($nameId)
155
    {
156
        $authnRequest = new AuthnRequest();
157
        // In order to later assert if the response succeeded or failed, set our own dummy ACS location
158
        $authnRequest->setAssertionConsumerServiceURL(SamlEntityRepository::SP_ACS_LOCATION);
159
        $authnRequest->setIssuer($this->currentSfoSp['entityId']);
160
        $authnRequest->setDestination(self::SFO_ENDPOINT_URL);
161
        $authnRequest->setProtocolBinding(Constants::BINDING_HTTP_REDIRECT);
162
        $authnRequest->setNameId($this->buildNameId($nameId));
163
        // Sign with random key, does not mather for now.
164
        // todo: use from services_test.yml
165
        $authnRequest->setSignatureKey(
166
            $this->loadPrivateKey(new PrivateKey('/var/www/ci/certificates/sp.pem', 'default'))
167
        );
168
        $authnRequest->setRequestedAuthnContext(
169
            ['AuthnContextClassRef' => ['http://stepup.example.com/assurance/sfo-level2']]
170
        );
171
        $request = Saml2AuthnRequest::createNew($authnRequest);
172
        $query = $request->buildRequestQuery();
173
174
        $this->getSession()->visit($request->getDestination().'?'.$query);
175
    }
176
177
    /**
178
     * @When /^([^\']*) starts an authentication$/
179
     */
180
    public function iStartAnAuthentication($nameId)
181
    {
182
        $authnRequest = new AuthnRequest();
183
        // In order to later assert if the response succeeded or failed, set our own dummy ACS location
184
        $authnRequest->setAssertionConsumerServiceURL(SamlEntityRepository::SP_ACS_LOCATION);
185
        $authnRequest->setIssuer($this->currentSp['entityId']);
186
        $authnRequest->setDestination(self::SSO_ENDPOINT_URL);
187
        $authnRequest->setProtocolBinding(Constants::BINDING_HTTP_REDIRECT);
188
        $authnRequest->setNameId($this->buildNameId($nameId));
189
        // Sign with random key, does not mather for now.
190
        // todo: use from services_test.yml
191
        $authnRequest->setSignatureKey(
192
            $this->loadPrivateKey(new PrivateKey('/var/www/ci/certificates/sp.pem', 'default'))
193
        );
194
        $authnRequest->setRequestedAuthnContext(
195
            ['AuthnContextClassRef' => ['http://stepup.example.com/assurance/level2']]
196
        );
197
        $request = Saml2AuthnRequest::createNew($authnRequest);
198
        $request->setSubject($authnRequest->getNameId()->value, $authnRequest->getNameId()->Format);
199
        $query = $request->buildRequestQuery();
200
        $this->getSession()->visit($request->getDestination().'?'.$query);
201
    }
202
203
    /**
204
     * @When /^I authenticate at the IdP$/
205
     */
206
    public function iAuthenticateAtTheIdp()
207
    {
208
        $this->minkContext->pressButton('Submit');
209
    }
210
211
    /**
212
     * @return IdentityProvider
213
     */
214
    public function getIdentityProvider()
215
    {
216
        /** @var RequestStack $stack */
217
218
        $stack = $this->kernel->getContainer()->get('request_stack');
219
        $stack->push(Request::create('https://gateway.stepup.example.com'));
220
        $ip = $this->kernel->getContainer()->get('surfnet_saml.hosted.identity_provider');
221
        $stack->pop();
222
223
        return $ip;
224
    }
225
226
    private static function loadPrivateKey(PrivateKey $key)
227
    {
228
        $keyLoader = new PrivateKeyLoader();
229
        $privateKey = $keyLoader->loadPrivateKey($key);
230
231
        $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, ['type' => 'private']);
232
        $key->loadKey($privateKey->getKeyAsString());
233
234
        return $key;
235
    }
236
237
    private function getSession()
238
    {
239
        return $this->minkContext->getSession();
240
    }
241
242
    /**
243
     * @param string $nameId
244
     * @return NameID
245
     */
246
    private function buildNameId($nameId)
247
    {
248
        $nameId = NameID::fromArray(['Value' => $nameId, 'Format' =>  Constants::NAMEFORMAT_UNSPECIFIED]);
0 ignored issues
show
Deprecated Code introduced by
The method SAML2\XML\saml\NameIDType::fromArray() has been deprecated.

This method has been deprecated.

Loading history...
249
        return $nameId;
250
    }
251
}