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 ( 994736...366350 )
by François
08:25 queued 05:01
created

OAuthModule::validateRequest()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 30
Code Lines 14

Duplication

Lines 3
Ratio 10 %

Importance

Changes 0
Metric Value
dl 3
loc 30
rs 8.439
c 0
b 0
f 0
cc 5
eloc 14
nc 5
nop 1
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\Config;
22
use fkooman\RemoteStorage\Http\Exception\HttpException;
23
use fkooman\RemoteStorage\Http\HtmlResponse;
24
use fkooman\RemoteStorage\Http\RedirectResponse;
25
use fkooman\RemoteStorage\Http\Request;
26
use fkooman\RemoteStorage\Http\Service;
27
use fkooman\RemoteStorage\Http\ServiceModuleInterface;
28
use fkooman\RemoteStorage\RandomInterface;
29
use fkooman\RemoteStorage\TplInterface;
30
31
class OAuthModule implements ServiceModuleInterface
32
{
33
    /** @var \fkooman\RemoteStorage\TplInterface */
34
    private $tpl;
35
36
    /** @var \fkooman\RemoteStorage\RandomInterface */
37
    private $random;
38
39
    /** @var TokenStorage */
40
    private $tokenStorage;
41
42
    /** @var \fkooman\RemoteStorage\Config */
43
    private $config;
44
45
    public function __construct(TplInterface $tpl, RandomInterface $random, TokenStorage $tokenStorage, Config $config)
46
    {
47
        $this->tpl = $tpl;
48
        $this->random = $random;
49
        $this->tokenStorage = $tokenStorage;
50
        $this->config = $config;
51
    }
52
53
    public function init(Service $service)
54
    {
55
        $service->get(
56
            '/_oauth/authorize',
57
            function (Request $request) {
58
                $this->validateRequest($request);
59
                $this->validateClient($request);
60
61
                // ask for approving this client/scope
62
                return new HtmlResponse(
63
                    $this->tpl->render(
64
                        'authorizeOAuthClient',
65
                        [
66
                            'client_id' => $request->getQueryParameter('client_id'),
67
                            'scope' => $request->getQueryParameter('scope'),
68
                            'redirect_uri' => $request->getQueryParameter('redirect_uri'),
69
                        ]
70
                    )
71
                );
72
            }
73
        );
74
75
        $service->post(
76
            '/_oauth/authorize',
77
            function (Request $request, array $hookData) {
78
                $userId = $hookData['auth'];
79
80
                $this->validateRequest($request);
81
                $this->validateClient($request);
82
83
                $returnUriPattern = '%s#%s';
84
85
                if ('no' === $request->getPostParameter('approve')) {
86
                    $redirectQuery = http_build_query(
87
                        [
88
                            'error' => 'access_denied',
89
                            'error_description' => 'user refused authorization',
90
                            'state' => $request->getQueryParameter('state'),
91
                        ]
92
                    );
93
94
                    $redirectUri = sprintf($returnUriPattern, $request->getQueryParameter('redirect_uri'), $redirectQuery);
95
96
                    return new RedirectResponse($redirectUri, 302);
97
                }
98
99
                $accessToken = $this->getAccessToken(
100
                    $userId,
101
                    $request->getQueryParameter('client_id'),
102
                    $request->getQueryParameter('scope')
103
                );
104
105
                // add state, access_token to redirect_uri
106
                $redirectQuery = http_build_query(
107
                    [
108
                        'access_token' => $accessToken,
109
                        'state' => $request->getQueryParameter('state'),
110
                    ]
111
                );
112
113
                $redirectUri = sprintf($returnUriPattern, $request->getQueryParameter('redirect_uri'), $redirectQuery);
114
115
                return new RedirectResponse($redirectUri, 302);
116
            }
117
        );
118
    }
119
120
    private function getAccessToken($userId, $clientId, $scope)
121
    {
122
        $existingToken = $this->tokenStorage->getExistingToken(
123
            $userId,
124
            $clientId,
125
            $scope
126
        );
127
128
        if (false !== $existingToken) {
129
            // if the user already has an access_token for this client and
130
            // scope, reuse it
131
            $accessTokenKey = $existingToken['access_token_key'];
132
            $accessToken = $existingToken['access_token'];
133
        } else {
134
            // generate a new one
135
            $accessTokenKey = $this->random->get(8);
136
            $accessToken = $this->random->get(16);
137
            // store it
138
            $this->tokenStorage->store(
139
                $userId,
140
                $accessTokenKey,
141
                $accessToken,
142
                $clientId,
143
                $scope
144
            );
145
        }
146
147
        return sprintf('%s.%s', $accessTokenKey, $accessToken);
148
    }
149
150
    private function validateRequest(Request $request)
151
    {
152
        // we enforce that all parameter are set, nothing is "OPTIONAL"
153
        $clientId = $request->getQueryParameter('client_id');
154
        if (1 !== preg_match('/^(?:[\x20-\x7E])+$/', $clientId)) {
155
            throw new HttpException('invalid client_id', 400);
156
        }
157
158
        // XXX we also should enforce HTTPS
159
        $redirectUri = $request->getQueryParameter('redirect_uri');
160 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...
161
            throw new HttpException('invalid redirect_uri', 400);
162
        }
163
        $responseType = $request->getQueryParameter('response_type');
164
        if ('token' !== $responseType) {
165
            throw new HttpException('invalid response_type', 400);
166
        }
167
        $scope = $request->getQueryParameter('scope');
0 ignored issues
show
Unused Code introduced by
$scope is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
168
169
        // XXX validate scopes!
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
170
//        if ('config' !== $scope) {
171
//            throw new HttpException('invalid scope', 400);
172
//        }
173
174
        // XXX make state optional for RS (bleh)
175
        $state = $request->getQueryParameter('state');
176
        if (1 !== preg_match('/^(?:[\x20-\x7E])+$/', $state)) {
177
            throw new HttpException('invalid state', 400);
178
        }
179
    }
180
181
    private function validateClient(Request $request)
182
    {
183
        $clientId = $request->getQueryParameter('client_id');
184
        $redirectUri = $request->getQueryParameter('redirect_uri');
185
186
        // redirectUri has to start with clientId (or be equal)
187
        if (0 !== strpos($redirectUri, $clientId)) {
188
            throw new HttpException('"redirect_uri" does not start with "client_id"', 400);
189
        }
190
    }
191
}
192