Completed
Pull Request — feature/acceptance-tests (#191)
by Michiel
02:42 queued 58s
created

anSFOEnabledSPWithEntityID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
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
44
    /**
45
     * @var array
46
     */
47
    private $currentSp;
48
49
    /**
50
     * @var FixtureService
51
     */
52
    private $fixtureService;
53
54
    /**
55
     * @var KernelInterface
56
     */
57
    private $kernel;
58
59
    /**
60
     * @var MinkContext
61
     */
62
    private $minkContext;
63
64
    public function __construct(FixtureService $fixtureService)
65
    {
66
        $this->fixtureService = $fixtureService;
67
    }
68
69
    public function setKernel(KernelInterface $kernel)
70
    {
71
        $this->kernel = $kernel;
72
    }
73
74
    /**
75
     * @BeforeScenario
76
     */
77
    public function gatherContexts(BeforeScenarioScope $scope)
78
    {
79
        $environment = $scope->getEnvironment();
80
        $this->minkContext = $environment->getContext(MinkContext::class);
81
    }
82
83
    /**
84
     * @Given /^an SFO enabled SP with EntityID ([^\']*)$/
85
     */
86
    public function anSFOEnabledSPWithEntityID($entityId)
87
    {
88
        $sfoEnabled = true;
89
        $publicKeyLoader = new KeyLoader();
90
        $publicKeyLoader->loadCertificateFile('/var/www/app/sp.crt');
91
        $keys = $publicKeyLoader->getKeys();
92
        /** @var Key $cert */
93
        $cert = $keys->first();
94
95
        $spEntity = $this->fixtureService->registerSP($entityId, $cert['X509Certificate'], $sfoEnabled);
96
97
        $spEntity['configuration'] = json_decode($spEntity['configuration'], true);
98
        $this->currentSp = $spEntity;
99
    }
100
101
    /**
102
     * @When /^([^\']*) starts a SFO authentication$/
103
     */
104
    public function iStartASecondFactorAuthenticationOnTheSecondFactorOnlyEndpoint($nameId)
105
    {
106
        $authnRequest = new AuthnRequest();
107
        // In order to later assert if the response succeeded or failed, set our own dummy ACS location
108
        $authnRequest->setAssertionConsumerServiceURL(SamlEntityRepository::SP_ACS_LOCATION);
109
        $authnRequest->setIssuer($this->currentSp['entityId']);
110
        $authnRequest->setDestination(self::SFO_ENDPOINT_URL);
111
        $authnRequest->setProtocolBinding(Constants::BINDING_HTTP_REDIRECT);
112
        $authnRequest->setNameId($this->buildNameId($nameId));
113
        // Sign with random key, does not mather for now.
114
        $authnRequest->setSignatureKey(
115
            $this->loadPrivateKey(new PrivateKey('/var/www/app/sp.pem', 'default'))
116
        );
117
        $authnRequest->setRequestedAuthnContext(
118
            ['AuthnContextClassRef' => ['http://stepup.example.com/assurance/sfo-level2']]
119
        );
120
        $request = Saml2AuthnRequest::createNew($authnRequest);
121
        $query = $request->buildRequestQuery();
122
123
        $this->getSession()->visit($request->getDestination().'?'.$query);
124
    }
125
126
    /**
127
     * @return IdentityProvider
128
     */
129
    public function getIdentityProvider()
130
    {
131
        /** @var RequestStack $stack */
132
133
        $stack = $this->kernel->getContainer()->get('request_stack');
134
        $stack->push(Request::create('https://gateway.stepup.example.com'));
135
        $ip = $this->kernel->getContainer()->get('surfnet_saml.hosted.identity_provider');
136
        $stack->pop();
137
138
        return $ip;
139
    }
140
141 View Code Duplication
    private static function loadPrivateKey(PrivateKey $key)
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...
142
    {
143
        $keyLoader = new PrivateKeyLoader();
144
        $privateKey = $keyLoader->loadPrivateKey($key);
145
146
        $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, ['type' => 'private']);
147
        $key->loadKey($privateKey->getKeyAsString());
148
149
        return $key;
150
    }
151
152
    private function getSession()
153
    {
154
        return $this->minkContext->getSession();
155
    }
156
157
    /**
158
     * @param string $nameId
159
     * @return NameID
160
     */
161
    private function buildNameId($nameId)
162
    {
163
        $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...
164
        return $nameId;
165
    }
166
}