Completed
Pull Request — master (#25920)
by Thomas
19:33
created

TwoFactorChallengeController   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 131
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 131
rs 10
wmc 12
lcom 1
cbo 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A getLogoutAttribute() 0 3 1
A selectChallenge() 0 11 1
A solveChallenge() 0 20 4
B showChallenge() 0 32 5
1
<?php
2
/**
3
 * @author Christoph Wurst <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 *
6
 * @copyright Copyright (c) 2016, ownCloud GmbH.
7
 * @license AGPL-3.0
8
 *
9
 * This code is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License, version 3,
11
 * as published by the Free Software Foundation.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License, version 3,
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
20
 *
21
 */
22
23
namespace OC\Core\Controller;
24
25
use OC\Authentication\TwoFactorAuth\Manager;
26
use OCP\AppFramework\Controller;
27
use OCP\AppFramework\Http\RedirectResponse;
28
use OCP\AppFramework\Http\TemplateResponse;
29
use OCP\IRequest;
30
use OCP\ISession;
31
use OCP\IURLGenerator;
32
use OCP\IUserSession;
33
34
class TwoFactorChallengeController extends Controller {
35
36
	/** @var Manager */
37
	private $twoFactorManager;
38
39
	/** @var IUserSession */
40
	private $userSession;
41
42
	/** @var ISession */
43
	private $session;
44
45
	/** @var IURLGenerator */
46
	private $urlGenerator;
47
48
	/**
49
	 * @param string $appName
50
	 * @param IRequest $request
51
	 * @param Manager $twoFactorManager
52
	 * @param IUserSession $userSession
53
	 * @param ISession $session
54
	 * @param IURLGenerator $urlGenerator
55
	 */
56
	public function __construct($appName, IRequest $request, Manager $twoFactorManager, IUserSession $userSession,
57
		ISession $session, IURLGenerator $urlGenerator) {
58
		parent::__construct($appName, $request);
59
		$this->twoFactorManager = $twoFactorManager;
60
		$this->userSession = $userSession;
61
		$this->session = $session;
62
		$this->urlGenerator = $urlGenerator;
63
	}
64
65
	/**
66
	 * @return string
67
	 */
68
	protected function getLogoutAttribute() {
69
		return \OC_User::getLogoutAttribute();
70
	}
71
72
	/**
73
	 * @NoAdminRequired
74
	 * @NoCSRFRequired
75
	 *
76
	 * @param string $redirect_url
77
	 * @return TemplateResponse
78
	 */
79
	public function selectChallenge($redirect_url) {
80
		$user = $this->userSession->getUser();
81
		$providers = $this->twoFactorManager->getProviders($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 80 can be null; however, OC\Authentication\TwoFac...Manager::getProviders() 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...
82
83
		$data = [
84
			'providers' => $providers,
85
			'redirect_url' => $redirect_url,
86
			'logout_attribute' => $this->getLogoutAttribute(),
87
		];
88
		return new TemplateResponse($this->appName, 'twofactorselectchallenge', $data, 'guest');
89
	}
90
91
	/**
92
	 * @NoAdminRequired
93
	 * @NoCSRFRequired
94
	 * @UseSession
95
	 *
96
	 * @param string $challengeProviderId
97
	 * @param string $redirect_url
98
	 * @return TemplateResponse
99
	 */
100
	public function showChallenge($challengeProviderId, $redirect_url) {
101
		$user = $this->userSession->getUser();
102
		$provider = $this->twoFactorManager->getProvider($user, $challengeProviderId);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 101 can be null; however, OC\Authentication\TwoFac...\Manager::getProvider() 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...
103
		if (is_null($provider)) {
104
			return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \OCP\AppFrame...nge.selectChallenge')); (OCP\AppFramework\Http\RedirectResponse) is incompatible with the return type documented by OC\Core\Controller\TwoFa...ntroller::showChallenge of type OCP\AppFramework\Http\TemplateResponse.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
105
		}
106
107
		if ($this->session->exists('two_factor_auth_error')) {
108
			$this->session->remove('two_factor_auth_error');
109
			$error = true;
110
		} else {
111
			$error = false;
112
		}
113
		//Attempt to get custom ContentSecurityPolicy(CSP) from 2FA provider
114
		if ($provider instanceof \OCP\Authentication\TwoFactorAuth\IProvider2) {
115
			$csp  = $provider->getCSP();
116
		}
117
		$tmpl = $provider->getTemplate($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 101 can be null; however, OCP\Authentication\TwoFa...Provider::getTemplate() 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...
118
		$tmpl->assign('redirect_url', $redirect_url);
119
		$data = [
120
			'error' => $error,
121
			'provider' => $provider,
122
			'logout_attribute' => $this->getLogoutAttribute(),
123
			'template' => $tmpl->fetchPage(),
124
		];
125
		//Generate the response and add the custom CSP (if defined)
126
		$response = new TemplateResponse($this->appName, 'twofactorshowchallenge', $data, 'guest');
127
		if (!is_null($csp)) {
128
			$response->setContentSecurityPolicy($csp);
0 ignored issues
show
Bug introduced by
The variable $csp does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
129
		}
130
		return $response;
131
	}	
132
133
	/**
134
	 * @NoAdminRequired
135
	 * @NoCSRFRequired
136
	 * @UseSession
137
	 *
138
	 * @param string $challengeProviderId
139
	 * @param string $challenge
140
	 * @param string $redirect_url
141
	 * @return RedirectResponse
142
	 */
143
	public function solveChallenge($challengeProviderId, $challenge, $redirect_url = null) {
144
		$user = $this->userSession->getUser();
145
		$provider = $this->twoFactorManager->getProvider($user, $challengeProviderId);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 144 can be null; however, OC\Authentication\TwoFac...\Manager::getProvider() 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...
146
		if (is_null($provider)) {
147
			return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
148
		}
149
150
		if ($this->twoFactorManager->verifyChallenge($challengeProviderId, $user, $challenge)) {
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->userSession->getUser() on line 144 can be null; however, OC\Authentication\TwoFac...ager::verifyChallenge() 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...
151
			if (!is_null($redirect_url)) {
152
				return new RedirectResponse($this->urlGenerator->getAbsoluteURL(urldecode($redirect_url)));
153
			}
154
			return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
155
		}
156
157
		$this->session->set('two_factor_auth_error', true);
158
		return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.showChallenge', [
159
			'challengeProviderId' => $provider->getId(),
160
			'redirect_url' => $redirect_url,
161
		]));
162
	}
163
164
}
165