305 lines
19 KiB
PHP
305 lines
19 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Processes;
|
|
use JumPHP\Ide\Ssh\SshCli;
|
|
use JumPHP\Ide\Ssh\SshCommands;
|
|
use JumPHP\Ide\Ssh\SshConfig;
|
|
use JumPHP\Ide\Ssh\SshServers;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/** The SSH window: ~/.ssh/config read, the ssh / scp command lines (quoting, ports, jump hosts, Windows), listings parsed, a fake ssh run. */
|
|
final class SshTest extends TestCase
|
|
{
|
|
private function server(array $s = []): array
|
|
{
|
|
return SshCli::server($s + ['host' => 'example.org', 'user' => 'deploy', 'port' => 2222]);
|
|
}
|
|
|
|
public function testTheSshConfigGivesItsNamedHostsAndFollowsIncludes(): void
|
|
{
|
|
$dir = sys_get_temp_dir() . '/jumphp-sshcfg-' . bin2hex(random_bytes(4));
|
|
mkdir("$dir/conf.d", 0777, true);
|
|
file_put_contents("$dir/conf.d/work", "Host build\n HostName 10.0.0.8\n User ci\n");
|
|
file_put_contents("$dir/config", <<<'CFG'
|
|
# comment
|
|
Include conf.d/*
|
|
Host prod web1
|
|
HostName prod.example.org
|
|
User deploy
|
|
Port 2222
|
|
IdentityFile ~/.ssh/id_prod
|
|
ProxyJump bastion
|
|
Host bastion
|
|
HostName=bastion.example.org
|
|
User "admin"
|
|
Host *.internal !nope *
|
|
User nobody
|
|
Match host foo
|
|
User ignored
|
|
Host prod
|
|
User second-is-ignored
|
|
CFG);
|
|
try {
|
|
$hosts = SshConfig::hosts("$dir/config");
|
|
self::assertSame(['build', 'prod', 'web1', 'bastion'], array_column($hosts, 'alias'));
|
|
self::assertSame(['alias' => 'prod', 'hostname' => 'prod.example.org', 'user' => 'deploy', 'port' => 2222, 'identity' => '~/.ssh/id_prod', 'jump' => 'bastion'], $hosts[1]);
|
|
self::assertSame('admin', $hosts[3]['user']);
|
|
self::assertSame('10.0.0.8', $hosts[0]['hostname']);
|
|
} finally {
|
|
exec('rm -rf ' . escapeshellarg($dir));
|
|
}
|
|
}
|
|
|
|
public function testAServerIsCheckedSoNothingBecomesAnOption(): void
|
|
{
|
|
$s = $this->server(['name' => '', 'jump' => 'admin@bastion:2200', 'identity' => '~/.ssh/id_ed25519', 'folder' => '/var/www']);
|
|
self::assertSame('[email protected]', $s['name']);
|
|
foreach ([['host' => '-oProxyCommand=x'], ['host' => 'a b'], ['host' => 'x;rm'], ['user' => 'a@b'], ['jump' => '-J'], ['identity' => '-x'], ['port' => 70000]] as $bad) {
|
|
try {
|
|
$this->server($bad);
|
|
self::fail('accepted: ' . json_encode($bad));
|
|
} catch (\InvalidArgumentException) {
|
|
$this->addToAssertionCount(1);
|
|
}
|
|
}
|
|
}
|
|
|
|
public function testTheCommandLinesOnLinux(): void
|
|
{
|
|
$s = $this->server(['jump' => 'bastion', 'identity' => '/home/me/.ssh/k']);
|
|
self::assertSame(['/usr/bin/ssh', '-p', '2222', '-i', '/home/me/.ssh/k', '-J', 'bastion', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15',
|
|
'-o', 'ControlPath=~/.ssh/jumphp-%C', '-o', 'ControlMaster=no', '-T', '[email protected]', "cd '/var/my site' && pwd && LC_ALL=C ls -lA"],
|
|
SshCli::exec($s, SshCli::listCommand('/var/my site'), '/usr/bin/ssh', 'Linux'));
|
|
// the session: interactive, master of the shared connection, in its start folder
|
|
$session = SshCli::session($this->server(['folder' => '~/www']), 'ssh', 'Linux');
|
|
self::assertSame(['ssh', '-p', '2222', '-o', 'ControlPath=~/.ssh/jumphp-%C', '-o', 'ControlMaster=auto', '-o', 'ControlPersist=no', '-t', '[email protected]',
|
|
'cd ~/\'www\' && exec "${SHELL:-/bin/sh}" -l'], $session);
|
|
self::assertSame("ssh -p 2222 -o 'ControlPath=~/.ssh/jumphp-%C' -o ControlMaster=auto -o ControlPersist=no -t [email protected] 'cd ~/'\\''www'\\'' && exec \"\${SHELL:-/bin/sh}\" -l'",
|
|
SshCli::line($session, 'Linux'));
|
|
// scp: -P for the port, remote paths escaped for both protocols, a relative local path never read as host:path
|
|
self::assertSame(['scp', '-P', '2222', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ControlPath=~/.ssh/jumphp-%C', '-o', 'ControlMaster=no', '-r', '-p',
|
|
'[email protected]:/srv/a\\ b\\(1\\).txt', './c:d'], SshCli::copy($this->server(), [['remote' => '/srv/a b(1).txt']], 'c:d', 'scp', 'Linux'));
|
|
// an upload's destination: as it is when scp speaks SFTP (OpenSSH 9+), escaped for the remote shell with the legacy protocol
|
|
self::assertSame('[email protected]:my site/', SshCli::copy($this->server(), ['/tmp/a'], ['remote' => '~/my site/'], 'scp', 'Linux')[14]);
|
|
self::assertSame('[email protected]:my\\ site/', SshCli::copy($this->server(), ['/tmp/a'], ['remote' => '~/my site/'], 'scp', 'Linux', false)[14]);
|
|
self::assertTrue(SshCli::speaksSftp('OpenSSH_10.0p2 Debian-7, OpenSSL 3.5.7'));
|
|
self::assertFalse(SshCli::speaksSftp('OpenSSH_for_Windows_8.1p1, LibreSSL 3.0.2'));
|
|
self::assertTrue(SshCli::speaksSftp('OpenSSH_for_Windows_9.5p1, LibreSSL 3.8.2'));
|
|
self::assertSame('x.txt', SshCli::scpPath('~/x.txt'));
|
|
self::assertSame('.', SshCli::scpPath('~'));
|
|
self::assertSame("it\\'s", SshCli::scpPath("it's"));
|
|
// a host of ~/.ssh/config: its alias alone, ssh applies the file
|
|
self::assertSame(['ssh', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-T', 'prod', 'exit 0'], SshCli::test(SshCli::server(['host' => 'prod']), 'ssh', 'Windows'));
|
|
}
|
|
|
|
public function testTheCommandLinesOnWindows(): void
|
|
{
|
|
$s = $this->server(['identity' => '~/.ssh/id_rsa', 'folder' => 'C:/not/remote/but/fine']);
|
|
$session = SshCli::session($s, 'ssh', 'Windows');
|
|
self::assertSame(['ssh', '-p', '2222', '-i'], array_slice($session, 0, 4));
|
|
self::assertSame(['-tt', '[email protected]', "cd 'C:/not/remote/but/fine' && exec \"\${SHELL:-/bin/sh}\" -l"], array_slice($session, 5));
|
|
self::assertSame('C:\\Users\\Me\\.ssh\\id_rsa', SshCli::expandHome('~/.ssh/id_rsa', 'Windows', 'C:\\Users\\Me'));
|
|
self::assertNotContains('ControlPath=~/.ssh/jumphp-%C', $session);
|
|
// cmd.exe: double quotes around words with spaces or shell characters, the remote command's single quotes kept
|
|
self::assertSame('ssh -tt [email protected] "cd \'/srv/my site\' && ls"', SshCli::line(['ssh', '-tt', '[email protected]', "cd '/srv/my site' && ls"], 'Windows'));
|
|
self::assertSame(['scp', '-P', '2222', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-r', '-p', 'C:\\Users\\Me\\site', '.\\build', '[email protected]:www/'],
|
|
SshCli::copy($this->server(), ['C:\\Users\\Me\\site', 'build'], ['remote' => '~/www/'], 'scp', 'Windows'));
|
|
self::assertSame(['script', '-qefc', "'scp' '-r' 'a b' 'h:c'", '/dev/null'], SshCli::withTerminal(['scp', '-r', 'a b', 'h:c'], 'script', 'Linux'));
|
|
self::assertSame(['script', '-q', '/dev/null', 'scp', 'x'], SshCli::withTerminal(['scp', 'x'], 'script', 'Darwin'));
|
|
self::assertSame(['scp', 'x'], SshCli::withTerminal(['scp', 'x'], 'script', 'Windows'));
|
|
}
|
|
|
|
public function testRemoteOperationsAreQuotedForTheRemoteShell(): void
|
|
{
|
|
self::assertSame("mv -- '/a/it'\\''s' '/b/new name'", SshCli::operation('move', ["/a/it's"], '/b/new name'));
|
|
self::assertSame("cp -R -- '/a' '/b' '/dest/'", SshCli::operation('copy', ['/a', '/b'], '/dest/'));
|
|
self::assertSame("rm -rf -- '/tmp/x'", SshCli::operation('delete', ['/tmp/x']));
|
|
self::assertSame("mkdir -p -- '/tmp/\$(boom)'", SshCli::operation('mkdir', ['/tmp/$(boom)']));
|
|
self::assertSame('cd ~ && pwd && LC_ALL=C ls -lA', SshCli::listCommand(''));
|
|
}
|
|
|
|
public function testListingsOfGnuBsdAndBusyBoxAreRead(): void
|
|
{
|
|
$out = <<<'TXT'
|
|
/home/deploy
|
|
total 24
|
|
drwxr-xr-x 3 deploy deploy 4096 Nov 15 13:40 www
|
|
-rw-r--r--. 1 deploy deploy 220 Jan 6 2025 .profile
|
|
lrwxrwxrwx 1 deploy deploy 11 Nov 15 13:40 current -> releases/12
|
|
-rw-r--r--@ 1 deploy staff 1234 Nov 2 09:01 my file (copy).txt
|
|
crw-rw-rw- 1 root root 1, 3 Nov 15 13:40 null
|
|
drwxr-xr-x 2 root root 4096 Nov 15 13:40 Bin
|
|
TXT;
|
|
$l = SshCli::parseListing($out);
|
|
self::assertSame('/home/deploy', $l['path']);
|
|
self::assertSame(['Bin', 'www', '.profile', 'current', 'my file (copy).txt', 'null'], array_column($l['entries'], 'name'));
|
|
self::assertSame(['dir', 'dir', 'file', 'link', 'file', 'other'], array_column($l['entries'], 'type'));
|
|
self::assertSame('releases/12', $l['entries'][3]['target']);
|
|
self::assertSame(1234, $l['entries'][4]['size']);
|
|
self::assertSame('Jan 6 2025', $l['entries'][2]['date']);
|
|
}
|
|
|
|
public function testScpProgressIsRead(): void
|
|
{
|
|
self::assertSame(['file' => 'big.iso', 'percent' => 42, 'done' => '420MB', 'speed' => '12.3MB/s', 'eta' => '00:47'],
|
|
SshCli::progress("big.iso 10% 100MB 11.0MB/s 01:20 ETA\rbig.iso 42% 420MB 12.3MB/s 00:47 ETA"));
|
|
self::assertNull(SshCli::progress('Permission denied (publickey).'));
|
|
}
|
|
|
|
public function testServersAreKeptOutOfTheProjectWithoutSecrets(): void
|
|
{
|
|
$file = sys_get_temp_dir() . '/jumphp-ssh-' . bin2hex(random_bytes(4)) . '/ide-ssh.json';
|
|
try {
|
|
$store = new SshServers($file);
|
|
$a = $store->save(['name' => 'Prod', 'host' => 'prod.example.org', 'user' => 'deploy', 'port' => '22', 'password' => 'never kept']);
|
|
self::assertMatchesRegularExpression('/^[0-9a-f]{8}$/', $a['id']);
|
|
$store->save(['id' => $a['id'], 'name' => 'Production'] + $a);
|
|
self::assertSame(1, $store->import(['prod.example.org', 'bastion']));
|
|
self::assertSame(['Production', 'bastion'], array_column($store->all(), 'name'));
|
|
self::assertStringNotContainsString('never kept', (string)file_get_contents($file));
|
|
self::assertSame('0600', substr(sprintf('%o', fileperms($file)), -4));
|
|
self::assertTrue($store->remove($a['id']));
|
|
self::assertSame(['bastion'], array_column($store->all(), 'host'));
|
|
} finally {
|
|
exec('rm -rf ' . escapeshellarg(dirname($file)));
|
|
}
|
|
}
|
|
|
|
public function testTheWindowRunsSshAndScp(): void
|
|
{
|
|
if (PHP_OS_FAMILY === 'Windows') {
|
|
self::markTestSkipped('a fake ssh shell script');
|
|
}
|
|
$dir = sys_get_temp_dir() . '/jumphp-ssh-' . bin2hex(random_bytes(4));
|
|
mkdir("$dir/fake", 0777, true);
|
|
mkdir("$dir/remote/www", 0777, true);
|
|
mkdir("$dir/project/src", 0777, true);
|
|
file_put_contents("$dir/remote/www/index.php", "<?php\r\necho 1;\r\n");
|
|
file_put_contents("$dir/project/src/app.txt", 'local');
|
|
// ssh: the "server" is a folder of this computer, the remote command runs there; scp: cp, host: and escapes removed
|
|
file_put_contents("$dir/fake/ssh", "#!/bin/sh\necho \"\$@\" >> $dir/calls\nfor a; do last=\$a; done\ncd $dir/remote && exec sh -c \"\$last\"\n");
|
|
file_put_contents("$dir/fake/scp", "#!/bin/sh\necho \"scp \$@\" >> $dir/calls\nfor a; do prev=\$last; last=\$a; done\n"
|
|
. "fix() { case \"\$1\" in *:*) echo \"$dir/remote/\$(echo \"\${1#*:}\" | sed 's/\\\\\\(.\\)/\\1/g')\" ;; *) echo \"\$1\" ;; esac; }\n"
|
|
. "cp -R \"\$(fix \"\$prev\")\" \"\$(fix \"\$last\")\" && printf 'app.txt 100%% 5 1.0KB/s 00:00 \\n'\n");
|
|
chmod("$dir/fake/ssh", 0755);
|
|
chmod("$dir/fake/scp", 0755);
|
|
try {
|
|
$events = [];
|
|
$processes = new Processes();
|
|
$servers = new SshServers("$dir/settings.json");
|
|
$server = $servers->save(['name' => 'Fake', 'host' => 'fake.example', 'user' => 'me', 'folder' => 'www']);
|
|
$ssh = new SshCommands($processes, "$dir/project", function (string $event, array $payload) use (&$events) { $events[] = [$event, $payload]; },
|
|
$servers, 'Linux', fn (string $p) => in_array($p, ['ssh', 'scp'], true) ? "$dir/fake/$p" : null, "$dir/none");
|
|
$id = $server['id'];
|
|
|
|
self::assertTrue($processes->wait($ssh->test($id), 10)['ok']);
|
|
$list = $processes->wait($ssh->list($id, ''), 10);
|
|
self::assertSame("$dir/remote/www", $list['path']);
|
|
self::assertSame(['index.php'], array_column($list['entries'], 'name'));
|
|
|
|
$processes->wait($ssh->operation($id, 'mkdir', ["$dir/remote/www/new dir"], ''), 10);
|
|
$processes->wait($ssh->operation($id, 'move', ["$dir/remote/www/index.php"], "$dir/remote/www/new dir/main.php"), 10);
|
|
self::assertFileExists("$dir/remote/www/new dir/main.php");
|
|
$failed = $ssh->operation($id, 'copy', ["$dir/remote/missing"], "$dir/remote/x");
|
|
for ($end = microtime(true) + 10; !$failed->isDone() && microtime(true) < $end; usleep(2000)) {
|
|
$processes->poll();
|
|
}
|
|
self::assertStringContainsString('missing', (string)$failed->error()?->getMessage());
|
|
$this->expectRefused(fn () => $ssh->operation($id, 'delete', ['/'], ''));
|
|
|
|
// a remote file in the editor: CRLF kept when written back
|
|
$file = $processes->wait($ssh->read($id, "$dir/remote/www/new dir/main.php"), 10);
|
|
self::assertSame(['text' => true, 'content' => "<?php\necho 1;\n", 'eol' => 'CRLF'], ['text' => $file['text'], 'content' => $file['content'], 'eol' => $file['eol']]);
|
|
$processes->wait($ssh->write($id, "$dir/remote/www/new dir/main.php", "<?php\necho 2;\n", 'UTF-8', 'CRLF'), 10);
|
|
self::assertSame("<?php\r\necho 2;\r\n", file_get_contents("$dir/remote/www/new dir/main.php"));
|
|
|
|
// upload a project file, with scp's progress; then download it back into the project
|
|
$job = $ssh->transfer($id, 'upload', ['src/app.txt'], 'www/')['job'];
|
|
$this->until($processes, $events, 'ssh.transfer.end');
|
|
self::assertSame('local', file_get_contents("$dir/remote/www/app.txt"));
|
|
self::assertContains(['ssh.transfer', ['job' => $job, 'file' => 'app.txt', 'percent' => 100, 'done' => '5', 'speed' => '1.0KB/s', 'eta' => '00:00']], $events);
|
|
self::assertSame(['ssh.transfer.end', ['job' => $job, 'code' => 0, 'error' => '']], end($events));
|
|
$events = [];
|
|
mkdir("$dir/project/downloads");
|
|
$ssh->transfer($id, 'download', ['www/new dir'], 'downloads');
|
|
$this->until($processes, $events, 'ssh.transfer.end');
|
|
self::assertFileExists("$dir/project/downloads/new dir/main.php");
|
|
|
|
$calls = (string)file_get_contents("$dir/calls");
|
|
self::assertStringContainsString("scp -o BatchMode=yes -o ConnectTimeout=15 -o ControlPath=~/.ssh/jumphp-%C -o ControlMaster=no -r -p $dir/project/src/app.txt [email protected]:www/", $calls);
|
|
self::assertStringContainsString("[email protected]:www/new\\ dir $dir/project/downloads", $calls);
|
|
self::assertStringStartsWith('ssh -o \'ControlPath', $ssh->session($id)['line']);
|
|
} finally {
|
|
exec('rm -rf ' . escapeshellarg($dir));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Against a real sshd with the computer's real ssh / scp (opt-in: JUMPHP_SSH_E2E=host:port:user:keyfile, e.g. a throwaway
|
|
* linuxserver/openssh-server container; see docs/ide.md "SSH"). Skipped without it.
|
|
*/
|
|
public function testARealServer(): void
|
|
{
|
|
$spec = (string)getenv('JUMPHP_SSH_E2E');
|
|
if ($spec === '' || PHP_OS_FAMILY === 'Windows') {
|
|
self::markTestSkipped('JUMPHP_SSH_E2E=host:port:user:keyfile runs it against a real sshd');
|
|
}
|
|
[$host, $port, $user, $key] = explode(':', $spec, 4);
|
|
$dir = sys_get_temp_dir() . '/jumphp-ssh-e2e-' . bin2hex(random_bytes(4));
|
|
mkdir("$dir/project/up dir", 0777, true);
|
|
file_put_contents("$dir/project/up dir/hello world.txt", "hi\r\n");
|
|
try {
|
|
$events = [];
|
|
$processes = new Processes();
|
|
$servers = new SshServers("$dir/settings.json");
|
|
$id = $servers->save(['host' => $host, 'port' => (int)$port, 'user' => $user, 'identity' => $key])['id'];
|
|
$ssh = new SshCommands($processes, "$dir/project", function (string $event, array $payload) use (&$events) { $events[] = [$event, $payload]; }, $servers);
|
|
self::assertSame(['ok' => true, 'message' => ''], $processes->wait($ssh->test($id), 30));
|
|
$home = $processes->wait($ssh->list($id, ''), 30)['path'];
|
|
$base = "$home/e2e it's (1)";
|
|
$processes->wait($ssh->operation($id, 'delete', [$base], ''), 30);
|
|
$processes->wait($ssh->operation($id, 'mkdir', [$base], ''), 30);
|
|
$ssh->transfer($id, 'upload', ['up dir'], $base);
|
|
$this->until($processes, $events, 'ssh.transfer.end');
|
|
self::assertSame(0, end($events)[1]['code'], (string)end($events)[1]['error']);
|
|
$listed = $processes->wait($ssh->list($id, "$base/up dir"), 30);
|
|
self::assertSame(['hello world.txt'], array_column($listed['entries'], 'name'));
|
|
$processes->wait($ssh->operation($id, 'copy', ["$base/up dir/hello world.txt"], "$base/copy.txt"), 30);
|
|
$processes->wait($ssh->operation($id, 'move', ["$base/copy.txt"], "$base/moved é.txt"), 30);
|
|
$file = $processes->wait($ssh->read($id, "$base/moved é.txt"), 30);
|
|
self::assertSame(["hi\n", 'CRLF'], [$file['content'], $file['eol']]);
|
|
$processes->wait($ssh->write($id, "$base/moved é.txt", "bye\n", 'UTF-8', 'LF'), 30);
|
|
$events = [];
|
|
mkdir("$dir/project/down");
|
|
$ssh->transfer($id, 'download', ["$base/moved é.txt", "$base/up dir"], 'down');
|
|
$this->until($processes, $events, 'ssh.transfer.end');
|
|
self::assertSame("bye\n", file_get_contents("$dir/project/down/moved é.txt"));
|
|
self::assertFileExists("$dir/project/down/up dir/hello world.txt");
|
|
$processes->wait($ssh->operation($id, 'delete', [$base], ''), 30);
|
|
self::assertNotContains("e2e it's (1)", array_column($processes->wait($ssh->list($id, $home), 30)['entries'], 'name'));
|
|
} finally {
|
|
exec('rm -rf ' . escapeshellarg($dir));
|
|
}
|
|
}
|
|
|
|
private function expectRefused(callable $fn): void
|
|
{
|
|
try {
|
|
$fn();
|
|
self::fail('not refused');
|
|
} catch (\InvalidArgumentException $e) {
|
|
self::assertStringContainsString('refused', $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/** @param list<array{0: string, 1: array<string, mixed>}> $events */
|
|
private function until(Processes $processes, array &$events, string $event): void
|
|
{
|
|
for ($end = microtime(true) + 10; !in_array($event, array_column($events, 0), true) && microtime(true) < $end; usleep(2000)) {
|
|
$processes->poll();
|
|
}
|
|
self::assertContains($event, array_column($events, 0));
|
|
}
|
|
}
|