GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( eac42d...55bb68 )
by François
02:33
created

OAuthModule   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 158
Duplicated Lines 1.9 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 7
dl 3
loc 158
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getAuthorize() 0 17 1
B postAuthorize() 0 42 4
B getAccessToken() 0 29 2
D validateRequest() 3 37 9
A validateClient() 0 10 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 *  Copyright (C) 2016 SURFnet.
4
 *
5
 *  This program is free software: you can redistribute it and/or modify
6
 *  it under the terms of the GNU Affero General Public License as
7
 *  published by the Free Software Foundation, either version 3 of the
8
 *  License, or (at your option) any later version.
9
 *
10
 *  This program is distributed in the hope that it will be useful,
11
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 *  GNU Affero General Public License for more details.
14
 *
15
 *  You should have received a copy of the GNU Affero General Public License
16
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace fkooman\RemoteStorage\OAuth;
20
21
use fkooman\RemoteStorage\Http\Exception\HttpException;
22
use fkooman\RemoteStorage\Http\HtmlResponse;
23
use fkooman\RemoteStorage\Http\RedirectResponse;
24
use fkooman\RemoteStorage\Http\Request;
25
use fkooman\RemoteStorage\RandomInterface;
26
use fkooman\RemoteStorage\TplInterface;
27
28
class OAuthModule
29
{
30
    /** @var \fkooman\RemoteStorage\TplInterface */
31
    private $tpl;
32
33
    /** @var \fkooman\RemoteStorage\RandomInterface */
34
    private $random;
35
36
    /** @var TokenStorage */
37
    private $tokenStorage;
38
39
    public function __construct(TplInterface $tpl, RandomInterface $random, TokenStorage $tokenStorage)
40
    {
41
        $this->tpl = $tpl;
42
        $this->random = $random;
43
        $this->tokenStorage = $tokenStorage;
44
    }
45
46
    public function getAuthorize(Request $request, $userId)
0 ignored issues
show
Unused Code introduced by
The parameter $userId is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
47
    {
48
        $this->validateRequest($request);
49
        $this->validateClient($request);
50
51
        // ask for approving this client/scope
52
        return new HtmlResponse(
53
            $this->tpl->render(
54
                'authorizeOAuthClient',
55
                [
56
                    'client_id' => $request->getQueryParameter('client_id'),
57
                    'scope' => $request->getQueryParameter('scope'),
58
                    'redirect_uri' => $request->getQueryParameter('redirect_uri'),
59
                ]
60
            )
61
        );
62
    }
63
64
    public function postAuthorize(Request $request, $userId)
65
    {
66
        $this->validateRequest($request);
67
        $this->validateClient($request);
68
69
        // state is OPTIONAL in remoteStorage specification
70
        $state = $request->getQueryParameter('state', false, null);
71
        $returnUriPattern = '%s#%s';
72
73
        if ('no' === $request->getPostParameter('approve')) {
74
            $redirectParameters = [
75
                'error' => 'access_denied',
76
                'error_description' => 'user refused authorization',
77
            ];
78
            if (!is_null($state)) {
79
                $redirectParameters['state'] = $state;
80
            }
81
            $redirectQuery = http_build_query($redirectParameters);
82
83
            $redirectUri = sprintf($returnUriPattern, $request->getQueryParameter('redirect_uri'), $redirectQuery);
84
85
            return new RedirectResponse($redirectUri, 302);
86
        }
87
88
        $accessToken = $this->getAccessToken(
89
            $userId,
90
            $request->getQueryParameter('client_id'),
91
            $request->getQueryParameter('scope')
92
        );
93
94
        // add access_token (and optionally state) to redirect_uri
95
        $redirectParameters = [
96
            'access_token' => $accessToken,
97
        ];
98
        if (!is_null($state)) {
99
            $redirectParameters['state'] = $state;
100
        }
101
        $redirectQuery = http_build_query($redirectParameters);
102
        $redirectUri = sprintf($returnUriPattern, $request->getQueryParameter('redirect_uri'), $redirectQuery);
103
104
        return new RedirectResponse($redirectUri, 302);
105
    }
106
107
    private function getAccessToken($userId, $clientId, $scope)
108
    {
109
        $existingToken = $this->tokenStorage->getExistingToken(
110
            $userId,
111
            $clientId,
112
            $scope
113
        );
114
115
        if (false !== $existingToken) {
116
            // if the user already has an access_token for this client and
117
            // scope, reuse it
118
            $accessTokenKey = $existingToken['access_token_key'];
119
            $accessToken = $existingToken['access_token'];
120
        } else {
121
            // generate a new one
122
            $accessTokenKey = $this->random->get(8);
123
            $accessToken = $this->random->get(16);
124
            // store it
125
            $this->tokenStorage->store(
126
                $userId,
127
                $accessTokenKey,
128
                $accessToken,
129
                $clientId,
130
                $scope
131
            );
132
        }
133
134
        return sprintf('%s.%s', $accessTokenKey, $accessToken);
135
    }
136
137
    private function validateRequest(Request $request)
138
    {
139
        // we enforce that all parameter are set, nothing is "OPTIONAL"
140
        $clientId = $request->getQueryParameter('client_id');
141
        if (1 !== preg_match('/^[\x20-\x7E]+$/', $clientId)) {
142
            throw new HttpException('invalid client_id', 400);
143
        }
144
145
        // XXX we also should enforce HTTPS
146
        $redirectUri = $request->getQueryParameter('redirect_uri');
147 View Code Duplication
        if (false === filter_var($redirectUri, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_PATH_REQUIRED)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
148
            throw new HttpException('invalid redirect_uri', 400);
149
        }
150
        if (false !== strpos($redirectUri, '?')) {
151
            throw new HttpException('invalid redirect_uri', 400);
152
        }
153
        $responseType = $request->getQueryParameter('response_type');
154
        if ('token' !== $responseType) {
155
            throw new HttpException('invalid response_type', 400);
156
        }
157
        // XXX make sure this regexp/code is actually correct!
158
        $scope = $request->getQueryParameter('scope');
159
        $scopeTokens = explode(' ', $scope);
160
        foreach ($scopeTokens as $scopeToken) {
161
            if (1 !== preg_match('/^\x21|[\x23-\x5B]|[\x5D-\x7E]+$/', $scopeToken)) {
162
                throw new HttpException('invalid scope', 400);
163
            }
164
        }
165
166
        // state is OPTIONAL in remoteStorage
167
        $state = $request->getQueryParameter('state', false, null);
168
        if (!is_null($state)) {
169
            if (1 !== preg_match('/^[\x20-\x7E]+$/', $state)) {
170
                throw new HttpException('invalid state', 400);
171
            }
172
        }
173
    }
174
175
    private function validateClient(Request $request)
176
    {
177
        $clientId = $request->getQueryParameter('client_id');
178
        $redirectUri = $request->getQueryParameter('redirect_uri');
179
180
        // redirectUri has to start with clientId (or be equal)
181
        if (0 !== strpos($redirectUri, $clientId)) {
182
            throw new HttpException('"redirect_uri" does not match "client_id"', 400);
183
        }
184
    }
185
}
186