Skip to content

Commit cd5dd9e

Browse files
williamdesDeepSeek
andcommitted
security: Read the access of a developer again while the session lives
The permission of a developer was decided at login from one answer of GitHub and kept in the session until it ended, without a limit: a developer who lost the write access of the repository kept it here for as long as their cookie lived, and the flag was a boolean derived from has_commit_access rather than the value itself (e452f05). Ask GitHub again when the last answer is older than 15 minutes, once per request at most, and keep what the session knew when the API cannot be asked. The login is stored at sign-in for that call, the decision reads has_commit_access, and the older read_only flag of an existing session is still honoured until the next sign-in. Signed-off-by: William Desportes <williamdes@wdes.fr> Co-Authored-By: DeepSeek <noreply@deepseek.com>
1 parent 138abb5 commit cd5dd9e

5 files changed

Lines changed: 268 additions & 2 deletions

File tree

‎src/Controller/DevelopersController.php‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
use function random_bytes;
3232
use function str_starts_with;
3333
use function strcasecmp;
34+
use function time;
3435

3536
use const PHP_URL_HOST;
3637

@@ -201,6 +202,11 @@ protected function authenticateDeveloper(array $userInfo, string $accessToken):
201202
$session->renew();
202203
$session->write('Developer.id', $developerId);
203204
$session->write('access_token', $accessToken);
205+
// The login is what the API is asked about later: the permission is
206+
// read again by the middleware, see AuthenticationMiddleware.
207+
$session->write('github_login', (string) ($userInfo['login'] ?? ''));
208+
$session->write('has_commit_access', (bool) $userInfo['has_commit_access']);
209+
$session->write('access_checked_at', time());
204210
$session->write('read_only', ! $userInfo['has_commit_access']);
205211
}
206212
}

‎src/Github/PermissionChecker.php‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
<?php
2+
3+
/**
4+
* phpMyAdmin Error reporting server
5+
* Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
6+
*
7+
* Licensed under The MIT License
8+
* For full copyright and license information, please see the LICENSE.txt
9+
* Redistributions of files must retain the above copyright notice.
10+
*
11+
* @copyright Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
12+
* @license https://opensource.org/licenses/mit-license.php MIT License
13+
*
14+
* @see https://www.phpmyadmin.net/
15+
*/
16+
17+
namespace App\Github;
18+
19+
use Cake\Http\Client;
20+
21+
use function in_array;
22+
use function is_array;
23+
use function is_string;
24+
25+
/**
26+
* Reads the permission a developer has on the repository the reports are filed
27+
* in.
28+
*
29+
* The middleware needs it outside a controller, so it does not go through the
30+
* component the controllers use.
31+
*/
32+
class PermissionChecker
33+
{
34+
/**
35+
* Seconds a permission read is believed before it is asked again.
36+
*/
37+
public const RECHECK_INTERVAL = 900;
38+
39+
/**
40+
* Roles of a repository that are allowed to act on the reports.
41+
*/
42+
public const WRITE_ROLES = ['admin', 'maintain', 'write'];
43+
44+
/**
45+
* Read the permission of a developer on a repository.
46+
*
47+
* @param string $login GitHub login of the developer
48+
* @param string $repoPath The repository, "owner/name"
49+
* @param string $token Token used to ask the API
50+
* @param Client|null $client HTTP client, one is built when absent
51+
*
52+
* @return bool|null True when the developer may write, null when the API
53+
* could not be asked, so a caller keeps what it knew
54+
*/
55+
public static function canCommitTo(
56+
string $login,
57+
string $repoPath,
58+
string $token,
59+
Client|null $client = null,
60+
): bool|null {
61+
if ($login === '' || $repoPath === '' || $token === '') {
62+
return null;
63+
}
64+
65+
$client ??= new Client([
66+
'headers' => [
67+
'Accept' => 'application/vnd.github+json',
68+
'User-Agent' => 'phpmyadmin-error-reporting-server',
69+
'Authorization' => 'token ' . $token,
70+
],
71+
'timeout' => 5,
72+
]);
73+
74+
$response = $client->get(
75+
'https://api.github.com/repos/' . $repoPath . '/collaborators/' . $login . '/permission',
76+
);
77+
78+
if ($response->getStatusCode() !== 200) {
79+
// A refusal is an answer: the developer may not write. Anything
80+
// else, a 5xx or a network failure, is not.
81+
return $response->getStatusCode() === 404 ? false : null;
82+
}
83+
84+
$data = $response->getJson();
85+
if (! is_array($data)) {
86+
return null;
87+
}
88+
89+
$role = $data['permission'] ?? $data['role_name'] ?? null;
90+
91+
return is_string($role) && in_array($role, self::WRITE_ROLES, true);
92+
}
93+
}

