Completed
Pull Request — develop (#131)
by A.
05:15 queued 02:40
created

VettingService::getProcedure()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 16
Ratio 100 %

Importance

Changes 0
Metric Value
dl 16
loc 16
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
3
/**
4
 * Copyright 2014 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\StepupRa\RaBundle\Service;
20
21
use RuntimeException;
22
use Surfnet\StepupBundle\Command\SendSmsChallengeCommand;
23
use Surfnet\StepupBundle\Command\VerifyPossessionOfPhoneCommand;
24
use Surfnet\StepupBundle\Service\SmsSecondFactor\OtpVerification;
25
use Surfnet\StepupBundle\Service\SmsSecondFactorService;
26
use Surfnet\StepupBundle\Value\PhoneNumber\InternationalPhoneNumber;
27
use Surfnet\StepupBundle\Value\SecondFactorType;
28
use Surfnet\StepupMiddlewareClientBundle\Identity\Command\VetSecondFactorCommand;
29
use Surfnet\StepupRa\RaBundle\Command\CreateU2fSignRequestCommand;
30
use Surfnet\StepupRa\RaBundle\Command\StartVettingProcedureCommand;
31
use Surfnet\StepupRa\RaBundle\Command\VerifyIdentityCommand;
32
use Surfnet\StepupRa\RaBundle\Command\VerifyU2fAuthenticationCommand;
33
use Surfnet\StepupRa\RaBundle\Command\VerifyYubikeyPublicIdCommand;
34
use Surfnet\StepupRa\RaBundle\Exception\DomainException;
35
use Surfnet\StepupRa\RaBundle\Exception\InvalidArgumentException;
36
use Surfnet\StepupRa\RaBundle\Exception\LoaTooLowException;
37
use Surfnet\StepupRa\RaBundle\Exception\UnknownVettingProcedureException;
38
use Surfnet\StepupRa\RaBundle\Repository\VettingProcedureRepository;
39
use Surfnet\StepupRa\RaBundle\Service\Gssf\VerificationResult as GssfVerificationResult;
40
use Surfnet\StepupRa\RaBundle\Service\U2f\AuthenticationVerificationResult;
41
use Surfnet\StepupRa\RaBundle\Service\U2f\SignRequestCreationResult;
42
use Surfnet\StepupRa\RaBundle\VettingProcedure;
43
use Surfnet\StepupU2fBundle\Dto\SignRequest;
44
use Surfnet\StepupU2fBundle\Dto\SignResponse;
45
use Symfony\Component\Translation\TranslatorInterface;
46
47
/**
48
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
49
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
50
 */
51
class VettingService
52
{
53
    const REGISTRATION_CODE_EXPIRED_ERROR =
54
        'Surfnet\Stepup\Exception\DomainException: Cannot vet second factor, the registration window is closed.';
55
56
    /**
57
     * @var \Surfnet\StepupBundle\Service\SmsSecondFactorService
58
     */
59
    private $smsSecondFactorService;
60
61
    /**
62
     * @var \Surfnet\StepupRa\RaBundle\Service\YubikeySecondFactorService
63
     */
64
    private $yubikeySecondFactorService;
65
66
    /**
67
     * @var \Surfnet\StepupRa\RaBundle\Service\GssfService
68
     */
69
    private $gssfService;
70
71
    /**
72
     * @var \Surfnet\StepupRa\RaBundle\Service\U2fService
73
     */
74
    private $u2fService;
75
76
    /**
77
     * @var \Surfnet\StepupRa\RaBundle\Service\CommandService
78
     */
79
    private $commandService;
80
81
    /**
82
     * @var \Surfnet\StepupRa\RaBundle\Repository\VettingProcedureRepository
83
     */
84
    private $vettingProcedureRepository;
85
86
    /**
87
     * @var \Symfony\Component\Translation\TranslatorInterface
88
     */
89
    private $translator;
90
91
    /**
92
     * @var \Surfnet\StepupRa\RaBundle\Service\IdentityService
93
     */
94
    private $identityService;
95
96
    public function __construct(
97
        SmsSecondFactorService $smsSecondFactorService,
98
        YubikeySecondFactorService $yubikeySecondFactorService,
99
        GssfService $gssfService,
100
        U2fService $u2fService,
101
        CommandService $commandService,
102
        VettingProcedureRepository $vettingProcedureRepository,
103
        TranslatorInterface $translator,
104
        IdentityService $identityService
105
    ) {
106
        $this->smsSecondFactorService = $smsSecondFactorService;
107
        $this->yubikeySecondFactorService = $yubikeySecondFactorService;
108
        $this->gssfService = $gssfService;
109
        $this->u2fService = $u2fService;
110
        $this->commandService = $commandService;
111
        $this->vettingProcedureRepository = $vettingProcedureRepository;
112
        $this->translator = $translator;
113
        $this->identityService = $identityService;
114
    }
115
116
    /**
117
     * @param StartVettingProcedureCommand $command
118
     * @return bool
119
     */
120
    public function isLoaSufficientToStartProcedure(StartVettingProcedureCommand $command)
121
    {
122
        $secondFactorType = new SecondFactorType($command->secondFactor->type);
123
124
        return $secondFactorType->isSatisfiedBy($command->authorityLoa);
125
    }
126
127
    /**
128
     * @param StartVettingProcedureCommand $command
129
     * @return string The procedure ID.
130
     */
131
    public function startProcedure(StartVettingProcedureCommand $command)
132
    {
133
        $this->smsSecondFactorService->clearSmsVerificationState();
134
135
        if (!$this->isLoaSufficientToStartProcedure($command)) {
136
            throw new LoaTooLowException(
137
                sprintf(
138
                    "Registration authority has LoA '%s', which is not enough to allow vetting of a '%s' second factor",
139
                    $command->authorityLoa,
140
                    $command->secondFactor->type
141
                )
142
            );
143
        }
144
145
        $procedure = VettingProcedure::start(
146
            $command->secondFactor->id,
147
            $command->authorityId,
148
            $command->registrationCode,
149
            $command->secondFactor
150
        );
151
152
        $this->vettingProcedureRepository->store($procedure);
153
154
        return $procedure->getId();
155
    }
156
157
    /**
158
     * @param string $procedureId
159
     * @throws UnknownVettingProcedureException
160
     */
161 View Code Duplication
    public function cancelProcedure($procedureId)
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...
162
    {
163
        if (!is_string($procedureId)) {
164
            throw InvalidArgumentException::invalidType('string', 'procedureId', $procedureId);
165
        }
166
167
        $procedure = $this->vettingProcedureRepository->retrieve($procedureId);
168
169
        if (!$procedure) {
170
            throw new UnknownVettingProcedureException(
171
                sprintf("No vetting procedure with id '%s' is known.", $procedureId)
172
            );
173
        }
174
175
        $this->vettingProcedureRepository->remove($procedureId);
176
    }
177
178
    /**
179
     * @return int
180
     */
181
    public function getSmsOtpRequestsRemainingCount()
182
    {
183
        return $this->smsSecondFactorService->getOtpRequestsRemainingCount();
184
    }
185
186
    /**
187
     * @return int
188
     */
189
    public function getSmsMaximumOtpRequestsCount()
190
    {
191
        return $this->smsSecondFactorService->getMaximumOtpRequestsCount();
192
    }
193
194
    /**
195
     * @param string $procedureId
196
     * @param SendSmsChallengeCommand $command
197
     * @return bool
198
     * @throws UnknownVettingProcedureException
199
     * @throws RuntimeException
200
     */
201
    public function sendSmsChallenge($procedureId, SendSmsChallengeCommand $command)
202
    {
203
        $procedure = $this->getProcedure($procedureId);
204
205
        $phoneNumber = InternationalPhoneNumber::fromStringFormat(
206
            $procedure->getSecondFactor()->secondFactorIdentifier
207
        );
208
209
        $identity = $this->identityService->findById($procedure->getSecondFactor()->identityId);
210
211
        if (!$identity) {
212
            throw new RuntimeException("Second factor is coupled to an identity that doesn't exist");
213
        }
214
215
        $command->phoneNumber = $phoneNumber;
216
        $command->body        = $this->translator->trans('ra.vetting.sms.challenge_body', [], 'messages', $identity->preferredLocale);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
217
        $command->identity    = $procedure->getSecondFactor()->identityId;
218
        $command->institution = $procedure->getSecondFactor()->institution;
219
220
        return $this->smsSecondFactorService->sendChallenge($command);
221
    }
222
223
    /**
224
     * @param string                   $procedureId
225
     * @param VerifyPossessionOfPhoneCommand $command
226
     * @return OtpVerification
227
     * @throws UnknownVettingProcedureException
228
     * @throws DomainException
229
     */
230
    public function verifyPhoneNumber($procedureId, VerifyPossessionOfPhoneCommand $command)
231
    {
232
        $procedure = $this->getProcedure($procedureId);
233
234
        $verification = $this->smsSecondFactorService->verifyPossession($command);
235
236
        if (!$verification->wasSuccessful()) {
237
            return $verification;
238
        }
239
240
        $procedure->verifySecondFactorIdentifier($verification->getPhoneNumber());
241
        $this->vettingProcedureRepository->store($procedure);
0 ignored issues
show
Bug introduced by
It seems like $procedure defined by $this->getProcedure($procedureId) on line 232 can be null; however, Surfnet\StepupRa\RaBundl...dureRepository::store() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
242
243
        return $verification;
244
    }
245
246
    /**
247
     * @param string                       $procedureId
248
     * @param VerifyYubikeyPublicIdCommand $command
249
     * @return YubikeySecondFactor\VerificationResult
250
     */
251
    public function verifyYubikeyPublicId($procedureId, VerifyYubikeyPublicIdCommand $command)
252
    {
253
        $procedure = $this->getProcedure($procedureId);
254
255
        $command->expectedPublicId = $procedure->getSecondFactor()->secondFactorIdentifier;
256
        $command->identityId = $procedure->getSecondFactor()->identityId;
257
        $command->institution = $procedure->getSecondFactor()->institution;
258
259
        $result = $this->yubikeySecondFactorService->verifyYubikeyPublicId($command);
260
261
        if ($result->didPublicIdMatch()) {
262
            $procedure->verifySecondFactorIdentifier($result->getPublicId()->getYubikeyPublicId());
263
264
            $this->vettingProcedureRepository->store($procedure);
0 ignored issues
show
Bug introduced by
It seems like $procedure defined by $this->getProcedure($procedureId) on line 253 can be null; however, Surfnet\StepupRa\RaBundl...dureRepository::store() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
265
        }
266
267
        return $result;
268
    }
269
270
    /**
271
     * @param string $procedureId
272
     */
273
    public function startGssfVerification($procedureId)
274
    {
275
        $procedure = $this->getProcedure($procedureId);
276
277
        $this->gssfService->startVerification($procedure->getSecondFactor()->secondFactorIdentifier, $procedureId);
278
    }
279
280
    /**
281
     * @param string $gssfId
282
     * @return GssfVerificationResult
283
     */
284
    public function verifyGssfId($gssfId)
285
    {
286
        $result = $this->gssfService->verify($gssfId);
287
288
        if (!$result->isSuccess()) {
289
            return $result;
290
        }
291
292
        $procedure = $this->getProcedure($result->getProcedureId());
293
        $procedure->verifySecondFactorIdentifier($gssfId);
294
295
        $this->vettingProcedureRepository->store($procedure);
0 ignored issues
show
Bug introduced by
It seems like $procedure defined by $this->getProcedure($result->getProcedureId()) on line 292 can be null; however, Surfnet\StepupRa\RaBundl...dureRepository::store() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
296
297
        return $result;
298
    }
299
300
    /**
301
     * @param string $procedureId
302
     * @return SignRequestCreationResult
303
     */
304
    public function createU2fSignRequest($procedureId)
305
    {
306
        $procedure = $this->getProcedure($procedureId);
307
308
        $command = new CreateU2fSignRequestCommand();
309
        $command->keyHandle = $procedure->getSecondFactor()->secondFactorIdentifier;
310
        $command->identityId = $procedure->getSecondFactor()->identityId;
311
        $command->institution = $procedure->getSecondFactor()->institution;
312
313
        return $this->u2fService->createSignRequest($command);
314
    }
315
316
    /**
317
     * @param string       $procedureId
318
     * @param SignRequest  $signRequest
319
     * @param SignResponse $signResponse
320
     * @return AuthenticationVerificationResult
321
     */
322
    public function verifyU2fAuthentication($procedureId, SignRequest $signRequest, SignResponse $signResponse)
323
    {
324
        $procedure = $this->getProcedure($procedureId);
325
326
        $command = new VerifyU2fAuthenticationCommand();
327
        $command->identityId = $procedure->getSecondFactor()->identityId;
328
        $command->institution = $procedure->getSecondFactor()->institution;
329
        $command->signRequest = $signRequest;
330
        $command->signResponse = $signResponse;
331
332
        $result = $this->u2fService->verifyAuthentication($command);
333
334
        if ($result->wasSuccessful()) {
335
            $procedure->verifySecondFactorIdentifier($signResponse->keyHandle);
336
            $this->vettingProcedureRepository->store($procedure);
0 ignored issues
show
Bug introduced by
It seems like $procedure defined by $this->getProcedure($procedureId) on line 324 can be null; however, Surfnet\StepupRa\RaBundl...dureRepository::store() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
337
        }
338
339
        return $result;
340
    }
341
342
    /**
343
     * @param string $procedureId
344
     * @param VerifyIdentityCommand $command
345
     * @return void
346
     * @throws UnknownVettingProcedureException
347
     * @throws DomainException
348
     */
349
    public function verifyIdentity($procedureId, VerifyIdentityCommand $command)
350
    {
351
        $procedure = $this->getProcedure($procedureId);
352
        $procedure->verifyIdentity($command->documentNumber, $command->identityVerified);
353
354
        $this->vettingProcedureRepository->store($procedure);
0 ignored issues
show
Bug introduced by
It seems like $procedure defined by $this->getProcedure($procedureId) on line 351 can be null; however, Surfnet\StepupRa\RaBundl...dureRepository::store() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
355
    }
356
357
    /**
358
     * @param string $procedureId
359
     * @return \Surfnet\StepupMiddlewareClient\Service\ExecutionResult
360
     * @throws UnknownVettingProcedureException
361
     * @throws DomainException
362
     */
363
    public function vet($procedureId)
364
    {
365
        $procedure = $this->getProcedure($procedureId);
366
        $procedure->vet();
367
368
        $command = new VetSecondFactorCommand();
369
        $command->authorityId = $procedure->getAuthorityId();
370
        $command->identityId = $procedure->getSecondFactor()->identityId;
371
        $command->secondFactorId = $procedure->getSecondFactor()->id;
372
        $command->registrationCode = $procedure->getRegistrationCode();
373
        $command->secondFactorType = $procedure->getSecondFactor()->type;
374
        $command->secondFactorIdentifier = $procedure->getInputSecondFactorIdentifier();
375
        $command->documentNumber = $procedure->getDocumentNumber();
376
        $command->identityVerified = $procedure->isIdentityVerified();
377
378
        $result = $this->commandService->execute($command);
379
380
        if ($result->isSuccessful()) {
381
            $this->vettingProcedureRepository->remove($procedureId);
382
        }
383
384
        return $result;
385
    }
386
387
    /**
388
     * @param string $procedureId
389
     * @return string
390
     * @throws UnknownVettingProcedureException
391
     */
392
    public function getIdentityCommonName($procedureId)
393
    {
394
        return $this->getProcedure($procedureId)->getSecondFactor()->commonName;
395
    }
396
397
    /**
398
     * @param $procedureId
399
     * @return string
400
     * @throws UnknownVettingProcedureException
401
     */
402
    public function getSecondFactorIdentifier($procedureId)
403
    {
404
        return $this->getProcedure($procedureId)->getSecondFactor()->secondFactorIdentifier;
405
    }
406
407
    /**
408
     * @param string $procedureId
409
     * @return null|VettingProcedure
410
     * @throws UnknownVettingProcedureException
411
     */
412 View Code Duplication
    private function getProcedure($procedureId)
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...
413
    {
414
        if (!is_string($procedureId)) {
415
            throw InvalidArgumentException::invalidType('string', 'procedureId', $procedureId);
416
        }
417
418
        $procedure = $this->vettingProcedureRepository->retrieve($procedureId);
419
420
        if (!$procedure) {
421
            throw new UnknownVettingProcedureException(
422
                sprintf("No vetting procedure with id '%s' is known.", $procedureId)
423
            );
424
        }
425
426
        return $procedure;
427
    }
428
429
    /**
430
     * @param string $procedureId
431
     * @return bool
432
     */
433
    public function hasProcedure($procedureId)
434
    {
435
        if (!is_string($procedureId)) {
436
            throw InvalidArgumentException::invalidType('string', 'procedureId', $procedureId);
437
        }
438
439
        return $this->vettingProcedureRepository->retrieve($procedureId) !== null;
440
    }
441
}
442