Completed
Push — feature/improve-input-validati... ( 8f7b6e )
by Michiel
02:14
created

AbstractBootstrapCommand::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 6
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 Rhumsaa\Uuid\Uuid;
23
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\Command as MiddlewareCommand;
24
use Surfnet\StepupMiddleware\CommandHandlingBundle\Command\Metadata;
25
use Surfnet\StepupMiddleware\CommandHandlingBundle\EventSourcing\MetadataEnricher;
26
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VerifyEmailCommand;
27
use Surfnet\StepupMiddleware\CommandHandlingBundle\Identity\Command\VetSecondFactorCommand;
28
use Surfnet\StepupMiddleware\CommandHandlingBundle\Pipeline\Pipeline;
29
use Surfnet\StepupMiddleware\MiddlewareBundle\Exception\InvalidArgumentException;
30
use Surfnet\StepupMiddleware\MiddlewareBundle\Service\DBALConnectionHelper;
31
use Surfnet\StepupMiddleware\MiddlewareBundle\Service\TokenBootstrapService;
32
use Symfony\Component\Console\Command\Command;
33
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
34
35
abstract class AbstractBootstrapCommand extends Command
36
{
37
    /** @var Pipeline  */
38
    private $pipeline;
39
    /** @var EventBusInterface  */
40
    private $eventBus;
41
    /** @var DBALConnectionHelper  */
42
    private $connection;
43
    /** @var TokenStorageInterface */
44
    protected $tokenStorage;
45
    /** @var MetadataEnricher */
46
    private $enricher;
47
    /** @var TokenBootstrapService */
48
    protected $tokenBootstrapService;
49
50
    private $validRegistrationStatuses = ['unverified', 'verified', 'vetted'];
51
52
    public function __construct(
53
        Pipeline $pipeline,
54
        EventBusInterface $eventBus,
55
        DBALConnectionHelper $connection,
56
        MetadataEnricher $enricher,
57
        TokenStorageInterface $tokenStorage,
58
        TokenBootstrapService $tokenBootstrapService
59
    ) {
60
        $this->pipeline = $pipeline;
61
        $this->eventBus = $eventBus;
62
        $this->connection = $connection;
63
        $this->enricher = $enricher;
64
        $this->tokenStorage = $tokenStorage;
65
        $this->tokenBootstrapService = $tokenBootstrapService;
66
        parent::__construct();
67
    }
68
69
    protected function beginTransaction()
70
    {
71
        $this->connection->beginTransaction();
72
    }
73
74
    protected function finishTransaction()
75
    {
76
        $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...
77
        $this->connection->commit();
78
    }
79
80
    protected function rollback()
81
    {
82
        $this->connection->rollBack();
83
    }
84
85
    protected function process(MiddlewareCommand $command)
86
    {
87
        $this->pipeline->process($command);
88
    }
89
90
    /**
91
     * @param string $registrationStatus
92
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
93
     */
94
    protected function validRegistrationStatus($registrationStatus)
95
    {
96
        if (!in_array($registrationStatus, $this->validRegistrationStatuses)){
97
            throw new InvalidArgumentException(
98
                sprintf(
99
                    'Invalid argument provided for the "registration-status" argument. One of: %s is expected. Received: "%s"',
100
                    implode(', ', $this->validRegistrationStatuses),
101
                    $registrationStatus
102
                )
103
            );
104
        }
105
    }
106
107
    protected function requiresMailVerification($institution)
108
    {
109
        $configuration = $this->tokenBootstrapService->findConfigurationOptionsFor($institution);
110
        if ($configuration) {
111
            return $configuration->verifyEmailOption->isEnabled();
112
        }
113
        return true;
114
    }
115
116
    protected function vetSecondFactor($tokenType, $actorId, $identity, $secondFactorId, $verifiedSecondFactor, $phoneNumber)
117
    {
118
        $command = new VetSecondFactorCommand();
119
        $command->UUID = (string) Uuid::uuid4();
120
        $command->authorityId = $actorId;
121
        $command->identityId = $identity->id;
122
        $command->secondFactorId = $secondFactorId;
123
        $command->registrationCode = $verifiedSecondFactor->registrationCode;
124
        $command->secondFactorType = $tokenType;
125
        $command->secondFactorIdentifier = $phoneNumber;
126
        $command->documentNumber = '123987';
127
        $command->identityVerified = true;
128
        $this->pipeline->process($command);
129
    }
130
131
    protected function enrichEventMetadata($actorId)
132
    {
133
        $actor = $this->tokenBootstrapService->findIdentityById($actorId);
134
        $metadata = new Metadata();
135
        $metadata->actorId = $actor->id;
136
        $metadata->actorInstitution = $actor->institution;
137
        $this->enricher->setMetadata($metadata);
138
    }
139
140
    protected function verifyEmail($identity, $unverifiedSecondFactor)
141
    {
142
        $command = new VerifyEmailCommand();
143
        $command->UUID = (string)Uuid::uuid4();
144
        $command->identityId = $identity->id;
145
        $command->verificationNonce = $unverifiedSecondFactor->verificationNonce;
146
        $this->process($command);
147
    }
148
}
149