rob-revisited/ide/tests/BoardCardDetailsTest.php

205 lines
14 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Board\BoardCommands;
use JumPHP\Ide\Board\BoardData;
use JumPHP\Ide\Board\BoardPaste;
use JumPHP\Ide\Board\LocalBoard;
use JumPHP\Ide\Board\RemoteBoard;
use PHPUnit\Framework\TestCase;
/** A card's details: title and description, dates, older board files, pictures pasted in the description (local and jumphp.net). */
final class BoardCardDetailsTest extends TestCase
{
private const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
private string $root;
protected function setUp(): void
{
$this->root = sys_get_temp_dir() . '/jumphp-board-' . bin2hex(random_bytes(4));
mkdir("$this->root/.git/info", 0777, true);
file_put_contents("$this->root/.git/info/exclude", "/.jumphp/*\n!/.jumphp/board.json\n");
}
protected function tearDown(): void
{
exec('rm -rf ' . escapeshellarg($this->root));
}
private static function done(Deferred $d): mixed
{
self::assertTrue($d->isDone());
if ($d->error() !== null) {
throw $d->error();
}
return $d->result();
}
public function testACardHasATitleAMultiLineDescriptionAndItsDates(): void
{
$local = new LocalBoard($this->root);
$todo = self::done($local->board())['columns'][0]['id'];
$card = self::done($local->addCard(['columnId' => $todo, 'title' => 'Boss fight', 'body' => "First line\r\n\nThird line"]));
self::assertSame("First line\n\nThird line", $card['body']);
self::assertMatchesRegularExpression('/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/', $card['createdAt']);
self::assertSame([], $card['attachments']);
// edited afterwards: the creation date stays
$edited = self::done($local->updateCard($card['id'], ['title' => 'Boss fight 2', 'body' => "New\ntext", 'assignee' => 'ada', 'createdAt' => '1999-01-01T00:00:00Z']));
self::assertSame(['Boss fight 2', "New\ntext", 'ada', $card['createdAt']], [$edited['title'], $edited['body'], $edited['assignee'], $edited['createdAt']]);
self::assertSame($edited, self::done($local->board())['cards'][0]);
}
public function testAnOlderBoardFileStillLoads(): void
{
mkdir("$this->root/.jumphp");
file_put_contents("$this->root/.jumphp/board.json", json_encode(['version' => 1, 'columns' => [['id' => 'c1', 'name' => 'To do', 'position' => 0]],
'cards' => [['id' => 'a1', 'columnId' => 'c1', 'position' => 0, 'title' => 'Old card', 'body' => '', 'updatedAt' => '2026-11-15T18:30:49Z']]]));
$card = self::done((new LocalBoard($this->root))->board())['cards'][0];
self::assertSame(['Old card', '', [], '2026-11-15T18:30:49Z'], [$card['title'], $card['createdAt'], $card['attachments'], $card['updatedAt']]);
}
public function testAPastedPictureIsKeptBesideTheBoardAndCanBeRemoved(): void
{
$local = new LocalBoard($this->root);
$todo = self::done($local->board())['columns'][0]['id'];
$id = self::done($local->addCard(['columnId' => $todo, 'title' => 'Bug']))['id'];
$card = self::done($local->addAttachment($id, '../../evil name.gif', self::PNG));
// the type is the bytes' (a PNG), the name has no folder
self::assertSame([['name' => 'evil-name.png', 'type' => 'image/png', 'size' => strlen(base64_decode(self::PNG))]], $card['attachments']);
self::assertFileExists("$this->root/.jumphp/board-files/$id/evil-name.png");
$again = self::done($local->addAttachment($id, '', 'data:image/png;base64,' . self::PNG));
self::assertSame('evil-name.png', $again['attachments'][0]['name']);
self::assertMatchesRegularExpression('/^image-\d{8}-\d{6}\.png$/', $again['attachments'][1]['name']);
self::assertSame(['name' => 'evil-name.png', 'type' => 'image/png', 'data' => self::PNG], self::done($local->attachment($id, 'evil-name.png')));
self::assertNotNull($local->attachment($id, '../board.json')->error());
// committed with the board
self::assertStringContainsString("!/.jumphp/board.json\n!/.jumphp/board-files/", (string)file_get_contents("$this->root/.git/info/exclude"));
$card = self::done($local->removeAttachment($id, 'evil-name.png'));
self::assertCount(1, $card['attachments']);
self::assertFileDoesNotExist("$this->root/.jumphp/board-files/$id/evil-name.png");
self::done($local->deleteCard($id));
self::assertDirectoryDoesNotExist("$this->root/.jumphp/board-files/$id");
}
public function testOnlySmallPicturesAreTaken(): void
{
$local = new LocalBoard($this->root);
$todo = self::done($local->board())['columns'][0]['id'];
$id = self::done($local->addCard(['columnId' => $todo, 'title' => 'Bug']))['id'];
self::assertSame('This is not a picture (PNG, JPEG, GIF or WebP).', $local->addAttachment($id, 'x.png', base64_encode('<?php echo 1;'))->error()?->getMessage());
self::assertSame('This is not a picture (PNG, JPEG, GIF or WebP).', $local->addAttachment($id, 'x.png', 'not base64 !')->error()?->getMessage());
$big = base64_encode("\x89PNG\r\n\x1a\n" . str_repeat('a', BoardData::IMAGE_MAX));
self::assertSame('A picture is 5 MB at most.', $local->addAttachment($id, 'x.png', $big)->error()?->getMessage());
self::assertSame([], self::done($local->board())['cards'][0]['attachments']);
self::assertSame(['bytes' => "GIF89a\x01", 'type' => 'image/gif', 'ext' => 'gif'], BoardData::image(base64_encode("GIF89a\x01")));
self::assertSame('image/webp', BoardData::image(base64_encode("RIFF\0\0\0\0WEBPVP8 "))['type']);
self::assertSame('image/jpeg', BoardData::image(base64_encode("\xff\xd8\xff\xe0"))['type']);
}
public function testTheCommandsReachTheBoard(): void
{
$handlers = [];
BoardCommands::register(function (string $name, callable $h) use (&$handlers) { $handlers[$name] = $h; }, null, $this->root);
$todo = self::done($handlers['board.get']([]))['columns'][0]['id'];
$card = self::done($handlers['board.card.add'](['columnId' => $todo, 'title' => 'T', 'body' => "a\nb"]));
self::assertSame("a\nb", $card['body']);
$card = self::done($handlers['board.card.attach'](['id' => $card['id'], 'name' => 'shot.png', 'data' => self::PNG]));
self::assertSame(self::PNG, self::done($handlers['board.card.file'](['id' => $card['id'], 'name' => 'shot.png']))['data']);
self::assertSame([], self::done($handlers['board.card.detach'](['id' => $card['id'], 'name' => 'shot.png']))['attachments']);
}
public function testJumphpNetCarriesTheSameFields(): void
{
$log = [];
$client = function (string $method, string $path, ?array $body) use (&$log): Deferred {
$log[] = [$method, $path, $body];
$card = ['id' => 7, 'columnId' => 1, 'title' => 'Sound', 'body' => "x\ny", 'priority' => 'normal', 'createdAt' => '2026-11-15T10:00:00+00:00',
'attachments' => [['name' => 'a.png', 'type' => 'image/png', 'size' => 70], ['name' => '../x', 'type' => 'text/html', 'size' => 1]]];
return Deferred::resolved(str_contains($path, 'format=base64') ? ['name' => 'a.png', 'type' => 'image/png', 'data' => self::PNG] : $card);
};
$remote = new RemoteBoard('g', $client);
$card = self::done($remote->addCard(['columnId' => '1', 'title' => 'Sound', 'body' => "x\ny", 'priority' => '']));
self::assertSame(['columnId' => '1', 'title' => 'Sound', 'body' => "x\ny", 'priority' => 'normal'], $log[0][2]);
self::assertSame(['', '2026-11-15T10:00:00+00:00', [['name' => 'a.png', 'type' => 'image/png', 'size' => 70]]], [$card['priority'], $card['createdAt'], $card['attachments']]);
self::done($remote->updateCard('7', ['priority' => 'medium', 'due' => '2026-12-01']));
self::assertSame(['PATCH', '/api/ide/projects/g/board/cards/7', ['due' => '2026-12-01', 'priority' => 'normal']], $log[1]);
self::done($remote->updateCard('7', ['priority' => 'urgent']));
self::assertSame(['priority' => 'urgent'], $log[2][2]);
self::done($remote->addAttachment('7', 'shot.png', self::PNG));
self::assertSame(['POST', '/api/ide/projects/g/board/cards/7/attachments', ['name' => 'shot.png', 'data' => self::PNG]], $log[3]);
self::assertNotNull($remote->addAttachment('7', 'x.png', base64_encode('text'))->error());
self::assertCount(4, $log); // nothing sent
self::done($remote->removeAttachment('7', 'a b.png'));
self::assertSame(['DELETE', '/api/ide/projects/g/board/cards/7/attachments/a%20b.png', null], $log[4]);
self::assertSame(self::PNG, self::done($remote->attachment('7', 'a.png'))['data']);
self::assertSame(['GET', '/api/ide/projects/g/board/cards/7/attachments/a.png?format=base64', null], $log[5]);
}
public function testAPastedDocumentKeepsItsPicturesInPlace(): void
{
$local = new LocalBoard($this->root);
$todo = self::done($local->board())['columns'][0]['id'];
$id = self::done($local->addCard(['columnId' => $todo, 'title' => 'Doc']))['id'];
$png = base64_decode(self::PNG);
$asked = [];
$http = function (string $method, string $url) use (&$asked, $png): Deferred {
$asked[] = $url;
return Deferred::resolved(match ($url) {
'https://cdn.example/a.png' => ['status' => 200, 'body' => $png],
'https://cdn.example/big.png' => ['status' => 200, 'body' => "\x89PNG\r\n\x1a\n" . str_repeat('a', BoardData::IMAGE_MAX)],
'https://cdn.example/page.png' => ['status' => 200, 'body' => '<html>not a picture</html>'],
default => ['status' => 404, 'body' => ''],
});
};
$resolve = fn (string $host) => ['cdn.example' => ['93.184.216.34'], 'intranet.example' => ['10.1.2.3'], 'sneaky.example' => ['93.184.216.34', '127.0.0.1']][$host] ?? [];
$paste = new BoardPaste($local, $http, $resolve);
$html = '<h2>Report</h2><p>Shot: <img src="data:image/png;base64,' . self::PNG . '" alt="shot"></p>'
. '<p><img src="https://cdn.example/a.png"> <img src="https://cdn.example/big.png"> <img src="https://cdn.example/page.png"></p>'
. '<p><img src="http://127.0.0.1/admin.png"> <img src="https://intranet.example/x.png"> <img src="https://sneaky.example/y.png"> <img src="http://[::1]/z.png"></p>'
. '<p><img src="file:///C:/Users/me/word.png"> <img src="cid:part1"></p><p><img src="attachment:old.png"></p>';
$r = self::done($paste->paste($id, $html, [['name' => 'word.png', 'data' => self::PNG]]));
$names = array_column($r['card']['attachments'], 'name');
self::assertCount(3, $names);
self::assertMatchesRegularExpression('/^image-\d{8}-\d{6}\.png$/', $names[0]);
self::assertSame(['a.png', 'word.png'], [$names[1], $names[2]]);
self::assertSame("## Report\n\nShot: ![shot](attachment:{$names[0]})\n\n![](attachment:a.png) ![](https://cdn.example/big.png) ![](https://cdn.example/page.png)\n\n"
. "![](http://127.0.0.1/admin.png) ![](https://intranet.example/x.png) ![](https://sneaky.example/y.png) ![](http://[::1]/z.png)\n\n![](attachment:word.png)\n\n![](attachment:old.png)\n", $r['markdown']);
// the private addresses were never asked for
self::assertSame(['https://cdn.example/a.png', 'https://cdn.example/big.png', 'https://cdn.example/page.png'], $asked);
self::assertFalse($paste->isPublic('ftp://cdn.example/a.png'));
self::assertFalse($paste->isPublic('http://user:[email protected]/a.png'));
self::assertFalse($paste->isPublic('http://localhost/a.png'));
self::assertFalse($paste->isPublic('http://169.254.169.254/latest/meta-data'));
self::assertTrue($paste->isPublic('https://cdn.example/a.png'));
}
public function testCopyingToJumphpNetTakesThePictures(): void
{
$log = [];
$client = function (string $method, string $path, ?array $body) use (&$log): Deferred {
$log[] = [$method, $path, $body];
return Deferred::resolved(match (true) {
$method === 'GET' && str_ends_with($path, '/board') => ['columns' => [['id' => 1, 'name' => 'To do', 'position' => 0]], 'cards' => []],
$method === 'GET' && str_ends_with($path, '/notes') => ['notes' => []],
$method === 'POST' && str_ends_with($path, '/board/cards') => ['id' => 40, 'columnId' => 1] + $body,
$method === 'POST' && str_ends_with($path, '/attachments') => ['id' => 40, 'attachments' => [['name' => 'shot-2.png', 'type' => 'image/png', 'size' => 70]]],
default => ['id' => 40] + (array)$body,
});
};
$commands = new BoardCommands($this->root);
$commands->connect(fn () => 'g', $client);
$local = $commands->local();
$todo = self::done($local->board())['columns'][0]['id'];
$id = self::done($local->addCard(['columnId' => $todo, 'title' => 'Doc', 'body' => "See ![](attachment:shot.png)"]))['id'];
self::done($local->addAttachment($id, 'shot.png', self::PNG));
self::assertSame([], self::done($commands->copyToRemote())['errors']);
$sent = array_values(array_filter($log, fn ($l) => str_contains($l[1], '/attachments') || $l[0] === 'PATCH'));
self::assertSame(['POST', '/api/ide/projects/g/board/cards/40/attachments', ['name' => 'shot.png', 'data' => self::PNG]], $sent[0]);
self::assertSame(['PATCH', '/api/ide/projects/g/board/cards/40', ['body' => 'See ![](attachment:shot-2.png)']], $sent[1]);
}
}