Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions app/Console/Commands/InstallModuleCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,15 +213,23 @@ protected function downloadModuleFile(string $location): string|null
$redirectLocation = $resp->getHeaderLine('Location');
if ($redirectLocation) {
$redirectUrl = parse_url($redirectLocation);
if (
($originalUrl['host'] ?? '') === ($redirectUrl['host'] ?? '')
$redirectOriginMatches = ($originalUrl['host'] ?? '') === ($redirectUrl['host'] ?? '')
&& ($originalUrl['scheme'] ?? '') === ($redirectUrl['scheme'] ?? '')
&& ($originalUrl['port'] ?? '') === ($redirectUrl['port'] ?? '')
) {
$currentLocation = $redirectLocation;
$redirectCount++;
continue;
&& ($originalUrl['port'] ?? '') === ($redirectUrl['port'] ?? '');

if (!$redirectOriginMatches) {
$redirectOrigin = ($redirectUrl['scheme'] ?? '') . '://' . ($redirectUrl['host'] ?? '') . (isset($redirectUrl['port']) ? ':' . $redirectUrl['port'] : '');
$this->info("The download URL is redirecting to a different site: {$redirectOrigin}");
$shouldContinue = $this->confirm("Do you trust downloading the module from this site?");
if (!$shouldContinue) {
$this->error("Stopping module installation");
return null;
}
}

$currentLocation = $redirectLocation;
$redirectCount++;
continue;
}
}

Expand Down
55 changes: 53 additions & 2 deletions app/Theming/ThemeModuleZip.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,41 @@ public function extractTo(string $destinationPath): void
{
$zip = new ZipArchive();
$zip->open($this->path);
$zip->extractTo($destinationPath);
$prefix = $this->getZipContentPrefix($zip);

for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
$entryIsDir = str_ends_with($name, "/");
if ($entryIsDir) {
continue;
}

$stream = $zip->getStreamIndex($i);

if ($prefix) {
if (!str_starts_with($name, $prefix) || $name === $prefix) {
continue;
}
$name = str_replace($prefix, '', $name);
}

$targetPath = $destinationPath . DIRECTORY_SEPARATOR . $name;
$targetPathDir = dirname($targetPath);
if (!is_dir($targetPathDir)) {
$dirCreated = mkdir($targetPathDir, 0777, true);
if (!$dirCreated) {
throw new ThemeModuleException("Failed to create directory {$targetPathDir} when extracting module files");
}
}

$targetFile = fopen($targetPath, 'w');
$written = stream_copy_to_stream($stream, $targetFile);
if (!$written) {
throw new ThemeModuleException("Failed to write to {$targetPath} when extracting module files");
}
fclose($targetFile);
}

$zip->close();
}

Expand All @@ -31,7 +65,8 @@ public function getModuleInstance(): ThemeModule
throw new ThemeModuleException("Unable to open zip file at {$this->path}");
}

$moduleJsonText = $zip->getFromName('bookstack-module.json');
$prefix = $this->getZipContentPrefix($zip);
$moduleJsonText = $zip->getFromName("{$prefix}bookstack-module.json");
$zip->close();

if ($moduleJsonText === false) {
Expand Down Expand Up @@ -95,4 +130,20 @@ public function getContentsSize(): int

return $totalSize;
}

protected function getZipContentPrefix(ZipArchive $zip): string
{
$index = $zip->locateName('bookstack-module.json', ZipArchive::FL_NODIR);
if ($index === false) {
return '';
}

$location = $zip->getNameIndex($index);
$pathParts = explode('/', $location);
if (count($pathParts) !== 2) {
return '';
}

return $pathParts[0] . '/';
}
}
1 change: 1 addition & 0 deletions dev/docs/theme-system-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Here are some general best practices when it comes to creating modules:
### Distribution Format

Modules are expected to be distributed as a compressed ZIP file, where the ZIP contents follow that of a module folder.
Contents may optionally be placed within a nested folder inside the ZIP.
BookStack provides a `php artisan bookstack:install-module` command which allows modules to be installed from these ZIP files, either from a local path or from a web URL.
Currently, there's a hardcoded total filesize limit of 50MB for module contents installed via this method.

Expand Down
77 changes: 76 additions & 1 deletion tests/Commands/InstallModuleCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,25 +96,71 @@ public function test_remote_module_install_follows_redirects()
});
}

