Completed
Pull Request — develop (#302)
by Michiel
02:23
created

vetSecondFactor()   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 5
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 Exception;
22
use Rhumsaa\Uuid\Uuid;
23
use Surfnet\Stepup\Identity\Value\Institution;
24
use Surfnet\Stepup\Identity\Value\NameId;
25
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\UnverifiedSecondFactor;
26
use Surfnet\StepupMiddleware\ApiBundle\Identity\Entity\VerifiedSecondFactor;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\CreateIdentityCommand;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\ProvePhonePossessionCommand;
29
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
30
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VetSecondFactorCommand;
31
use Symfony\Component\Console\Command\Command;
32
use Symfony\Component\Console\Input\InputArgument;
33
use Symfony\Component\Console\Input\InputInterface;
34
use Symfony\Component\Console\Output\OutputInterface;
35
use Symfony\Component\DependencyInjection\Container;
36
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
37
38
final class BootstrapIdentityWithSmsSecondFactorCommand extends Command
39
{
40 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...
41
    {
42
        $this
43
            ->setName('middleware:bootstrap:identity-with-sms')
44
            ->setDescription('Creates an identity with a SMS second factor')
45
            ->addArgument('name-id', InputArgument::REQUIRED, 'The NameID of the identity to create')
46
            ->addArgument('institution', InputArgument::REQUIRED, 'The institution of the identity to create')
47
            ->addArgument('common-name', InputArgument::REQUIRED, 'The Common Name of the identity to create')
48
            ->addArgument('email', InputArgument::REQUIRED, 'The e-mail address of the identity to create')
49
            ->addArgument('preferred-locale', InputArgument::REQUIRED, 'The preferred locale of the identity to create')
50
            ->addArgument(
51
                'phone-number',
52
                InputArgument::REQUIRED,
53
                'The phone number of the user should be formatted like "+31 (0) 612345678"'
54
            )
55
            ->addArgument(
56
                'registration-status',
57
                InputArgument::REQUIRED,
58
                'Valid arguments: unverified, verified, vetted'
59
            );
60
    }
61
62
    protected function execute(InputInterface $input, OutputInterface $output)
63
    {
64
        /** @var Container $container */
65
        $container = $this->getApplication()->getKernel()->getContainer();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Symfony\Component\Console\Application as the method getKernel() does only exist in the following sub-classes of Symfony\Component\Console\Application: Symfony\Bundle\FrameworkBundle\Console\Application. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
66
        $tokenStorage = $container->get('security.token_storage');
67
        $identityRepository = $container->get('surfnet_stepup_middleware_api.repository.identity');
68
        $unverifiedSecondFactorRepository = $container->get(
69
            'surfnet_stepup_middleware_api.repository.unverified_second_factor'
70
        );
71
        $verifiedSecondFactorRepository = $container->get(
72
            'surfnet_stepup_middleware_api.repository.verified_second_factor'
73
        );
74
        $pipeline = $container->get('surfnet_stepup_middleware_command_handling.pipeline.transaction_aware_pipeline');
75
        $eventBus = $container->get('surfnet_stepup_middleware_command_handling.event_bus.buffered');
76
        $connection = $container->get('surfnet_stepup_middleware_middleware.dbal_connection_helper');
77
78
        $tokenStorage->setToken(
79
            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...
80
        );
81
82
        $nameId = new NameId($input->getArgument('name-id'));
83
        $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...
84
        $commonName = $input->getArgument('common-name');
85
        $email = $input->getArgument('email');
86
        $preferredLocale = $input->getArgument('preferred-locale');
87
        $registrationStatus = $input->getArgument('registration-status');
88
        $phoneNumber = $input->getArgument('phone-number');
89
        $identity = false;
90
91
        $output->writeln(
92
            sprintf(
93
                '<notice>Adding a %s SMS token for %s</notice>',
94
                $registrationStatus,
95
                $commonName
96
            )
97
        );
98
99
        if ($identityRepository->hasIdentityWithNameIdAndInstitution($nameId, $institution)) {
100
            $output->writeln(
101
                sprintf(
102
                    '<notice>An identity with name ID "%s" from institution "%s" already exists, using that identity</notice>',
103
                    $nameId->getNameId(),
104
                    $institution->getInstitution()
105
                )
106
            );
107
            $identity = $identityRepository->findOneByNameIdAndInstitution($nameId, $institution);
108
        }
109
110
        $connection->beginTransaction();
111
112
        $secondFactorId = Uuid::uuid4()->toString();
113
114
        if (!$identity) {
115
            $output->writeln('<notice>Creating a new identity</notice>');
116
            $identity = new CreateIdentityCommand();
117
            $identity->UUID = (string) Uuid::uuid4();
118
            $identity->id = (string) Uuid::uuid4();
119
            $identity->institution = $institution->getInstitution();
120
            $identity->nameId = $nameId->getNameId();
121
            $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...
122
            $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...
123
            $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...
124
            $pipeline->process($identity);
125
        }
126
127
        try {
128
            switch ($registrationStatus) {
129
                case "unverified":
130
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
131
                    $this->provePosession($pipeline, $secondFactorId, $identity, $phoneNumber);
132
                    break;
133
                case "verified":
134
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
135
                    $this->provePosession($pipeline, $secondFactorId, $identity, $phoneNumber);
136
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
137
                    $unverifiedSecondFactor = $unverifiedSecondFactorRepository->findOneBy(
138
                        ['identityId' => $identity->id, 'type' => 'sms']
139
                    );
140
                    $output->writeln('<notice>Creating a verified SMS token</notice>');
141
                    $this->verifyEmail($pipeline, $identity, $unverifiedSecondFactor);
142
                    break;
143
                case "vetted":
144
                    $output->writeln('<notice>Creating an unverified SMS token</notice>');
145
                    $this->provePosession($pipeline, $secondFactorId, $identity, $phoneNumber);
146
                    /** @var UnverifiedSecondFactor $unverifiedSecondFactor */
147
                    $unverifiedSecondFactor = $unverifiedSecondFactorRepository->findOneBy(
148
                        ['identityId' => $identity->id, 'type' => 'sms']
149
                    );
150
                    $output->writeln('<notice>Creating a verified SMS token</notice>');
151
                    $this->verifyEmail($pipeline, $identity, $unverifiedSecondFactor);
152
                    /** @var VerifiedSecondFactor $verifiedSecondFactor */
153
                    $verifiedSecondFactor = $verifiedSecondFactorRepository->findOneBy(
154
                        ['identityId' => $identity->id, 'type' => 'sms']
155
                    );
156
                    $output->writeln('<notice>Vetting the verified SMS token</notice>');
157
                    $this->vetSecondFactor($pipeline, $identity, $secondFactorId, $verifiedSecondFactor, $phoneNumber);
158
                    break;
159
            }
160
161
            $eventBus->flush();
162
            $connection->commit();
163
164
        } catch (Exception $e) {
165
            $output->writeln(
166
                sprintf(
167
                    '<error>An Error occurred when trying to bootstrap the identity: "%s"</error>',
168
                    $e->getMessage()
169
                )
170
            );
171
172
            $connection->rollBack();
173
174
            throw $e;
175
        }
176
177
        $output->writeln(
178
            sprintf(
179
                '<info>Successfully created identity with UUID %s and %s second factor with UUID %s</info>',
180
                $identity->id,
181
                $registrationStatus,
182
                $secondFactorId
183
            )
184
        );
185
    }
186
187 View Code Duplication
    private function provePosession($pipeline, $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...
188
    {
189
        $command = new ProvePhonePossessionCommand();
190
        $command->UUID = (string) Uuid::uuid4();
191
        $command->secondFactorId = $secondFactorId;
192
        $command->identityId = $identity->id;
193
        $command->phoneNumber = $phoneNumber;
194
        $pipeline->process($command);
195
    }
196
197 View Code Duplication
    private function verifyEmail($pipeline, $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...
198
    {
199
        $command = new VerifyEmailCommand();
200
        $command->UUID = (string) Uuid::uuid4();
201
        $command->identityId = $identity->id;
202
        $command->verificationNonce = $unverifiedSecondFactor->verificationNonce;
203
        $pipeline->process($command);
204
    }
205
206
    private function vetSecondFactor($pipeline, $identity, $secondFactorId, $verifiedSecondFactor, $phoneNumber)
207
    {
208
        $command = new VetSecondFactorCommand();
209
        $command->UUID = (string) Uuid::uuid4();
210
        $command->authorityId = 'db9b8bdf-720c-44ba-a4c4-154953e45f14';
211
        $command->identityId = $identity->id;
212
        $command->secondFactorId = $secondFactorId;
213
        $command->registrationCode = $verifiedSecondFactor->registrationCode;
214
        $command->secondFactorType = 'sms';
215
        $command->secondFactorIdentifier = $phoneNumber;
216
        $command->documentNumber = '123987';
217
        $command->identityVerified = true;
218
        $pipeline->process($command);
219
    }
220
}
221