Completed
Push — bugfix/institution-based-on-sh... ( 23e8a9 )
by
unknown
02:11
created

resolveHighestRequiredLoa()   D

Complexity

Conditions 16
Paths 216

Size

Total Lines 106
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 106
rs 4.2926
cc 16
eloc 57
nc 216
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\StepupGateway\GatewayBundle\Service;
20
21
use Doctrine\Common\Collections\ArrayCollection;
22
use Psr\Log\LoggerInterface;
23
use Surfnet\SamlBundle\Entity\ServiceProvider;
24
use Surfnet\StepupBundle\Command\SendSmsChallengeCommand as StepupSendSmsChallengeCommand;
25
use Surfnet\StepupBundle\Command\VerifyPossessionOfPhoneCommand;
26
use Surfnet\StepupBundle\Service\LoaResolutionService;
27
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
28
use Surfnet\StepupBundle\Service\SmsSecondFactor\OtpVerification;
29
use Surfnet\StepupBundle\Service\SmsSecondFactorService;
30
use Surfnet\StepupBundle\Value\Loa;
31
use Surfnet\StepupBundle\Value\PhoneNumber\InternationalPhoneNumber;
32
use Surfnet\StepupBundle\Value\YubikeyOtp;
33
use Surfnet\StepupBundle\Value\YubikeyPublicId;
34
use Surfnet\StepupGateway\ApiBundle\Dto\Otp as ApiOtp;
35
use Surfnet\StepupGateway\ApiBundle\Dto\Requester;
36
use Surfnet\StepupGateway\ApiBundle\Service\YubikeyService;
37
use Surfnet\StepupGateway\GatewayBundle\Command\SendSmsChallengeCommand;
38
use Surfnet\StepupGateway\GatewayBundle\Command\VerifyYubikeyOtpCommand;
39
use Surfnet\StepupGateway\GatewayBundle\Entity\SecondFactor;
40
use Surfnet\StepupGateway\GatewayBundle\Entity\SecondFactorRepository;
41
use Surfnet\StepupGateway\GatewayBundle\Exception\RuntimeException;
42
use Surfnet\StepupGateway\GatewayBundle\Service\StepUp\YubikeyOtpVerificationResult;
43
use Symfony\Component\Translation\TranslatorInterface;
44
45
/**
46
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
47
 */