public function test_remote_module_install_does_not_follow_redirects_to_different_origin()
public function test_remote_module_install_prompts_on_following_redirects_to_different_origin()
{
$this->usingThemeFolder(function () {
$zip = $this->getModuleZipPath();

$http = $this->mockHttpClient([
new Response(302, ['Location' => 'http://example.com/a-test-module.zip']),
new Response(301, ['Location' => 'https://a.example.com:8080/a-test-module.zip']),
new Response(200, ['Content-Length' => filesize($zip)], file_get_contents($zip))
]);

$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
->expectsConfirmation('Are you sure you trust this source?', 'yes')
->expectsOutput('The download URL is redirecting to a different site: http://example.com')
->expectsConfirmation('Do you trust downloading the module from this site?', 'yes')
->expectsOutput('The download URL is redirecting to a different site: https://a.example.com:8080')
->expectsConfirmation('Do you trust downloading the module from this site?', 'yes')
->assertExitCode(0);

$this->assertEquals(3, $http->requestCount());
$this->assertEquals('https', $http->requestAt(0)->getUri()->getScheme());
$this->assertEquals('http', $http->requestAt(1)->getUri()->getScheme());
$this->assertEquals('a.example.com', $http->requestAt(2)->getUri()->getHost());
});
}

public function test_remote_module_install_redirect_origin_prompt_rejection()
{
$this->usingThemeFolder(function () {
$http = $this->mockHttpClient([
new Response(302, ['Location' => 'http://example.com/a-test-module.zip']),
new Response(301, ['Location' => 'https://a.example.com:8080/a-test-module.zip']),
]);

$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
->expectsConfirmation('Are you sure you trust this source?', 'yes')
->expectsOutput('The download URL is redirecting to a different site: http://example.com')
->expectsConfirmation('Do you trust downloading the module from this site?', 'no')
->assertExitCode(1);

$this->assertEquals(1, $http->requestCount());
$this->assertEquals('https', $http->requestAt(0)->getUri()->getScheme());
});
}

public function test_remote_module_install_has_redirect_limit()
{
$this->usingThemeFolder(function () {
$http = $this->mockHttpClient([
new Response(302, ['Location' => 'https://example.com/a-test-module.zip']),
new Response(302, ['Location' => 'https://example.com/b-test-module.zip']),
new Response(302, ['Location' => 'https://example.com/c-test-module.zip']),
new Response(302, ['Location' => 'https://example.com/d-test-module.zip']),
]);

$this->artisan('bookstack:install-module', ['location' => 'https://example.com/test-module.zip'])
->expectsConfirmation('Are you sure you trust this source?', 'yes')
->expectsOutput('ERROR: Failed to download module from https://example.com/test-module.zip')
->assertExitCode(1);

$this->assertEquals(4, $http->requestCount());
$this->assertEquals('/c-test-module.zip', $http->requestAt(3)->getUri()->getPath());
});
}

public function test_remote_module_install_download_failures_are_announced_to_user()
{
$this->usingThemeFolder(function () {
Expand Down Expand Up @@ -175,6 +221,35 @@ public function test_run_with_invalid_module_data_has_early_exit()
->assertExitCode(1);
}

public function test_module_zip_when_files_in_nested_directory()
{
$this->usingThemeFolder(function ($themeFolder) {
$zip = new ZipArchive();
$zipFile = tempnam(sys_get_temp_dir(), 'bs-test-module');
$zip->open($zipFile, ZipArchive::CREATE);

$zip->addEmptyDir('mod');
$zip->addFromString('mod/bookstack-module.json', json_encode($metadata ?? [
'name' => 'Test Module',
'description' => 'A test module for BookStack',
'version' => '1.0.0',
]));
$zip->addFromString('mod/functions.php', '<?php $a = "cat";');
$zip->addEmptyDir('mod/a');
$zip->addFromString('mod/a/cat.txt', 'Meow');
$zip->close();

$this->artisan('bookstack:install-module', ['location' => $zipFile])
->expectsConfirmation('Are you sure you want to install this module?', 'yes')
->assertExitCode(0);

$modulePath = glob(theme_path('modules/*'), GLOB_ONLYDIR)[0];
$this->assertFileExists($modulePath . '/a/cat.txt');
$contents = file_get_contents($modulePath . '/a/cat.txt');
$this->assertEquals('Meow', $contents);
});
}

public function test_local_module_install_without_active_theme_can_setup_theme_folder()
{
$zip = $this->getModuleZipPath();
Expand Down
Loading