700 lines
36 KiB
PHP
700 lines
36 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Deferred;
|
|
use JumPHP\Ide\HttpClient\BruFormat;
|
|
use JumPHP\Ide\HttpClient\Collections;
|
|
use JumPHP\Ide\HttpClient\History;
|
|
use JumPHP\Ide\HttpClient\HttpClientCommands;
|
|
use JumPHP\Ide\HttpClient\HttpFile;
|
|
use JumPHP\Ide\HttpClient\HttpRunner;
|
|
use JumPHP\Ide\HttpClient\HttpSender;
|
|
use JumPHP\Ide\HttpClient\Interpolator;
|
|
use JumPHP\Ide\HttpClient\JsonPath;
|
|
use JumPHP\Ide\HttpClient\OpenApi;
|
|
use JumPHP\Ide\HttpClient\ResourceFetcher;
|
|
use JumPHP\Ide\HttpClient\ShareSync;
|
|
use JumPHP\Ide\HttpClient\SpecFinder;
|
|
use JumPHP\Ide\HttpClient\Transport;
|
|
use JumPHP\Ide\HttpClient\Vault;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/** The HTTP Client: its text format, variables, auth (JWT refreshed, OAuth2), the transport on a real server, OpenAPI, sharing. */
|
|
final class HttpClientTest extends TestCase
|
|
{
|
|
private string $dir;
|
|
/** @var resource|null */
|
|
private static $server = null;
|
|
private static int $port = 0;
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->dir = sys_get_temp_dir() . '/jumphp-http-' . bin2hex(random_bytes(4));
|
|
mkdir($this->dir . '/project', 0777, true);
|
|
}
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
exec('rm -rf ' . escapeshellarg($this->dir));
|
|
}
|
|
|
|
public static function tearDownAfterClass(): void
|
|
{
|
|
if (self::$server !== null) {
|
|
proc_terminate(self::$server);
|
|
self::$server = null;
|
|
}
|
|
}
|
|
|
|
private static function server(): string
|
|
{
|
|
if (self::$server === null) {
|
|
$sock = stream_socket_server('tcp://127.0.0.1:0');
|
|
self::$port = (int)substr((string)stream_socket_get_name($sock, false), strrpos((string)stream_socket_get_name($sock, false), ':') + 1);
|
|
fclose($sock);
|
|
@unlink(sys_get_temp_dir() . '/jumphp-http-test-logins-' . self::$port);
|
|
self::$server = proc_open([PHP_BINARY, '-S', '127.0.0.1:' . self::$port, __DIR__ . '/fixtures/http-client/server.php'],
|
|
[['pipe', 'r'], ['file', '/dev/null', 'w'], ['file', '/dev/null', 'w']], $pipes, null, ['PHP_CLI_SERVER_WORKERS' => '4'] + getenv());
|
|
for ($i = 0; $i < 100 && !@fsockopen('127.0.0.1', self::$port); $i++) {
|
|
usleep(50000);
|
|
}
|
|
}
|
|
return 'http://127.0.0.1:' . self::$port;
|
|
}
|
|
|
|
/** Polls until the Deferred is settled (the IDE's frame does it). */
|
|
private static function wait(Deferred $d, ?HttpSender $sender = null, float $seconds = 10): mixed
|
|
{
|
|
$value = null;
|
|
$error = null;
|
|
$done = false;
|
|
$d->then(function ($v) use (&$value, &$done) {
|
|
$value = $v;
|
|
$done = true;
|
|
}, function (\Throwable $e) use (&$error, &$done) {
|
|
$error = $e;
|
|
$done = true;
|
|
});
|
|
$end = microtime(true) + $seconds;
|
|
while (!$done && microtime(true) < $end) {
|
|
$sender?->poll();
|
|
usleep(2000);
|
|
}
|
|
if ($error !== null) {
|
|
throw $error;
|
|
}
|
|
self::assertTrue($done, 'the Deferred was not settled');
|
|
return $value;
|
|
}
|
|
|
|
// text format -----------------------------------------------------------------------------------------------------
|
|
|
|
public function testARequestFileRoundTrips(): void
|
|
{
|
|
$r = HttpFile::blank('Create a book');
|
|
$r['method'] = 'POST';
|
|
$r['url'] = '{{baseUrl}}/api/books?x=1';
|
|
$r['headers'] = [['Content-Type', 'application/json'], ['X-Trace', '{{$uuid}}']];
|
|
$r['body'] = "{\n \"title\": \"Dune\"\n}";
|
|
$r['auth'] = ['type' => 'jwt', 'login' => 'auth/login.http', 'path' => '$.token', 'var' => 'token'];
|
|
$r['pre'] = 'request.variables.set("a", "1");';
|
|
$r['post'] = "client.test(\"created\", () => {\n client.assert(response.status === 201);\n});";
|
|
$r['options'] = ['redirects' => false, 'verify' => false, 'timeout' => 12.0];
|
|
$r['seq'] = 3;
|
|
$r['description'] = 'Makes a book';
|
|
$text = HttpFile::serialize($r);
|
|
self::assertStringContainsString("# @auth jwt login=auth/login.http path=$.token var=token\n", $text);
|
|
self::assertStringContainsString("POST {{baseUrl}}/api/books?x=1\nContent-Type: application/json\n", $text);
|
|
$back = HttpFile::parse($text);
|
|
foreach (['name', 'method', 'url', 'headers', 'body', 'auth', 'pre', 'post', 'seq', 'description'] as $key) {
|
|
self::assertSame($r[$key], $back[$key], $key);
|
|
}
|
|
self::assertFalse($back['options']['redirects']);
|
|
self::assertFalse($back['options']['verify']);
|
|
self::assertSame(12.0, $back['options']['timeout']);
|
|
self::assertSame($text, HttpFile::serialize($back));
|
|
}
|
|
|
|
public function testAnHttpFileOfOtherToolsIsRead(): void
|
|
{
|
|
$text = <<<'HTTP'
|
|
@host = https://api.example.com
|
|
|
|
### List users
|
|
GET {{host}}/users
|
|
?page=2
|
|
&size=10
|
|
Accept: application/json
|
|
|
|
###
|
|
# @name Login
|
|
POST {{host}}/login HTTP/1.1
|
|
Content-Type: application/json
|
|
|
|
{"user": "a b"}
|
|
|
|
> {%
|
|
client.global.set("token", response.body.token);
|
|
%}
|
|
|
|
###
|
|
https://example.org/plain
|
|
HTTP;
|
|
$all = HttpFile::parseAll($text);
|
|
self::assertCount(3, $all);
|
|
self::assertSame('List users', $all[0]['name']);
|
|
self::assertSame('{{host}}/users?page=2&size=10', $all[0]['url']);
|
|
self::assertSame(['host' => 'https://api.example.com'], $all[0]['vars']);
|
|
self::assertSame('Login', $all[1]['name']);
|
|
self::assertSame('POST', $all[1]['method']);
|
|
self::assertSame('{"user": "a b"}', $all[1]['body']);
|
|
self::assertSame('client.global.set("token", response.body.token);', $all[1]['post']);
|
|
self::assertSame('GET', $all[2]['method']);
|
|
self::assertSame('https://example.org/plain', $all[2]['url']);
|
|
}
|
|
|
|
public function testBrunoFilesAreImportedAndExported(): void
|
|
{
|
|
$bru = <<<'BRU'
|
|
meta {
|
|
name: Get user
|
|
type: http
|
|
seq: 4
|
|
}
|
|
|
|
get {
|
|
url: {{baseUrl}}/users/1
|
|
body: json
|
|
auth: bearer
|
|
}
|
|
|
|
headers {
|
|
Accept: application/json
|
|
~X-Disabled: no
|
|
}
|
|
|
|
auth:bearer {
|
|
token: {{token}}
|
|
}
|
|
|
|
body:json {
|
|
{
|
|
"a": 1
|
|
}
|
|
}
|
|
|
|
tests {
|
|
test("ok", function() { expect(res.getStatus()).to.equal(200); });
|
|
}
|
|
BRU;
|
|
$r = BruFormat::parse($bru);
|
|
self::assertSame('Get user', $r['name']);
|
|
self::assertSame(4, $r['seq']);
|
|
self::assertSame('{{baseUrl}}/users/1', $r['url']);
|
|
self::assertSame([['Accept', 'application/json'], ['Content-Type', 'application/json']], $r['headers']);
|
|
self::assertSame(['type' => 'bearer', 'token' => '{{token}}'], $r['auth']);
|
|
self::assertSame("{\n \"a\": 1\n}", $r['body']);
|
|
self::assertStringContainsString('expect(res.getStatus())', $r['post']);
|
|
$again = BruFormat::parse(BruFormat::serialize($r));
|
|
foreach (['name', 'url', 'method', 'auth', 'body', 'post'] as $key) {
|
|
self::assertSame($r[$key], $again[$key], $key);
|
|
}
|
|
[$vars, $secrets] = BruFormat::parseEnvironment("vars {\n baseUrl: http://x\n}\nvars:secret [\n token,\n password\n]\n");
|
|
self::assertSame(['baseUrl' => 'http://x'], $vars);
|
|
self::assertSame(['token', 'password'], $secrets);
|
|
}
|
|
|
|
public function testVariablesAndJsonPath(): void
|
|
{
|
|
$i = new Interpolator(['baseUrl' => 'https://{{host}}', 'host' => 'example.org']);
|
|
self::assertSame('https://example.org/a?x={{nope}}', $i->resolve('{{baseUrl}}/a?x={{nope}}'));
|
|
self::assertSame(['nope'], $i->missing);
|
|
self::assertMatchesRegularExpression('/^[0-9a-f-]{36}$/', $i->resolve('{{$uuid}}'));
|
|
self::assertMatchesRegularExpression('/^\d+$/', $i->resolve('{{$random.integer(1, 9)}}'));
|
|
$data = ['data' => ['items' => [['id' => 1, 'token' => 'a'], ['id' => 2, 'meta' => ['token' => 'b']]]], 'token' => 'top'];
|
|
self::assertSame('top', JsonPath::first($data, '$.token'));
|
|
self::assertSame('top', JsonPath::first($data, 'token'));
|
|
self::assertSame(2, JsonPath::first($data, '$.data.items[-1].id'));
|
|
self::assertSame([1, 2], JsonPath::all($data, "$.data['items'][*].id"));
|
|
self::assertSame(['top', 'a', 'b'], JsonPath::all($data, '$..token'));
|
|
}
|
|
|
|
// auth ------------------------------------------------------------------------------------------------------------
|
|
|
|
/** A collection "api" with an environment "dev" and a fake sender answering $answer($request). */
|
|
private function runner(\Closure $answer, ?\Closure $clock = null, ?FakeSender &$sender = null): HttpRunner
|
|
{
|
|
$root = $this->dir . '/project';
|
|
$c = new Collections($root);
|
|
$id = $c->create('api');
|
|
$c->saveEnvironments($id, ['dev' => ['baseUrl' => 'http://api.test', 'user' => 'admin', '$secrets' => ['password']]]);
|
|
$vault = new Vault($root, $this->dir . '/secrets.json');
|
|
$vault->setSecret('api', 'dev', 'password', 'secret');
|
|
$sender = new FakeSender($answer);
|
|
return new HttpRunner($c, $vault, $sender, new History($root, $this->dir . '/history'), $clock);
|
|
}
|
|
|
|
public function testStaticAuthsAndInheritance(): void
|
|
{
|
|
$runner = $this->runner(fn (array $r) => ['status' => 200, 'body' => '{}', 'headers' => [], 'url' => $r['url']]);
|
|
$basic = HttpFile::blank();
|
|
$basic['url'] = '{{baseUrl}}/a';
|
|
$basic['auth'] = ['type' => 'basic', 'username' => '{{user}}', 'password' => '{{password}}'];
|
|
$built = $runner->build('api', 'dev', $basic);
|
|
self::assertSame('http://api.test/a', $built['url']);
|
|
self::assertContains(['Authorization', 'Basic ' . base64_encode('admin:secret')], $built['headers']);
|
|
$key = HttpFile::blank();
|
|
$key['url'] = '{{baseUrl}}/a?x=1';
|
|
$key['auth'] = ['type' => 'apikey', 'in' => 'query', 'name' => 'api_key', 'value' => 'k 1'];
|
|
self::assertSame('http://api.test/a?x=1&api_key=k%201', $runner->build('api', 'dev', $key)['url']);
|
|
// inherit: the collection's auth and headers
|
|
$c = new Collections($this->dir . '/project');
|
|
$c->saveSettings('api', ['name' => 'api', 'auth' => ['type' => 'bearer', 'token' => 'T0'], 'headers' => [['X-App', 'ide'], ['Accept', 'text/plain']]]);
|
|
$inherit = HttpFile::blank();
|
|
$inherit['headers'] = [['accept', 'application/json']];
|
|
$built = $runner->build('api', 'dev', $inherit);
|
|
self::assertSame([['X-App', 'ide'], ['accept', 'application/json'], ['Authorization', 'Bearer T0']], $built['headers']);
|
|
}
|
|
|
|
public function testAJwtLoginIsKeptThenAskedAgainWhenItEnds(): void
|
|
{
|
|
$now = 1000;
|
|
$logins = 0;
|
|
$runner = $this->runner(function (array $r) use (&$logins, &$now) {
|
|
if (str_ends_with($r['url'], '/login')) {
|
|
$logins++;
|
|
$payload = rtrim(strtr(base64_encode(json_encode(['exp' => $now + 60, 'n' => $logins])), '+/', '-_'), '=');
|
|
return ['status' => 200, 'body' => json_encode(['data' => ['jwt' => "h.$payload.s"]]), 'headers' => [], 'url' => $r['url']];
|
|
}
|
|
$auth = '';
|
|
foreach ($r['headers'] as $h) {
|
|
$auth = strcasecmp($h[0], 'authorization') === 0 ? $h[1] : $auth;
|
|
}
|
|
return ['status' => 200, 'body' => json_encode(['auth' => $auth]), 'headers' => [], 'url' => $r['url']];
|
|
}, function () use (&$now) {
|
|
return $now;
|
|
});
|
|
$c = new Collections($this->dir . '/project');
|
|
$login = HttpFile::blank('Login');
|
|
$login['method'] = 'POST';
|
|
$login['url'] = '{{baseUrl}}/login';
|
|
$login['body'] = '{"username": "{{user}}", "password": "{{password}}"}';
|
|
$c->save('api', 'auth/login.http', $login);
|
|
$c->saveSettings('api', ['name' => 'api', 'auth' => ['type' => 'jwt', 'login' => 'auth/login.http', 'path' => '$.data.jwt', 'var' => 'token']]);
|
|
$get = HttpFile::blank();
|
|
$get['url'] = '{{baseUrl}}/books';
|
|
$first = self::wait($runner->send('api', 'dev', $get));
|
|
self::assertSame(1, $logins);
|
|
self::assertTrue($first['auth']['refreshed']);
|
|
self::assertSame(1060, $first['auth']['expires']);
|
|
self::assertStringStartsWith('Bearer h.', json_decode($first['response']['body'], true)['auth']);
|
|
$second = self::wait($runner->send('api', 'dev', $get));
|
|
self::assertSame(1, $logins, 'the token is kept');
|
|
self::assertFalse($second['auth']['refreshed']);
|
|
// {{token}} is a variable of the environment now
|
|
self::assertStringStartsWith('h.', $runner->variables('api', 'dev')['token']);
|
|
$now += 40; // 20 s left < the margin: asked again
|
|
self::wait($runner->send('api', 'dev', $get));
|
|
self::assertSame(2, $logins);
|
|
// the history never holds the token nor the password
|
|
$history = (string)file_get_contents((string)glob($this->dir . '/history/*.json')[0]);
|
|
self::assertStringNotContainsString('secret', $history);
|
|
self::assertStringNotContainsString('h.ey', $history);
|
|
}
|
|
|
|
public function testATokenTheApiRefusesIsAskedAgainOnce(): void
|
|
{
|
|
$logins = 0;
|
|
$runner = $this->runner(function (array $r) use (&$logins) {
|
|
if (str_ends_with($r['url'], '/login')) {
|
|
$logins++;
|
|
return ['status' => 200, 'body' => json_encode(['token' => "opaque-$logins"]), 'headers' => [], 'url' => $r['url']];
|
|
}
|
|
$ok = in_array(['Authorization', 'Bearer opaque-2'], $r['headers'], true);
|
|
return ['status' => $ok ? 200 : 401, 'body' => '', 'headers' => [], 'url' => $r['url']];
|
|
});
|
|
$c = new Collections($this->dir . '/project');
|
|
$login = HttpFile::blank('Login');
|
|
$login['url'] = '{{baseUrl}}/login';
|
|
$c->save('api', 'login.http', $login);
|
|
$get = HttpFile::blank();
|
|
$get['url'] = '{{baseUrl}}/x';
|
|
$get['auth'] = ['type' => 'jwt', 'login' => 'login.http'];
|
|
self::assertSame(401, self::wait($runner->send('api', 'dev', $get))['response']['status'], 'a fresh token refused is not asked again');
|
|
$r = self::wait($runner->send('api', 'dev', $get));
|
|
self::assertSame(200, $r['response']['status']);
|
|
self::assertSame(2, $logins);
|
|
}
|
|
|
|
public function testOAuth2ClientCredentials(): void
|
|
{
|
|
$asked = [];
|
|
$runner = $this->runner(function (array $r) use (&$asked) {
|
|
if (str_ends_with($r['url'], '/token')) {
|
|
$asked[] = $r['body'];
|
|
return ['status' => 200, 'body' => '{"access_token":"AT","expires_in":3600}', 'headers' => [], 'url' => $r['url']];
|
|
}
|
|
return ['status' => 200, 'body' => json_encode($r['headers']), 'headers' => [], 'url' => $r['url']];
|
|
});
|
|
$get = HttpFile::blank();
|
|
$get['url'] = '{{baseUrl}}/x';
|
|
$get['auth'] = ['type' => 'oauth2', 'grant' => 'client_credentials', 'tokenUrl' => '{{baseUrl}}/token', 'clientId' => 'cid', 'clientSecret' => '{{password}}', 'scope' => 'read write'];
|
|
$r = self::wait($runner->send('api', 'dev', $get));
|
|
self::assertContains(['Authorization', 'Bearer AT'], json_decode($r['response']['body'], true));
|
|
self::wait($runner->send('api', 'dev', $get));
|
|
self::assertSame(['grant_type=client_credentials&client_id=cid&client_secret=secret&scope=read+write'], $asked);
|
|
$runner->logout('api', 'dev');
|
|
self::wait($runner->send('api', 'dev', $get));
|
|
self::assertCount(2, $asked);
|
|
}
|
|
|
|
// the transport, on a real server -----------------------------------------------------------------------------
|
|
|
|
public function testTheTransportOnARealServer(): void
|
|
{
|
|
$base = self::server();
|
|
$t = new Transport();
|
|
$send = fn (array $r) => self::wait($t->send($r + ['timeout' => 5.0]), $t);
|
|
$echo = $send(['method' => 'POST', 'url' => "$base/echo?a=1", 'headers' => [['Content-Type', 'text/plain']], 'body' => 'hello']);
|
|
self::assertSame(200, $echo['status']);
|
|
$data = json_decode($echo['body'], true);
|
|
self::assertSame('hello', $data['body']);
|
|
self::assertSame(['a' => '1'], $data['query']);
|
|
self::assertSame('jumphp-ide', $data['headers']['User-Agent']);
|
|
self::assertGreaterThan(0, $echo['time']);
|
|
$mine = $send(['url' => "$base/echo", 'headers' => [['User-Agent', 'mine/1']]]);
|
|
self::assertSame('mine/1', json_decode($mine['body'], true)['headers']['User-Agent']);
|
|
// redirects followed, or not
|
|
$followed = $send(['url' => "$base/redirect"]);
|
|
self::assertSame(200, $followed['status']);
|
|
self::assertSame(['from' => 'redirect'], json_decode($followed['body'], true)['query']);
|
|
self::assertSame(302, $followed['redirects'][0][0]);
|
|
$stopped = $send(['url' => "$base/redirect", 'redirects' => false]);
|
|
self::assertSame(302, $stopped['status']);
|
|
// gzip, cookies kept and sent back
|
|
self::assertSame(str_repeat('zipped ', 100), $send(['url' => "$base/gzip"])['body']);
|
|
$send(['url' => "$base/cookie"]);
|
|
self::assertSame('session=abc123', json_decode($send(['url' => "$base/echo"])['body'], true)['headers']['Cookie']);
|
|
// no answer: a refused port, a timeout
|
|
try {
|
|
$send(['url' => 'http://127.0.0.1:1/']);
|
|
self::fail('refused');
|
|
} catch (\RuntimeException $e) {
|
|
self::assertStringContainsString('127.0.0.1', $e->getMessage());
|
|
}
|
|
try {
|
|
self::wait($t->send(['url' => "$base/slow", 'timeout' => 0.5]), $t);
|
|
self::fail('timeout');
|
|
} catch (\RuntimeException $e) {
|
|
self::assertStringContainsString('timeout', $e->getMessage());
|
|
}
|
|
}
|
|
|
|
public function testAJwtLoginAgainstARealServer(): void
|
|
{
|
|
$base = self::server();
|
|
$root = $this->dir . '/project';
|
|
$c = new Collections($root);
|
|
$c->create('api');
|
|
$c->saveEnvironments('api', ['dev' => ['baseUrl' => $base, '$secrets' => ['password']]]);
|
|
$vault = new Vault($root, $this->dir . '/secrets.json');
|
|
$vault->setSecret('api', 'dev', 'password', 'secret');
|
|
$login = HttpFile::blank('Login');
|
|
$login['method'] = 'POST';
|
|
$login['url'] = '{{baseUrl}}/login?ttl=31'; // ends 1 s after the margin
|
|
$login['headers'] = [['Content-Type', 'application/json']];
|
|
$login['body'] = '{"username":"admin","password":"{{password}}"}';
|
|
$c->save('api', 'login.http', $login);
|
|
$c->saveSettings('api', ['name' => 'api', 'auth' => ['type' => 'jwt', 'login' => 'login.http']]);
|
|
$t = new Transport();
|
|
$runner = new HttpRunner($c, $vault, $t);
|
|
$get = HttpFile::blank();
|
|
$get['url'] = '{{baseUrl}}/private';
|
|
self::assertTrue(json_decode(self::wait($runner->send('api', 'dev', $get), $t)['response']['body'], true)['ok']);
|
|
self::wait($runner->send('api', 'dev', $get), $t);
|
|
self::assertSame(1, json_decode(self::wait($t->send(['url' => "$base/logins"]), $t)['body'], true)['count']);
|
|
sleep(2);
|
|
self::assertTrue(self::wait($runner->send('api', 'dev', $get), $t)['auth']['refreshed']);
|
|
self::assertSame(2, json_decode(self::wait($t->send(['url' => "$base/logins"]), $t)['body'], true)['count']);
|
|
}
|
|
|
|
// OpenAPI -----------------------------------------------------------------------------------------------------
|
|
|
|
public function testAnOpenApiDescriptionIsShownAndTried(): void
|
|
{
|
|
$spec = OpenApi::fromText((string)file_get_contents(__DIR__ . '/fixtures/http-client/openapi.json'));
|
|
$d = $spec->describe('http://localhost:8765/api/docs.jsonopenapi');
|
|
self::assertSame('Library', $d['title']);
|
|
self::assertSame(['http://localhost:8765'], $d['servers']);
|
|
self::assertSame(['Book', 'default'], array_column($d['tags'], 'name'));
|
|
self::assertCount(3, $d['tags'][0]['operations']);
|
|
$post = $spec->operation('POST /api/books');
|
|
$example = $post['requestBody']['content']['application/ld+json']['example'];
|
|
self::assertSame('Dune', $example['title']);
|
|
self::assertArrayNotHasKey('id', $example, 'read-only properties are not sent');
|
|
self::assertSame('[email protected]', $example['author']['email'], 'allOf merged');
|
|
self::assertNull($example['author']['books'][0]['author'] ?? null, 'a cycle is cut');
|
|
$r = $spec->toRequest('listBooks');
|
|
self::assertSame('{{baseUrl}}/api/books?page=1', $r['url']);
|
|
self::assertContains(['Accept', 'application/ld+json'], $r['headers']);
|
|
$r = $spec->toRequest('POST /api/books');
|
|
self::assertSame('POST', $r['method']);
|
|
self::assertSame(['type' => 'bearer', 'token' => '{{token}}'], $r['auth']);
|
|
self::assertSame('Dune', json_decode($r['body'], true)['title']);
|
|
$r = $spec->toRequest('GET /api/books/{id}');
|
|
self::assertSame('{{baseUrl}}/api/books/{{id}}', $r['url'], 'a path parameter is a variable of the request');
|
|
self::assertSame('42', $r['vars']['id'], "the spec's example");
|
|
$plain = OpenApi::fromText('{"openapi":"3.1.0","paths":{"/api/xxxes/{id}":{"get":{"parameters":[{"name":"id","in":"path","required":true,"schema":{"type":"string"}}],"responses":{"200":{"description":"ok"}}}}}}');
|
|
self::assertSame('1', $plain->toRequest('GET /api/xxxes/{id}')['vars']['id'], 'never the placeholder "string"');
|
|
self::assertSame(['type' => 'apikey', 'in' => 'header', 'name' => 'X-API-Key', 'value' => '{{apiKey}}'], $spec->toRequest('DELETE /api/books/{id}')['auth']);
|
|
$swagger = OpenApi::fromText("swagger: '2.0'\nhost: api.test\nbasePath: /v1\nschemes: [https]\npaths:\n /pets:\n post:\n parameters:\n - in: body\n name: pet\n schema: {type: object, properties: {name: {type: string, example: Rex}}}\n responses: {'200': {description: ok}}\n");
|
|
self::assertSame(['https://api.test/v1'], $swagger->servers());
|
|
self::assertSame('{"name":"Rex"}', (string)json_encode(json_decode($swagger->toRequest('POST /pets')['body'])));
|
|
}
|
|
|
|
public function testTheCommandsFindLoadTryAndImportASpec(): void
|
|
{
|
|
$root = $this->dir . '/project';
|
|
mkdir("$root/docs");
|
|
copy(__DIR__ . '/fixtures/http-client/openapi.json', "$root/docs/openapi.json");
|
|
file_put_contents("$root/composer.json", '{"require": {"api-platform/symfony": "^4"}}');
|
|
$commands = [];
|
|
$c = HttpClientCommands::register(function (string $n, callable $h) use (&$commands) {
|
|
$commands[$n] = $h;
|
|
}, $root, new FakeSender(fn () => ['status' => 200, 'body' => '', 'headers' => [], 'url' => '']), new Vault($root, $this->dir . '/s.json'), new History($root, $this->dir . '/h'));
|
|
$found = $commands['http.openapi.find']([]);
|
|
self::assertSame(['docs/openapi.json'], $found['files']);
|
|
self::assertSame('api-platform', $found['framework']);
|
|
self::assertStringEndsWith('/api/docs.jsonopenapi', $found['urls'][0]);
|
|
$loaded = self::wait($commands['http.openapi.load'](['source' => 'docs/openapi.json']));
|
|
self::assertSame('Library', $loaded['spec']['title']);
|
|
$id = $commands['http.collection.create'](['name' => 'Library'])['id'];
|
|
$c->collections()->saveSettings($id, ['name' => 'Library', 'auth' => ['type' => 'jwt', 'login' => 'x.http']]);
|
|
self::assertSame(['type' => 'inherit'], $commands['http.openapi.request'](['source' => 'docs/openapi.json', 'id' => 'POST /api/books', 'collection' => $id])['request']['auth']);
|
|
self::assertSame(4, $commands['http.openapi.import'](['source' => 'docs/openapi.json', 'collection' => $id])['imported']);
|
|
$tree = $commands['http.list']([])['collections'][0]['items'];
|
|
self::assertSame(['Book', 'default'], array_column($tree, 'name'));
|
|
self::assertFileExists("$root/http-requests/Library/Book/creates-a-book.http");
|
|
// export / import
|
|
$text = $commands['http.export'](['collection' => $id, 'format' => 'http'])['text'];
|
|
self::assertSame(4, substr_count($text, '### '));
|
|
$other = $commands['http.collection.create'](['name' => 'Copy'])['id'];
|
|
self::assertSame(4, $commands['http.import'](['collection' => $other, 'text' => $text])['imported']);
|
|
// environments: secrets out of the project
|
|
$commands['http.env.save'](['collection' => $id, 'environments' => ['dev' => ['vars' => ['baseUrl' => 'http://x', 'password' => 'leak'], 'secrets' => ['password']]],
|
|
'secrets' => ['dev' => ['password' => 'p4ss']]]);
|
|
$file = (string)file_get_contents("$root/http-requests/Library/http-client.env.json");
|
|
self::assertStringNotContainsString('leak', $file);
|
|
self::assertStringNotContainsString('p4ss', $file);
|
|
$env = $commands['http.env.get'](['collection' => $id])['environments'];
|
|
self::assertTrue($env->dev['secrets']->password);
|
|
self::assertSame('p4ss', $commands['http.vars'](['collection' => $id, 'env' => 'dev'])['vars']['password']);
|
|
}
|
|
|
|
public function testThePortOfWebServeIsCksumsOne(): void
|
|
{
|
|
if (!is_executable('/usr/bin/cksum') && !is_executable('/bin/cksum')) {
|
|
self::markTestSkipped('no cksum here');
|
|
}
|
|
foreach (['/home/u/site', '/tmp/x y'] as $folder) {
|
|
$expected = (int)explode(' ', (string)shell_exec('printf %s ' . escapeshellarg($folder) . ' | cksum'))[0];
|
|
self::assertSame($expected, SpecFinder::cksum($folder));
|
|
}
|
|
}
|
|
|
|
// sharing -----------------------------------------------------------------------------------------------------
|
|
|
|
public function testACollectionIsSharedBothWays(): void
|
|
{
|
|
$site = new FakeSite();
|
|
$alice = new Collections($this->dir . '/alice');
|
|
$bob = new Collections($this->dir . '/bob');
|
|
$alice->create('api');
|
|
$alice->saveEnvironments('api', ['dev' => ['baseUrl' => 'http://x', '$secrets' => ['token']]]);
|
|
// a hand edit puts a secret's value in the file: it is never sent
|
|
file_put_contents($this->dir . '/alice/http-requests/api/http-client.env.json', '{"dev": {"baseUrl": "http://x", "token": "LEAK", "$secrets": ["token"]}}');
|
|
$one = HttpFile::blank('One');
|
|
$alice->save('api', 'one.http', $one);
|
|
$aliceSync = new ShareSync($alice, $site->client('alice'), $this->dir . '/alice-sync.json');
|
|
$bobSync = new ShareSync($bob, $site->client('bob'), $this->dir . '/bob-sync.json');
|
|
$report = self::wait($aliceSync->sync('api', 'game'));
|
|
self::assertSame(['collection.json', 'http-client.env.json', 'one.http'], $report['pushed']);
|
|
self::assertStringNotContainsString('LEAK', json_encode($site->files));
|
|
$report = self::wait($bobSync->sync('api', 'game'));
|
|
self::assertCount(3, $report['pulled']);
|
|
self::assertSame('One', $bob->read('api', 'one.http')['name']);
|
|
// Bob changes one, Alice adds another: both arrive
|
|
$one['url'] = 'http://changed';
|
|
$bob->save('api', 'one.http', $one);
|
|
$alice->save('api', 'two.http', HttpFile::blank('Two'));
|
|
self::assertSame(['one.http'], self::wait($bobSync->sync('api', 'game'))['pushed']);
|
|
$report = self::wait($aliceSync->sync('api', 'game'));
|
|
self::assertSame(['one.http'], $report['pulled']);
|
|
self::assertSame(['two.http'], $report['pushed']);
|
|
self::assertSame('http://changed', $alice->read('api', 'one.http')['url']);
|
|
// both change the same file: this computer's is kept, theirs beside it
|
|
$one['url'] = 'http://alice';
|
|
$alice->save('api', 'one.http', $one);
|
|
self::wait($aliceSync->sync('api', 'game'));
|
|
$one['url'] = 'http://bob';
|
|
$bob->save('api', 'one.http', $one);
|
|
$report = self::wait($bobSync->sync('api', 'game'));
|
|
self::assertSame(['one.http'], $report['conflicts']);
|
|
self::assertSame('http://bob', $bob->read('api', 'one.http')['url']);
|
|
self::assertStringContainsString('http://alice', (string)file_get_contents($this->dir . '/bob/http-requests/api/one.theirs.http'));
|
|
self::assertArrayNotHasKey('one.theirs.http', $bob->files('api'));
|
|
// a deletion travels
|
|
$alice->remove('api', 'two.http');
|
|
self::wait($aliceSync->sync('api', 'game'));
|
|
self::assertSame(['two.http'], self::wait($bobSync->sync('api', 'game'))['deleted']);
|
|
// a reader cannot send
|
|
$site->readOnly = ['carol'];
|
|
$carol = new Collections($this->dir . '/carol');
|
|
$carolSync = new ShareSync($carol, $site->client('carol'), $this->dir . '/carol-sync.json');
|
|
$report = self::wait($carolSync->sync('api', 'game'));
|
|
self::assertTrue($report['readOnly']);
|
|
$carol->save('api', 'mine.http', HttpFile::blank('Mine'));
|
|
self::assertSame([], self::wait($carolSync->sync('api', 'game'))['pushed']);
|
|
self::assertArrayNotHasKey('mine.http', $site->files['api']);
|
|
}
|
|
|
|
// response preview: the page's resources ----------------------------------------------------------------------------
|
|
|
|
public function testTheResourceGuardsKeepToThePagesSite(): void
|
|
{
|
|
$page = 'https://shop.example.com/a/b.html';
|
|
self::assertNull(ResourceFetcher::refuse($page, 'https://shop.example.com:8443/x.css'));
|
|
self::assertNotNull(ResourceFetcher::refuse($page, 'https://evil.net/x.css'));
|
|
self::assertNotNull(ResourceFetcher::refuse($page, 'http://127.0.0.1/x.css'));
|
|
self::assertNotNull(ResourceFetcher::refuse($page, 'http://localhost:8000/x.css'));
|
|
self::assertNotNull(ResourceFetcher::refuse($page, 'http://10.0.0.5/x.css'));
|
|
self::assertNotNull(ResourceFetcher::refuse($page, 'ftp://shop.example.com/x.css'));
|
|
self::assertNotNull(ResourceFetcher::refuse($page, 'file:///etc/passwd'));
|
|
self::assertNull(ResourceFetcher::refuse('http://localhost:8000/', 'http://127.0.0.1:9000/x.css'));
|
|
self::assertNotNull(ResourceFetcher::refuse('http://10.0.0.5/', 'http://10.0.0.6/x.css'));
|
|
}
|
|
|
|
public function testALinkIsResolvedAgainstTheResponseUrl(): void
|
|
{
|
|
$base = 'http://site.test:8080/docs/page.html?x=1';
|
|
self::assertSame('http://site.test:8080/docs/css/a.css', ResourceFetcher::resolve($base, 'css/a.css#h'));
|
|
self::assertSame('http://site.test:8080/img/a.png', ResourceFetcher::resolve($base, '../img/a.png'));
|
|
self::assertSame('http://site.test:8080/a.png', ResourceFetcher::resolve($base, '/a.png'));
|
|
self::assertSame('http://cdn.test/a.png', ResourceFetcher::resolve($base, '//cdn.test/a.png'));
|
|
self::assertNull(ResourceFetcher::resolve($base, 'data:image/png;base64,AA=='));
|
|
self::assertNull(ResourceFetcher::resolve($base, '#top'));
|
|
}
|
|
|
|
public function testResourcesAreFetchedWithLimitsAndRedirectsAreChecked(): void
|
|
{
|
|
$sender = new FakeSender(function (array $r) {
|
|
self::assertFalse($r['redirects']);
|
|
return match (parse_url($r['url'], PHP_URL_PATH)) {
|
|
'/ok.css' => ['body' => 'body{color:red}', 'headers' => [['Content-Type', 'text/css; charset=utf-8']]],
|
|
'/missing.png' => ['status' => 404],
|
|
'/to-other' => ['status' => 302, 'headers' => [['Location', 'http://evil.net/x.css']]],
|
|
'/to-same' => ['status' => 301, 'headers' => [['Location', '/ok.css']]],
|
|
'/big.png' => ['body' => str_repeat('x', ResourceFetcher::MAX_RESOURCE + 1)],
|
|
default => throw new \RuntimeException('connection refused'),
|
|
};
|
|
});
|
|
$base = 'http://site.test/index.html';
|
|
$urls = ['/ok.css', '/missing.png', '/to-other', '/to-same', '/big.png', '/boom'];
|
|
$got = self::wait((new ResourceFetcher($sender))->fetch($base, array_merge(array_map(fn ($u) => 'http://site.test' . $u, $urls), ['http://evil.net/y.css'])))['resources'];
|
|
self::assertTrue($got['http://site.test/ok.css']['ok']);
|
|
self::assertSame('body{color:red}', base64_decode($got['http://site.test/ok.css']['base64']));
|
|
self::assertSame('text/css', $got['http://site.test/ok.css']['type']);
|
|
self::assertSame('HTTP 404', $got['http://site.test/missing.png']['error']);
|
|
self::assertFalse($got['http://site.test/to-other']['ok']);
|
|
self::assertStringContainsString('another host', $got['http://site.test/to-other']['error']);
|
|
self::assertTrue($got['http://site.test/to-same']['ok']);
|
|
self::assertStringContainsString('too big', $got['http://site.test/big.png']['error']);
|
|
self::assertSame('connection refused', $got['http://site.test/boom']['error']);
|
|
self::assertStringContainsString('another host', $got['http://evil.net/y.css']['error']);
|
|
foreach ($sender->sent as $request) {
|
|
self::assertStringNotContainsString('evil.net', $request['url'], 'nothing is ever sent to another host');
|
|
}
|
|
}
|
|
|
|
public function testResourcesComeFromARealServerWithTheSessionsCookie(): void
|
|
{
|
|
$base = self::server();
|
|
$t = new Transport();
|
|
self::wait($t->send(['method' => 'GET', 'url' => "$base/cookie", 'timeout' => 5.0]), $t);
|
|
$got = self::wait((new ResourceFetcher($t))->fetch("$base/page", ["$base/echo?r=1", "$base/gzip", 'http://example.org/x.css']), $t)['resources'];
|
|
$echo = json_decode(base64_decode($got["$base/echo?r=1"]['base64']), true);
|
|
self::assertSame('jumphp-ide', $echo['headers']['User-Agent']);
|
|
self::assertSame('session=abc123', $echo['headers']['Cookie']);
|
|
self::assertSame(str_repeat('zipped ', 100), base64_decode($got["$base/gzip"]['base64']));
|
|
self::assertFalse($got['http://example.org/x.css']['ok']);
|
|
}
|
|
}
|
|
|
|
/** A sender that answers at once. */
|
|
final class FakeSender implements HttpSender
|
|
{
|
|
/** @var list<array<string, mixed>> */
|
|
public array $sent = [];
|
|
|
|
public function __construct(private \Closure $answer)
|
|
{
|
|
}
|
|
|
|
public function send(array $request): Deferred
|
|
{
|
|
$this->sent[] = $request;
|
|
try {
|
|
return Deferred::resolved(($this->answer)($request) + ['status' => 200, 'reason' => 'OK', 'headers' => [], 'body' => '', 'size' => 0, 'time' => 1, 'redirects' => [], 'url' => $request['url']]);
|
|
} catch (\Throwable $e) {
|
|
return Deferred::rejected($e);
|
|
}
|
|
}
|
|
|
|
public function poll(): void
|
|
{
|
|
}
|
|
|
|
public function busy(): bool
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/** jumphp.net's /http API, in memory (the same rules as the site's controller). */
|
|
final class FakeSite
|
|
{
|
|
/** @var array<string, array<string, array{content: string, version: int}>> collection => path => file */
|
|
public array $files = [];
|
|
/** @var list<string> */
|
|
public array $readOnly = [];
|
|
|
|
public function client(string $user): \Closure
|
|
{
|
|
return function (string $method, string $path, ?array $body) use ($user): Deferred {
|
|
preg_match('#/http/([^/]+)$#', $path, $m);
|
|
$collection = rawurldecode($m[1] ?? '');
|
|
$can = ['write' => !in_array($user, $this->readOnly, true)];
|
|
$list = fn () => array_map(fn ($p, $f) => ['path' => $p] + $f, array_keys($this->files[$collection] ?? []), $this->files[$collection] ?? []);
|
|
if ($method === 'GET') {
|
|
return Deferred::resolved(['files' => $list(), 'can' => $can]);
|
|
}
|
|
if (!$can['write']) {
|
|
return Deferred::rejected(new \RuntimeException('read only'));
|
|
}
|
|
$conflicts = [];
|
|
foreach ($body['files'] ?? [] as $f) {
|
|
$now = $this->files[$collection][$f['path']] ?? null;
|
|
if (($now['version'] ?? 0) !== $f['baseVersion']) {
|
|
$conflicts[] = ['path' => $f['path']] + (array)$now;
|
|
continue;
|
|
}
|
|
$this->files[$collection][$f['path']] = ['content' => $f['content'], 'version' => ($now['version'] ?? 0) + 1];
|
|
}
|
|
foreach ($body['deletes'] ?? [] as $d) {
|
|
unset($this->files[$collection][$d['path']]);
|
|
}
|
|
return Deferred::resolved(['files' => $list(), 'conflicts' => $conflicts]);
|
|
};
|
|
}
|
|
}
|