48
class StepUpAuthenticationService
49
{
50
    /**
51
     * @var \Surfnet\StepupBundle\Service\LoaResolutionService
52
     */
53
    private $loaResolutionService;
54
55
    /**
56
     * @var \Surfnet\StepupGateway\GatewayBundle\Entity\SecondFactorRepository
57
     */
58
    private $secondFactorRepository;
59
60
    /**
61
     * @var \Surfnet\StepupGateway\ApiBundle\Service\YubikeyService
62
     */
63
    private $yubikeyService;
64
65
    /**
66
     * @var \Surfnet\StepupBundle\Service\SmsSecondFactorService
67
     */
68
    private $smsService;
69
70
    /** @var InstitutionMatchingHelper */
71
    private $institutionMatchingHelper;
72
73
    /**
74
     * @var \Symfony\Component\Translation\TranslatorInterface
75
     */
76
    private $translator;
77
78
    /**
79
     * @var \Psr\Log\LoggerInterface
80
     */
81
    private $logger;
82
83
    /**
84
     * @var SecondFactorTypeService
85
     */
86
    private $secondFactorTypeService;
87
88
    /**
89
     * @param LoaResolutionService   $loaResolutionService
90
     * @param SecondFactorRepository $secondFactorRepository
91
     * @param YubikeyService         $yubikeyService
92
     * @param SmsSecondFactorService $smsService
93
     * @param InstitutionMatchingHelper $institutionMatchingHelper
94
     * @param TranslatorInterface    $translator
95
     * @param LoggerInterface        $logger
96
     * @param SecondFactorTypeService $secondFactorTypeService
97
     */
98
    public function __construct(
99
        LoaResolutionService $loaResolutionService,
100
        SecondFactorRepository $secondFactorRepository,
101
        YubikeyService $yubikeyService,
102
        SmsSecondFactorService $smsService,
103
        InstitutionMatchingHelper $institutionMatchingHelper,
104
        TranslatorInterface $translator,
105
        LoggerInterface $logger,
106
        SecondFactorTypeService $secondFactorTypeService
107
    ) {
108
        $this->loaResolutionService = $loaResolutionService;
109
        $this->secondFactorRepository = $secondFactorRepository;
110
        $this->yubikeyService = $yubikeyService;
111
        $this->smsService = $smsService;
112
        $this->institutionMatchingHelper = $institutionMatchingHelper;
113
        $this->translator = $translator;
114
        $this->logger = $logger;
115
        $this->secondFactorTypeService = $secondFactorTypeService;
116
    }
117
118
    /**
119
     * @param string $identityNameId
120
     * @param Loa $requiredLoa
121
     * @param WhitelistService $whitelistService
122
     * @return \Doctrine\Common\Collections\Collection
123
     */
124
    public function determineViableSecondFactors(
125
        $identityNameId,
126
        Loa $requiredLoa,
127
        WhitelistService $whitelistService
128
    ) {
129
130
        $candidateSecondFactors = $this->secondFactorRepository->getAllMatchingFor(
131
            $requiredLoa,
132
            $identityNameId,
133
            $this->secondFactorTypeService
134
        );
135
        $this->logger->info(
136
            sprintf('Loaded %d matching candidate second factors', count($candidateSecondFactors))
137
        );
138
139
        foreach ($candidateSecondFactors as $key => $secondFactor) {
140
            if (!$whitelistService->contains($secondFactor->institution)) {
141
                $this->logger->notice(
142
                    sprintf(
143
                        'Second factor "%s" is listed for institution "%s" which is not on the whitelist',
144
                        $secondFactor->secondFactorId,
145
                        $secondFactor->institution
146
                    )
147
                );
148
149
                $candidateSecondFactors->remove($key);
150
            }
151
        }
152
153
        if ($candidateSecondFactors->isEmpty()) {
154
            $this->logger->alert('No suitable candidate second factors found, sending Loa cannot be given response');
155
        }
156
157
        return $candidateSecondFactors;
158
    }
159
160
    /**
161
     * @param string $requestedLoa
162
     * @param $identityNameId
163
     * @param string $identityInstitution
164
     * @param ServiceProvider $serviceProvider
165
     * @return null|Loa
166
     * @SuppressWarnings(PHPMD.CyclomaticComplexity) see https://www.pivotaltracker.com/story/show/96065350
167
     * @SuppressWarnings(PHPMD.NPathComplexity)      see https://www.pivotaltracker.com/story/show/96065350
168
     */
169
    public function resolveHighestRequiredLoa(
170
        $requestedLoa,
171
        $identityNameId,
172
        $identityInstitution,
173
        ServiceProvider $serviceProvider
174
    ) {
175
        $loaCandidates = new ArrayCollection();
176
177
        if ($requestedLoa) {
178
            $loaCandidates->add($requestedLoa);
179
            $this->logger->info(sprintf('Added requested Loa "%s" as candidate', $requestedLoa));
180
        }
181
182
        $spConfiguredLoas = $serviceProvider->get('configuredLoas');
183
184
        if (!$loaCandidates->contains($spConfiguredLoas['__default__'])) {
185
            $loaCandidates->add($spConfiguredLoas['__default__']);
186
        }
187
188
        if (count($spConfiguredLoas) > 1 && is_null($identityInstitution)) {
189
            throw new RuntimeException(
190
                'SP configured LOA\'s are applicable but the authenticating user has no' .
191
                'schacHomeOrganization in the assertion.'
192
            );
193
        }
194
195
        $this->logger->info(sprintf('Added SP\'s default Loa "%s" as candidate', $spConfiguredLoas['__default__']));
196
197
        // Load the institutions the user has vetted a second factor
198
        $institutionsBasedOnVettedTokens = $this->determineInstitutionsByIdentityNameId($identityNameId);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $institutionsBasedOnVettedTokens exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
199
200
        if (!is_null($identityInstitution) && !empty($institutionsBasedOnVettedTokens)) {
201
            $institutionMatches = $this->institutionMatchingHelper->findMatches(
202
                $institutionsBasedOnVettedTokens,
203
                [$identityInstitution]
204
            );
205
206
            if (empty($institutionMatches)) {
207
                throw new RuntimeException(
208
                    'None of the authenticating users tokens are registered at an institution the user is currently' .
209
                    'authenticating from.'
210
                );
211
            }
212
        }
213
214
        // Add the SHO of the authenticating user to the list of institutions based on vetted tokens. This ensures the
215
        // correct LOA can be based on the organisation of the user.
216
        // There is a chance the user has no vetted tokens. In that case the user will not be granted access to the SP
217
        // if the LOA is higher than LOA1 @see https://www.pivotaltracker.com/story/show/153594101
218
        $institutionsBasedOnVettedTokens[] = $identityInstitution;
219
220
        $this->logger->info(sprintf('Loaded institution(s) for "%s"', $identityNameId));
221
222
        // Match the users institutions loas against the SP configured institutions
223
        $matchingInstitutions = $this->institutionMatchingHelper->findMatches(
224
            array_keys($spConfiguredLoas),
225
            $institutionsBasedOnVettedTokens
226
        );
227
228
        if (count($matchingInstitutions) > 0) {
229
            $this->logger->info('Found matching SP configured LoA\'s');
230
            foreach ($matchingInstitutions as $matchingInstitution) {
231
                $loaCandidates->add($spConfiguredLoas[$matchingInstitution]);
232
                $this->logger->info(sprintf(
233
                    'Added SP\'s Loa "%s" as candidate',
234
                    $spConfiguredLoas[$matchingInstitution]
235
                ));
236
            }
237
        }
238
239
        if (!count($loaCandidates)) {
240
            throw new RuntimeException('No Loa can be found, at least one Loa (SP default) should be found');
241
        }
242
243
        $actualLoas = new ArrayCollection();
244
        foreach ($loaCandidates as $loaDefinition) {
245
            $loa = $this->loaResolutionService->getLoa($loaDefinition);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $loa is correct as $this->loaResolutionServ...>getLoa($loaDefinition) (which targets Surfnet\StepupBundle\Ser...lutionService::getLoa()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
246
            if ($loa) {
247
                $actualLoas->add($loa);
248
            }
249
        }
250
251
        if (!count($actualLoas)) {
252
            $this->logger->info(sprintf(
253
                'Out of "%d" candidates, no existing Loa could be found, no authentication is possible.',
254
                count($loaCandidates)
255
            ));
256
257
            return null;
258
        }
259
260
        /** @var \Surfnet\StepupBundle\Value\Loa $highestLoa */
261
        $highestLoa = $actualLoas->first();
262
        foreach ($actualLoas as $loa) {
263
            // if the current highest Loa cannot satisfy the next Loa, that must be of a higher level...
264
            if (!$highestLoa->canSatisfyLoa($loa)) {
265
                $highestLoa = $loa;
266
            }
267
        }
268
269
        $this->logger->info(
270
            sprintf('Out of %d candidate Loa\'s, Loa "%s" is the highest', count($loaCandidates), $highestLoa)
271
        );
272
273
        return $highestLoa;
274
    }
275
276
    /**
277
     * Returns whether the given Loa identifier identifies the minimum Loa, intrinsic to being authenticated via an IdP.
278
     *
279
     * @param Loa $loa
280
     * @return bool
281
     */
282
    public function isIntrinsicLoa(Loa $loa)
283
    {
284
        return $loa->levelIsLowerOrEqualTo(Loa::LOA_1);
285
    }
286
287
    /**
288
     * @param VerifyYubikeyOtpCommand $command
289
     * @return YubikeyOtpVerificationResult
290
     */
291
    public function verifyYubikeyOtp(VerifyYubikeyOtpCommand $command)
292
    {
293
        /** @var SecondFactor $secondFactor */
294
        $secondFactor = $this->secondFactorRepository->findOneBySecondFactorId($command->secondFactorId);
295
296
        $requester = new Requester();
297
        $requester->identity = $secondFactor->identityId;
298
        $requester->institution = $secondFactor->institution;
299
300
        $otp = new ApiOtp();
301
        $otp->value = $command->otp;
302
303
        $result = $this->yubikeyService->verify($otp, $requester);
304
305
        if (!$result->isSuccessful()) {
306
            return new YubikeyOtpVerificationResult(YubikeyOtpVerificationResult::RESULT_OTP_VERIFICATION_FAILED, null);
307
        }
308
309
        $otp = YubikeyOtp::fromString($command->otp);
310
        $publicId = YubikeyPublicId::fromOtp($otp);
311
312
        if (!$publicId->equals(new YubikeyPublicId($secondFactor->secondFactorIdentifier))) {
313
            return new YubikeyOtpVerificationResult(
314
                YubikeyOtpVerificationResult::RESULT_PUBLIC_ID_DID_NOT_MATCH,
315
                $publicId
316
            );
317
        }
318
319
        return new YubikeyOtpVerificationResult(YubikeyOtpVerificationResult::RESULT_PUBLIC_ID_MATCHED, $publicId);
320
    }
321
322
    /**
323
     * @param string $secondFactorId
324
     * @return string
325
     */
326
    public function getSecondFactorIdentifier($secondFactorId)
327
    {
328
        /** @var SecondFactor $secondFactor */
329
        $secondFactor = $this->secondFactorRepository->findOneBySecondFactorId($secondFactorId);
330
331
        return $secondFactor->secondFactorIdentifier;
332
    }
333
334
    /**
335
     * @return int
336
     */
337
    public function getSmsOtpRequestsRemainingCount()
338
    {
339
        return $this->smsService->getOtpRequestsRemainingCount();
340
    }
341
342
    /**
343
     * @return int
344
     */
345
    public function getSmsMaximumOtpRequestsCount()
346
    {
347
        return $this->smsService->getMaximumOtpRequestsCount();
348
    }
349
350
    /**
351
     * @param SendSmsChallengeCommand $command
352
     * @return bool
353
     */
354
    public function sendSmsChallenge(SendSmsChallengeCommand $command)
355
    {
356
        /** @var SecondFactor $secondFactor */
357
        $secondFactor = $this->secondFactorRepository->findOneBySecondFactorId($command->secondFactorId);
358
359
        $phoneNumber = InternationalPhoneNumber::fromStringFormat($secondFactor->secondFactorIdentifier);
360
361
        $stepupCommand = new StepupSendSmsChallengeCommand();
362
        $stepupCommand->phoneNumber = $phoneNumber;
363
        $stepupCommand->body = $this->translator->trans('gateway.second_factor.sms.challenge_body');
364
        $stepupCommand->identity = $secondFactor->identityId;
365
        $stepupCommand->institution = $secondFactor->institution;
366
367
        return $this->smsService->sendChallenge($stepupCommand);
368
    }
369
370
    /**
371
     * @param VerifyPossessionOfPhoneCommand $command
372
     * @return OtpVerification
373
     */
374
    public function verifySmsChallenge(VerifyPossessionOfPhoneCommand $command)
375
    {
376
        return $this->smsService->verifyPossession($command);
377
    }
378
379
    public function clearSmsVerificationState()
380
    {
381
        $this->smsService->clearSmsVerificationState();
382
    }
383
384
    private function determineInstitutionsByIdentityNameId($identityNameId)
385
    {
386
        return $this->secondFactorRepository->getAllInstitutions($identityNameId);
387
    }
388
}
389