‎src/Middleware/AuthenticationMiddleware.php‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
namespace App\Middleware;
66

7+
use App\Github\PermissionChecker;
78
use Cake\Core\App;
9+
use Cake\Core\Configure;
810
use Cake\Http\Exception\ForbiddenException;
911
use Cake\Http\Response;
1012
use Cake\Http\ServerRequest;
@@ -18,6 +20,7 @@
1820
use function assert;
1921
use function in_array;
2022
use function is_string;
23+
use function time;
2124

2225
class AuthenticationMiddleware implements MiddlewareInterface
2326
{
@@ -72,6 +75,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
7275
}
7376

7477
if ($currentDeveloper !== null) {
78+
$this->refreshCommitAccess($request);
79+
7580
$hasAccess = $this->hasAccessToAction($request);
7681
if ($hasAccess === false) {
7782
$request->getSession()->destroy();
@@ -130,14 +135,52 @@ protected function isPublicAccess(ServerRequest $request): bool
130135
return in_array($action, self::NO_ACCESS_CONTROL_LIST[$controllerName]);
131136
}
132137

138+
/**
139+
* Ask GitHub again what the developer may do, at most once per interval.
140+
*
141+
* The access of the developer is decided at login from a single answer of
142+
* GitHub: left alone, a login stays valid with write access long after the
143+
* account lost its permission on the repository, and a read-only developer
144+
* keeps being refused after they were granted it.
145+
*
146+
* A failure to ask GitHub keeps what the session already knew.
147+
*
148+
* @param ServerRequest $request The request
149+
*/
150+
protected function refreshCommitAccess(ServerRequest $request): void
151+
{
152+
$session = $request->getSession();
153+
$checkedAt = (int) $session->read('access_checked_at');
154+
if ($checkedAt > 0 && time() - $checkedAt < PermissionChecker::RECHECK_INTERVAL) {
155+
return;
156+
}
157+
158+
$login = (string) $session->read('github_login');
159+
$token = (string) $session->read('access_token');
160+
$repoPath = (string) Configure::read('GithubRepoPath');
161+
162+
$hasCommitAccess = PermissionChecker::canCommitTo($login, $repoPath, $token);
163+
if ($hasCommitAccess !== null) {
164+
$session->write('has_commit_access', $hasCommitAccess);
165+
}
166+
167+
$session->write('access_checked_at', time());
168+
}
169+
133170
protected function hasAccessToAction(ServerRequest $request): bool
134171
{
135172
$controllerName = $request->getParam('controller');
136173
$action = $request->getParam('action');
137-
$read_only = $request->getSession()->read('read_only');
174+
$session = $request->getSession();
175+
$hasCommitAccess = $session->read('has_commit_access');
176+
if ($hasCommitAccess === null) {
177+
// Sessions opened before this key existed.
178+
$readOnly = $session->read('read_only');
179+
$hasCommitAccess = $readOnly === null ? false : ! $readOnly;
180+
}
138181

139182
// If developer has commit access on phpmyadmin/phpmyadmin
140-
if ($read_only === false) {
183+
if ($hasCommitAccess === true) {
141184
return true;
142185
}
143186

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
<?php
2+
3+
/**
4+
* phpMyAdmin Error reporting server
5+
* Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
6+
*
7+
* Licensed under The MIT License
8+
* For full copyright and license information, please see the LICENSE.txt
9+
* Redistributions of files must retain the above copyright notice.
10+
*
11+
* @copyright Copyright (c) phpMyAdmin project (https://www.phpmyadmin.net/)
12+
* @license https://opensource.org/licenses/mit-license.php MIT License
13+
*
14+
* @see https://www.phpmyadmin.net/
15+
*/
16+
17+
namespace App\Test\TestCase\Github;
18+
19+
use App\Github\PermissionChecker;
20+
use Cake\Http\Client;
21+
use Cake\Http\Client\Response;
22+
use Cake\TestSuite\TestCase;
23+
use PHPUnit\Framework\Attributes\DataProvider;
24+
25+
use function json_encode;
26+
27+
/**
28+
* The role of a developer is read from one answer of the GitHub API.
29+
*/
30+
class PermissionCheckerTest extends TestCase
31+
{
32+
/**
33+
* Build a client that answers a canned response, without a connection.
34+
*
35+
* @param int $status The status code to answer
36+
* @param array<string, mixed>|null $json The body, as JSON
37+
*/
38+
protected function clientAnswering(int $status, array|null $json): Client
39+
{
40+
$response = new Response(
41+
['HTTP/1.1 ' . $status . ' Answer', 'Content-Type: application/json'],
42+
(string) json_encode($json),
43+
);
44+
45+
return new class ($response) extends Client {
46+
public function __construct(private Response $canned)
47+
{
48+
}
49+
50+
public function get(string $url, array|string $data = [], array $options = []): Response
51+
{
52+
return $this->canned;
53+
}
54+
};
55+
}
56+
57+
/** @return array<string, array{int, array<string, string>|null, bool|null}> */
58+
public static function roleProvider(): array
59+
{
60+
return [
61+
'admin' => [200, ['permission' => 'admin'], true],
62+
'maintain' => [200, ['permission' => 'maintain'], true],
63+
'write' => [200, ['permission' => 'write'], true],
64+
'write as a role_name' => [200, ['role_name' => 'write'], true],
65+
'read' => [200, ['permission' => 'read'], false],
66+
'triage' => [200, ['permission' => 'triage'], false],
67+
'no role' => [200, [], false],
68+
'a role that is not a string' => [200, ['permission' => 1], false],
69+
'not a collaborator' => [404, null, false],
70+
'the API is down' => [500, null, null],
71+
'a forbidden answer' => [403, null, null],
72+
];
73+
}
74+
75+
#[DataProvider('roleProvider')]
76+
public function testTheRoleDecidesTheAccess(int $status, array|null $json, bool|null $expected): void
77+
{
78+
$result = PermissionChecker::canCommitTo(
79+
'pma-bot',
80+
'phpmyadmin/phpmyadmin',
81+
'token',
82+
$this->clientAnswering($status, $json),
83+
);
84+
85+
$this->assertSame($expected, $result);
86+
}
87+
88+
public function testNoTokenIsNotAnAnswer(): void
89+
{
90+
$this->assertNull(PermissionChecker::canCommitTo('pma-bot', 'phpmyadmin/phpmyadmin', ''));
91+
$this->assertNull(PermissionChecker::canCommitTo('', 'phpmyadmin/phpmyadmin', 'token'));
92+
}
93+
}

‎tests/TestCase/Middleware/AuthenticationMiddlewareTest.php‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,35 @@ public function testAReadOnlyDeveloperIsStillRedirectedFromAProtectedAction(): v
4646
'You need to have commit access on phpmyadmin/phpmyadmin repository on Github.com to do this action (Stats:stats)',
4747
);
4848
}
49+
50+
/**
51+
* The access is decided from the key the login writes now, and a session
52+
* that still carries the old derived flag must not override it.
53+
*/
54+
public function testTheCommitAccessOfTheSessionDecides(): void
55+
{
56+
$this->session([
57+
'Developer.id' => 1,
58+
'has_commit_access' => true,
59+
'read_only' => true,
60+
]);
61+
62+
$this->get('/stats');
63+
64+
$this->assertResponseCode(200);
65+
}
66+
67+
public function testARevokedCommitAccessIsRefused(): void
68+
{
69+
$this->session([
70+
'Developer.id' => 1,
71+
'has_commit_access' => false,
72+
'read_only' => false,
73+
]);
74+
75+
$this->get('/stats');
76+
77+
$this->assertResponseCode(307);
78+
$this->assertRedirect('/');
79+
}
4980
}

0 commit comments

Comments
 (0)