-
Notifications
You must be signed in to change notification settings - Fork 4
/
endpoint.php
496 lines (481 loc) · 17.1 KB
/
endpoint.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<?php
declare(strict_types=1);
define('MINTOKEN_SQLITE_PATH', '');
define('MINTOKEN_CURL_TIMEOUT', 4);
define('MINTOKEN_REVOKE_AFTER', '7 days');
if (!file_exists(MINTOKEN_SQLITE_PATH)) {
header('HTTP/1.1 500 Internal Server Error');
header('Content-Type: text/plain;charset=UTF-8');
exit('The token endpoint is not ready for use.');
}
function connectToDatabase(): PDO
{
static $pdo;
if (!isset($pdo)) {
$pdo = new PDO('sqlite:' . MINTOKEN_SQLITE_PATH, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
}
return $pdo;
}
function initCurl(string $url)/* : resource */
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 8);
curl_setopt($curl, CURLOPT_TIMEOUT_MS, round(MINTOKEN_CURL_TIMEOUT * 1000));
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 2000);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2);
return $curl;
}
function storeToken(string $me, string $client_id, string $scope): string
{
$pdo = connectToDatabase();
do {
$hashable = substr(str_replace(chr(0), '', random_bytes(100)), 0, 72);
$hash = password_hash($hashable, PASSWORD_BCRYPT);
} while (strlen($hashable) !== 72 || $hash === false);
for ($i = 0; $i < 10; $i++) {
$lastException = null;
$id = bin2hex(random_bytes(32));
$revokeColumn = '';
$revokeValue = '';
$revoking = [];
if (is_string(MINTOKEN_REVOKE_AFTER) && strlen(MINTOKEN_REVOKE_AFTER) > 0) {
$revokeColumn = ', revoked';
$revokeValue = ', datetime(CURRENT_TIMESTAMP, ?)';
$revoking = ['+' . MINTOKEN_REVOKE_AFTER];
}
// We have to prepare inside the loop, https://github.com/teamtnt/tntsearch/pull/126
$statement = $pdo->prepare('INSERT INTO tokens (token_id, token_hash, auth_me, auth_client_id, auth_scope' . $revokeColumn . ') VALUES (?, ?, ?, ?, ?' . $revokeValue . ')');
try {
$statement->execute(array_merge([$id, $hash, $me, $client_id, $scope], $revoking));
} catch (PDOException $e) {
$lastException = $e;
if ($statement->errorInfo()[1] !== 19) {
throw $e;
}
continue;
}
break;
}
if ($lastException !== null) {
throw $e;
}
return $id . '_' . bin2hex($hashable);
}
function retrieveToken(string $token): ?array
{
list($id, $hashable) = explode('_', $token);
$pdo = connectToDatabase();
$statement = $pdo->prepare('SELECT *, revoked > CURRENT_TIMESTAMP AS active FROM tokens WHERE token_id = ?');
$statement->execute([$id]);
$token = $statement->fetch(PDO::FETCH_ASSOC);
if ($token !== false && password_verify(hex2bin($hashable), $token['token_hash'])) {
return $token;
}
return null;
}
function markTokenUsed(string $tokenId): void
{
$pdo = connectToDatabase();
$statement = $pdo->prepare('UPDATE tokens SET last_use = CURRENT_TIMESTAMP WHERE token_id = ? AND (last_use IS NULL OR last_use < CURRENT_TIMESTAMP)');
$statement->execute([$tokenId]);
}
function revokeToken(string $token): void
{
$token = retrieveToken($token);
if ($token !== null) {
$pdo = connectToDatabase();
$statement = $pdo->prepare('UPDATE tokens SET revoked = CURRENT_TIMESTAMP WHERE token_id = ? AND (revoked IS NULL OR revoked > CURRENT_TIMESTAMP)');
$statement->execute([$token['token_id']]);
}
}
function isTrustedEndpoint(string $endpoint): bool
{
$pdo = connectToDatabase();
$statement = $pdo->prepare('SELECT COUNT(*) FROM settings WHERE setting_name = ? AND setting_value = ?');
$statement->execute(['endpoint', $endpoint]);
return $statement->fetchColumn() > 0;
}
function discoverAuthorizationEndpoint(string $url): ?string
{
$curl = initCurl($url);
$headers = [];
$last = '';
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($curl, $header) use (&$headers, &$last): int {
$url = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
if ($url !== $last) {
$headers = [];
}
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) === 2) {
$name = strtolower(trim($header[0]));
if (!array_key_exists($name, $headers)) {
$headers[$name] = [trim($header[1])];
} else {
$headers[$name][] = trim($header[1]);
}
}
$last = $url;
return $len;
});
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_HTTP_CODE) !== 200 || curl_errno($curl) !== 0) {
return null;
}
curl_close($curl);
$endpoint = null;
if (array_key_exists('link', $headers)) {
foreach ($headers['link'] as $link) {
$found = preg_match('@^\s*<([^>]*)>\s*;(.*?;)?\srel="([^"]*?\s+)?authorization_endpoint(\s+[^"]*?)?"@', $link, $match);
if ($found === 1) {
$endpoint = $match[1];
break;
}
}
}
if ($endpoint === null) {
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8'));
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//*[contains(concat(" ", normalize-space(@rel), " "), " authorization_endpoint ") and @href][1]/@href');
if ($nodes->length === 0) {
return null;
}
$endpoint = $nodes->item(0)->value;
$bases = $xpath->query('//base[@href][1]/@href');
if ($bases->length !== 0) {
$last = resolveUrl($last, $bases->item(0)->value);
}
}
return resolveUrl($last, $endpoint);
}
function verifyCode(string $code, string $client_id, string $redirect_uri, string $endpoint): ?array
{
$curl = initCurl($endpoint);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query([
'code' => $code,
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
]));
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Accept: application/json']);
$body = curl_exec($curl);
curl_close($curl);
$info = json_decode($body, true, 2);
if (json_last_error() !== JSON_ERROR_NONE) {
return null;
}
$info = filter_var_array($info, [
'me' => FILTER_VALIDATE_URL,
'scope' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['regexp' => '@^[\x21\x23-\x5B\x5D-\x7E]+( [\x21\x23-\x5B\x5D-\x7E]+)*$@'],
],
]);
if (in_array(null, $info, true) || in_array(false, $info, true)) {
return null;
}
return $info;
}
function invalidRequest(): void
{
// This is probably wrong, but RFC 6750 is a little unclear.
// Maybe this should be handled per RFC 6749, putting the error code in the redirect?
header('HTTP/1.1 400 Bad Request');
header('Content-Type: text/plain;charset=UTF-8');
exit('invalid_request');
}
$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '@^[!#$%&\'*+.^_`|~0-9a-z-]+$@i']]);
if ($method === 'GET') {
$bearer_regexp = '@^Bearer [0-9a-f]+_[0-9a-f]+$@';
$authorization = filter_input(INPUT_SERVER, 'HTTP_AUTHORIZATION', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => $bearer_regexp]])
?? filter_input(INPUT_SERVER, 'REDIRECT_HTTP_AUTHORIZATION', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => $bearer_regexp]]);
if ($authorization === null && function_exists('apache_request_headers')) {
$headers = array_change_key_case(apache_request_headers(), CASE_LOWER);
if (isset($headers['authorization'])) {
$authorization = filter_var($headers['authorization'], FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => $bearer_regexp]]);
}
}
if ($authorization === null) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Bearer');
exit();
} elseif ($authorization === false) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Bearer, error="invalid_token", error_description="The access token is malformed"');
exit();
} else {
$token = retrieveToken(substr($authorization, 7));
if ($token === null) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Bearer, error="invalid_token", error_description="The access token is unknown"');
exit();
} elseif ($token['active'] === '0') {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Bearer, error="invalid_token", error_description="The access token is revoked"');
exit();
} else {
header('HTTP/1.1 200 OK');
header('Content-Type: application/json;charset=UTF-8');
markTokenUsed($token['token_id']);
exit(json_encode([
'me' => $token['auth_me'],
'client_id' => $token['auth_client_id'],
'scope' => $token['auth_scope'],
]));
}
}
} elseif ($method === 'POST') {
$type = filter_input(INPUT_SERVER, 'CONTENT_TYPE', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '@^application/x-www-form-urlencoded(;.*)?$@']]);
if (!is_string($type)) {
header('HTTP/1.1 415 Unsupported Media Type');
exit();
}
$revoke = filter_input(INPUT_POST, 'action', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '@^revoke$@']]);
if (is_string($revoke)) {
$token = filter_input(INPUT_POST, 'token', FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '@^[0-9a-f]+_[0-9a-f]+$@']]);
if (is_string($token)) {
revokeToken($token);
}
header('HTTP/1.1 200 OK');
exit();
}
$request = array_merge(
filter_input_array(INPUT_POST, [
'grant_type' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['regexp' => '@^authorization_code$@'],
],
'code' => [
'filter' => FILTER_VALIDATE_REGEXP,
'options' => ['regexp' => '@^[\x20-\x7E]+$@'],
],
'client_id' => FILTER_VALIDATE_URL,
'redirect_uri' => FILTER_VALIDATE_URL,
]),
filter_input_array(INPUT_GET, [
'me' => FILTER_VALIDATE_URL,
])
);
if (in_array(null, $request, true) || in_array(false, $request, true)) {
invalidRequest();
}
$endpoint = discoverAuthorizationEndpoint($request['me']);
if ($endpoint === null || !isTrustedEndpoint($endpoint)) {
invalidRequest();
}
$info = verifyCode($request['code'], $request['client_id'], $request['redirect_uri'], $endpoint);
if ($info === null) {
invalidRequest();
}
$token = storeToken($info['me'], $request['client_id'], $info['scope']);
header('HTTP/1.1 200 OK');
header('Content-Type: application/json;charset=UTF-8');
exit(json_encode([
'access_token' => $token,
'token_type' => 'Bearer',
'scope' => $info['scope'],
'me' => $info['me'],
]));
} else {
header('HTTP/1.1 405 Method Not Allowed');
header('Allow: GET, POST');
exit();
}
/**
* The following wall of code is dangerous. There be dragons.
* Taken from the mf2-php project, which is pledged to the public domain under CC0.
*/
function parseUriToComponents(string $uri): array
{
$result = [
'scheme' => null,
'authority' => null,
'path' => null,
'query' => null,
'fragment' => null,
];
$u = @parse_url($uri);
if (array_key_exists('scheme', $u)) {
$result['scheme'] = $u['scheme'];
}
if (array_key_exists('host', $u)) {
if (array_key_exists('user', $u)) {
$result['authority'] = $u['user'];
}
if (array_key_exists('pass', $u)) {
$result['authority'] .= ':' . $u['pass'];
}
if (array_key_exists('user', $u) || array_key_exists('pass', $u)) {
$result['authority'] .= '@';
}
$result['authority'] .= $u['host'];
if (array_key_exists('port', $u)) {
$result['authority'] .= ':' . $u['port'];
}
}
if (array_key_exists('path', $u)) {
$result['path'] = $u['path'];
}
if (array_key_exists('query', $u)) {
$result['query'] = $u['query'];
}
if (array_key_exists('fragment', $u)) {
$result['fragment'] = $u['fragment'];
}
return $result;
}
function resolveUrl(string $baseURI, string $referenceURI): string
{
$target = [
'scheme' => null,
'authority' => null,
'path' => null,
'query' => null,
'fragment' => null,
];
$base = parseUriToComponents($baseURI);
if ($base['path'] == null) {
$base['path'] = '/';
}
$reference = parseUriToComponents($referenceURI);
if ($reference['scheme']) {
$target['scheme'] = $reference['scheme'];
$target['authority'] = $reference['authority'];
$target['path'] = removeDotSegments($reference['path']);
$target['query'] = $reference['query'];
} else {
if ($reference['authority']) {
$target['authority'] = $reference['authority'];
$target['path'] = removeDotSegments($reference['path']);
$target['query'] = $reference['query'];
} else {
if ($reference['path'] == '') {
$target['path'] = $base['path'];
if ($reference['query']) {
$target['query'] = $reference['query'];
} else {
$target['query'] = $base['query'];
}
} else {
if (substr($reference['path'], 0, 1) == '/') {
$target['path'] = removeDotSegments($reference['path']);
} else {
$target['path'] = mergePaths($base, $reference);
$target['path'] = removeDotSegments($target['path']);
}
$target['query'] = $reference['query'];
}
$target['authority'] = $base['authority'];
}
$target['scheme'] = $base['scheme'];
}
$target['fragment'] = $reference['fragment'];
$result = '';
if ($target['scheme']) {
$result .= $target['scheme'] . ':';
}
if ($target['authority']) {
$result .= '//' . $target['authority'];
}
$result .= $target['path'];
if ($target['query']) {
$result .= '?' . $target['query'];
}
if ($target['fragment']) {
$result .= '#' . $target['fragment'];
} elseif ($referenceURI == '#') {
$result .= '#';
}
return $result;
}
function mergePaths(array $base, array $reference): string
{
if ($base['authority'] && $base['path'] == null) {
$merged = '/' . $reference['path'];
} else {
if (($pos=strrpos($base['path'], '/')) !== false) {
$merged = substr($base['path'], 0, $pos + 1) . $reference['path'];
} else {
$merged = $base['path'];
}
}
return $merged;
}
function removeLeadingDotSlash(string &$input): void
{
if (substr($input, 0, 3) == '../') {
$input = substr($input, 3);
} elseif (substr($input, 0, 2) == './') {
$input = substr($input, 2);
}
}
function removeLeadingSlashDot(string &$input): void
{
if (substr($input, 0, 3) == '/./') {
$input = '/' . substr($input, 3);
} else {
$input = '/' . substr($input, 2);
}
}
function removeOneDirLevel(string &$input, string &$output): void
{
if (substr($input, 0, 4) == '/../') {
$input = '/' . substr($input, 4);
} else {
$input = '/' . substr($input, 3);
}
$output = substr($output, 0, strrpos($output, '/'));
}
function removeLoneDotDot(string &$input): void
{
if ($input == '.') {
$input = substr($input, 1);
} else {
$input = substr($input, 2);
}
}
function moveOneSegmentFromInput(string &$input, string &$output): void
{
if (substr($input, 0, 1) != '/') {
$pos = strpos($input, '/');
} else {
$pos = strpos($input, '/', 1);
}
if ($pos === false) {
$output .= $input;
$input = '';
} else {
$output .= substr($input, 0, $pos);
$input = substr($input, $pos);
}
}
function removeDotSegments(string $path): string
{
$input = $path;
$output = '';
$step = 0;
while ($input) {
$step++;
if (substr($input, 0, 3) == '../' || substr($input, 0, 2) == './') {
removeLeadingDotSlash($input);
} elseif (substr($input, 0, 3) == '/./' || $input == '/.') {
removeLeadingSlashDot($input);
} elseif (substr($input, 0, 4) == '/../' || $input == '/..') {
removeOneDirLevel($input, $output);
} elseif ($input == '.' || $input == '..') {
removeLoneDotDot($input);
} else {
moveOneSegmentFromInput($input, $output);
}
}
return $output;
}