Completed
Pull Request — develop (#302)
by Michiel
04:02 queued 01:58
created

__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 1
nc 1
nop 7
1
<?php
2
3
/**
4
 * Copyright 2020 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\StepupMiddleware\MiddlewareBundle\Console\Command;
20
21
use Broadway\EventHandling\EventBusInterface;
22
use Exception;
23
use Rhumsaa\Uuid\Uuid;
24
use Surfnet\Stepup\Identity\Value\Institution;
25
use Surfnet\Stepup\Identity\Value\NameId;
26
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\UnverifiedSecondFactor;
27
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\VerifiedSecondFactor;
28
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\IdentityRepository;
29
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\UnverifiedSecondFactorRepository;
30
use Surfnet\StepupMiddleware\ApiBundle\Identity\Repository\VerifiedSecondFactorRepository;
31
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\CreateIdentityCommand;
32
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProvePhonePossessionCommand;
33
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
34
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VetSecondFactorCommand;
35
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Pipeline;
36
use Surfnet\StepupMiddleware\MiddlewareBundle\Service\DBALConnectionHelper;
37
use Symfony\Component\Console\Command\Command;
38
use Symfony\Component\Console\Input\InputArgument;
39
use Symfony\Component\Console\Input\InputInterface;
40
use Symfony\Component\Console\Output\OutputInterface;
41
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
42
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
43
44
final class BootstrapIdentityWithSmsSecondFactorCommand extends Command
45
{
46
    /** @var Pipeline  */
47
    private $pipeline;
48
    /** @var EventBusInterface  */
49
    private $eventBus;
50
    /** @var DBALConnectionHelper  */
51
    private $connection;
52
    /** @var IdentityRepository  */
53
    private $identityRepository;
54
    /** @var UnverifiedSecondFactorRepository  */
55
    private $unverifiedSecondFactorRepository;
56
    /** @var VerifiedSecondFactorRepository */
57
    private $verifiedSecondFactorRepository;
58
    /** @var TokenStorageInterface */
59
    private $tokenStorage;
60
61
    public function __construct(
62
        Pipeline $pipeline,
63
        EventBusInterface $eventBus,
64
        DBALConnectionHelper $connection,
65
        IdentityRepository $identityRepository,
66
        UnverifiedSecondFactorRepository $unverifiedSecondFactorRepository,
67
        VerifiedSecondFactorRepository $verifiedSecondFactorRepository,
68
        TokenStorageInterface $tokenStorage
69
    ) {
70
        $this->pipeline = $pipeline;
71
        $this->eventBus = $eventBus;
72
        $this->connection = $connection;
73
        $this->identityRepository = $identityRepository;
74
        $this->unverifiedSecondFactorRepository = $unverifiedSecondFactorRepository;
75
        $this->verifiedSecondFactorRepository = $verifiedSecondFactorRepository;
76
        $this->tokenStorage = $tokenStorage;
77
    }
78
79 View Code Duplication
    protected function configure()
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...
80
    {
81
        $this
82
            ->setName('middleware:bootstrap:identity-with-sms')
83
            ->setDescription('Creates an identity with a SMS second factor')
84
            ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create')
85
            ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create')
86
            ->addArgument('common-name', InputArgument::REQUIRED, 'The Common Name of the identity to create')
87
            ->addArgument('email', InputArgument::REQUIRED, 'The e-mail address of the identity to create')
88
            ->addArgument('preferred-locale', InputArgument::REQUIRED, 'The preferred locale of the identity to create')
89
            ->addArgument(
90
                'phone-number',
91
                InputArgument::REQUIRED,
92
                'The phone number of the user should be formatted like "+31 (0) 612345678"'
93
            )
94
            ->addArgument(
95
                'registration-status',
96
                InputArgument::REQUIRED,
97
                'Valid arguments: unverified, verified, vetted'
98
            );
99
    }
100
101
    protected function execute(InputInterface $input, OutputInterface $output)
102
    {
103
104
        $this->tokenStorage->setToken(
105
            new AnonymousToken('cli.bootstrap-identity-with-sms-token', 'cli', ['ROLE_SS', 'ROLE_RA'])
0 ignored issues
show
Documentation introduced by
array('ROLE_SS', 'ROLE_RA') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a array<integer,object<Sym...curity\Core\Role\Role>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
106
        );
107
108
        $nameId = new NameId($input->getArgument('name-id'));
109
        $institution = new Institution($input->getArgument('institution'));
0 ignored issues
show
Bug introduced by
It seems like $input->getArgument('institution') targeting Symfony\Component\Consol...nterface::getArgument() can also be of type array<integer,string> or null; however, Surfnet\Stepup\Identity\...titution::__construct() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
110
        $commonName = $input->getArgument('common-name');
111
        $email = $input->getArgument('email');
112
        $preferredLocale = $input->getArgument('preferred-locale');
113
        $registrationStatus = $input->getArgument('registration-status');
114
        $phoneNumber = $input->getArgument('phone-number');
115
        $identity = false;
116
117
        $output->writeln(
118
            sprintf(
119
                '<notice>Adding a %s SMS token for %s</notice>',
120
                $registrationStatus,
121
                $commonName
122
            )
123
        );
124
125
        if ($this->identityRepository->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
126
            $output->writeln(
127
                sprintf(
128
                    '<notice>An identity with name ID "%s" from institution "%s" already exists, using that identity</notice>',
129
                    $nameId->getNameId(),
130
                    $institution->getInstitution()
131
                )
132
            );
133
            $identity = $this->identityRepository->findOneByNameIdAndInstitution($nameId, $institution);
134
        }
135
136
        $this->connection->beginTransaction();
137
138
        $secondFactorId = Uuid::uuid4()->toString();
139
140
        if (!$identity) {
141
            $output->writeln('<notice>Creating a new identity</notice>');
142
            $identity = new CreateIdentityCommand();
143
            $identity->UUID = (string) Uuid::uuid4();
144
            $identity->id = (string) Uuid::uuid4();
145
            $identity->institution = $institution->getInstitution();
146
            $identity->nameId = $nameId->getNameId();
147
            $identity->commonName = $commonName;
0 ignored issues
show
Documentation Bug introduced by
It seems like $commonName can also be of type array<integer,string>. However, the property $commonName is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
148
            $identity->email = $email;
0 ignored issues
show
Documentation Bug introduced by
It seems like $email can also be of type array<integer,string>. However, the property $email is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
149
            $identity->preferredLocale = $preferredLocale;
0 ignored issues
show
Documentation Bug introduced by
It seems like $preferredLocale can also be of type array<integer,string>. However, the property $preferredLocale is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
150
            $this->pipeline->process($identity);
151
        }
152
153
        try {
154
            switch ($registrationStatus) {
155
                case "unverified":
156
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
157
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
158
                    break;
159
                case "verified":
160
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
161
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
162
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
163
                    $unverifiedSecondFactor = $this->unverifiedSecondFactorRepository->findOneBy(
164
                        ['identityId' => $identity->id, 'type' => 'sms']
165
                    );
166
                    $output->writeln('<notice>Creating a verified SMS token</notice>');
167
                    $this->verifyEmail($identity, $unverifiedSecondFactor);
168
                    break;
169
                case "vetted":
170
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
171
                    $this->provePossession($secondFactorId, $identity, $phoneNumber);
172
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
173
                    $unverifiedSecondFactor = $this->unverifiedSecondFactorRepository->findOneBy(
174
                        ['identityId' => $identity->id, 'type' => 'sms']
175
                    );
176
                    $output->writeln('<notice>Creating a verified SMS token</notice>');
177
                    $this->verifyEmail($identity, $unverifiedSecondFactor);
178
                    /** @var VerifiedSecondFactor $verifiedSecondFactor */
179
                    $verifiedSecondFactor = $this->verifiedSecondFactorRepository->findOneBy(
180
                        ['identityId' => $identity->id, 'type' => 'sms']
181
                    );
182
                    $output->writeln('<notice>Vetting the verified SMS token</notice>');
183
                    $this->vetSecondFactor($identity, $secondFactorId, $verifiedSecondFactor, $phoneNumber);
184
                    break;
185
            }
186
187
            $this->eventBus->flush();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Broadway\EventHandling\EventBusInterface as the method flush() does only exist in the following implementations of said interface: Surfnet\StepupMiddleware...ndling\BufferedEventBus.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
188
            $this->connection->commit();
189
190
        } catch (Exception $e) {
191
            $output->writeln(
192
                sprintf(
193
                    '<error>An Error occurred when trying to bootstrap the identity: "%s"</error>',
194
                    $e->getMessage()
195
                )
196
            );
197
198
            $this->connection->rollBack();
199
200
            throw $e;
201
        }
202
203
        $output->writeln(
204
            sprintf(
205
                '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>',
206
                $identity->id,
207
                $registrationStatus,
208
                $secondFactorId
209
            )
210
        );
211
    }
212
213 View Code Duplication
    private function provePossession($secondFactorId, $identity, $phoneNumber)
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...
214
    {
215
        $command = new ProvePhonePossessionCommand();
216
        $command->UUID = (string) Uuid::uuid4();
217
        $command->secondFactorId = $secondFactorId;
218
        $command->identityId = $identity->id;
219
        $command->phoneNumber = $phoneNumber;
220
        $this->pipeline->process($command);
221
    }
222
223 View Code Duplication
    private function verifyEmail($identity, $unverifiedSecondFactor)
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...
224
    {
225
        $command = new VerifyEmailCommand();
226
        $command->UUID = (string) Uuid::uuid4();
227
        $command->identityId = $identity->id;
228
        $command->verificationNonce = $unverifiedSecondFactor->verificationNonce;
229
        $this->pipeline->process($command);
230
    }
231
232
    private function vetSecondFactor($identity, $secondFactorId, $verifiedSecondFactor, $phoneNumber)
233
    {
234
        $command = new VetSecondFactorCommand();
235
        $command->UUID = (string) Uuid::uuid4();
236
        $command->authorityId = 'db9b8bdf-720c-44ba-a4c4-154953e45f14';
237
        $command->identityId = $identity->id;
238
        $command->secondFactorId = $secondFactorId;
239
        $command->registrationCode = $verifiedSecondFactor->registrationCode;
240
        $command->secondFactorType = 'sms';
241
        $command->secondFactorIdentifier = $phoneNumber;
242
        $command->documentNumber = '123987';
243
        $command->identityVerified = true;
244
        $this->pipeline->process($command);
245
    }
246
}
247