SPE-3961: Fix plugin marketplace install and token handoff

MarketplaceClient: remove the recursive perform_download_step() that
reinstalled the plugin in a loop, copy `config` into the job callbacks
instead of holding a reference to a temporary, and report real HTTP errors
(HttpCurl passes an empty `error` for status >= 400, so failures were
reported as an empty string). The verify step had no on_error at all.

BrowserLogicPluginMarketplace: answer REQUEST_CONFIG and
REQUEST_ACCESS_TOKEN through one send_config() that stays silent while the
access token is refreshing and pushes the fresh one from
on_user_account_id_success(), instead of resending the same expired token
forever. Build the init() options through nlohmann so the token is escaped,
and stop dereferencing an unexpected after a failed INSTALL_PLUGIN parse.

PluginBundle: accept manifest.txt/manifest.sig next to
checksum.sha256/checksum.sha256.sign, and fall back to plugin_api_version
when required_apis is absent, so bundles from the marketplace install. This
is a shim until one form is agreed on.

PluginSystem: report download errors through IPluginInstallationListener
instead of swallowing them, and keep a store_key() exception from killing
the main thread.

HttpCurl: the User-Agent used boost::format placeholders in fmt::format and
sent the literal "%1%/%2% (%3%)" on every request.

ServiceConfig: add SLIC3R_ALLOW_LOCALHOST_SERVICES (default OFF) so a dev
build can point PRUSA_*_URL at localhost, and name the variable in the
rejection warning.

Adds tests covering the install contract against a real signed bundle from
the marketplace.
This commit is contained in:
Lukáš Brzák 2026-08-21 09:33:46 +02:00 • committed by Jan Bařtipán
parent 2cf4f93c44
commit ab60c05992
15 changed files with 791 additions and 107 deletions

View file

@ -28,6 +28,7 @@ endif ()
option(SLIC3R_ASAN "Enable ASan on Clang and GCC" 0)
option(SLIC3R_UBSAN "Enable UBSan on Clang and GCC" 0)
option(SLIC3R_REPO_URL "Preset repo URL")
option(SLIC3R_ALLOW_LOCALHOST_SERVICES "Let PRUSA_*_URL env overrides point at localhost (local development only, never for release builds)" OFF)
option(SLIC3R_RELEASE_DEBUG_SYMBOLS "Build release build with debug symbols" ON)
option(SLIC3R_ENABLE_PROFILING "Enable Tracy profiling instrumentation" OFF)

View file

@ -1616,6 +1616,10 @@ if (SLIC3R_REPO_URL)
target_compile_definitions(slic3r-shared PRIVATE SLIC3R_REPO_URL="${SLIC3R_REPO_URL}")
endif()
if (SLIC3R_ALLOW_LOCALHOST_SERVICES)
target_compile_definitions(slic3r-shared PRIVATE SLIC3R_ALLOW_LOCALHOST_SERVICES)
endif()
if (SLIC3R_ENABLE_WEBKIT)
target_compile_definitions(slic3r-shared PRIVATE SLIC3R_HAS_WEBKIT)
endif()
@ -1667,6 +1671,9 @@ if(SLIC3R_BUILD_TESTS)
test/Slic3r/App/DialogNavigationTests.cpp
test/Slic3r/App/OpenFiles/OpenFilesDialogModelTests.cpp
test/Slic3r/App/Lua/PluginBundleTests.cpp
test/Slic3r/App/Lua/MarketplaceClientTests.cpp
test/Slic3r/App/Config/CategoryUtilsTests.cpp
test/Slic3r/App/Undo/ToolStateSerializeTests.cpp

View file

@ -19,7 +19,30 @@ public:
const std::string& current_url
) override;
/**
* @brief A (possibly refreshed) access token is available - push it to the web app.
*/
std::vector<BrowserLogicCommand> on_user_account_id_success(bool is_refresh, const std::string& current_url) override;
/**
* @brief Account signed out - let the web app drop its marketplace session.
*/
std::vector<BrowserLogicCommand> on_user_account_logged_out(const std::string& current_url) override;
private:
/**
* @brief Answer REQUEST_CONFIG / REQUEST_ACCESS_TOKEN. Stays silent while a token
* refresh is in flight; on_user_account_id_success() delivers the fresh token.
* @param reason Action name, for logging only.
*/
std::vector<BrowserLogicCommand> send_config(const std::string& reason);
/**
* @brief `_pluginMarketplace_v1.init(...)` call. Pass an empty token to hand over
* only the plugin API version (anonymous browsing).
*/
std::string init_script(const std::string& access_token) const;
Biz::ProjectInteractor& m_project_interactor;
Lua::PluginSystem& m_plugin_system;
};

View file

@ -3,9 +3,17 @@
#include <nlohmann/json.hpp>
#include "Slic3r/Biz/Network/ServiceConfig.hpp"
#include "Slic3r/Log.hpp"
namespace Slic3r::App::Browser {
namespace {
// Plugin API this Slicer build speaks (semver). The marketplace filters the
// catalogue by it - see docs/slicer-webview.md in the marketplace repo.
// Bump together with the Lua plugin API.
constexpr const char* PLUGIN_API_VERSION = "1.0.0";
} // namespace
BrowserLogicPluginMarketplace::BrowserLogicPluginMarketplace(Biz::ProjectInteractor& project_interactor, Lua::PluginSystem& plugin_system) :
AbstractBrowserLogic(
Biz::Network::ServiceConfig::instance().plugin_marketplace_url(),
@ -18,60 +26,125 @@ BrowserLogicPluginMarketplace::BrowserLogicPluginMarketplace(Biz::ProjectInterac
m_plugin_system(plugin_system)
{}
std::string BrowserLogicPluginMarketplace::init_script(const std::string& access_token) const
{
// Build the options through nlohmann so the token is JSON-escaped instead of
// being pasted straight into a JS string literal.
nlohmann::json options;
options["pluginApiVersion"] = PLUGIN_API_VERSION;
if (!access_token.empty()) {
options["accessToken"] = access_token;
}
// The web app registers _pluginMarketplace_v1 on load; guard so an unsolicited
// push (token refresh) before that cannot throw inside the webview.
return "window._pluginMarketplace_v1 && window._pluginMarketplace_v1.init(" + options.dump() + ")";
}
std::vector<BrowserLogicCommand> BrowserLogicPluginMarketplace::send_config(const std::string& reason)
{
auto& account = m_project_interactor.user_account_interactor();
if (!account.is_logged_in()) {
// Hand over the plugin API version anyway so the catalogue can filter;
// without a token the web app stays on its anonymous path instead of
// retrying the session exchange.
SPDLOG_INFO("Plugin Marketplace: {} with no signed-in account, sending config without a token", reason);
return {{BrowserLogicCommandType::RunScript, init_script({})}};
}
if (account.validate_and_refresh()) {
// Token is expired and a refresh was just queued. Answering with the stale
// token is what made the web app and the host ping-pong REQUEST_ACCESS_TOKEN
// forever; on_user_account_id_success() pushes the fresh one once it lands.
SPDLOG_INFO("Plugin Marketplace: {} while the access token is refreshing, deferring", reason);
return {};
}
const std::string access_token = account.access_token();
if (access_token.empty()) {
SPDLOG_WARN("Plugin Marketplace: {} but the access token is empty, sending config without a token", reason);
return {{BrowserLogicCommandType::RunScript, init_script({})}};
}
return {{BrowserLogicCommandType::RunScript, init_script(access_token)}};
}
std::vector<BrowserLogicCommand> BrowserLogicPluginMarketplace::on_script_message_webview_event(
const std::string& message
)
{
std::string action;
nlohmann::json msg = nlohmann::json::parse(message);
if (auto it = msg.find("action"); it != msg.end()) {
it->get_to(action);
}
// FE → Slicer (_prusaSlicer.postMessage)
// FE -> Slicer (_prusaSlicer.postMessage)
//
// Host bridge detected
// { action: 'WEBAPP_READY', componentName: 'plugin-marketplace' }
//
// Host bridge detected
// { action: 'REQUEST_CONFIG' }
//
// /auth/slicer-session fails
// { action: 'REQUEST_ACCESS_TOKEN' }
//
// User taps Install
// { action: 'REQUEST_ACCESS_TOKEN' } // session exchange failed
// { action: 'INSTALL_PLUGIN', pluginId, version, downloadUrl, verifyUrl, apiOrigin }
if (action == "WEBAPP_READY") {
SPDLOG_INFO("Plugin marketplace loaded");
} else if (action == "REQUEST_CONFIG") {
SPDLOG_INFO("Plugin market place request config");
auto access_token = m_project_interactor.user_account_interactor().access_token();
return {BrowserLogicCommand{
BrowserLogicCommandType::RunScript,
std::string("_pluginMarketplace_v1.init({ accessToken: '") + access_token + "', pluginApiVersion: '1.0.0' })"
}};
} else if (action == "REQUEST_ACCESS_TOKEN") {
SPDLOG_INFO("Plugin market place request token");
auto access_token = m_project_interactor.user_account_interactor().access_token();
return {BrowserLogicCommand{
BrowserLogicCommandType::RunScript,
std::string("window._pluginMarketplace_v1.init({ accessToken: '") + access_token + "', pluginApiVersion: '1.0.0' }); console.log('token passed');"
}};
} else if (action == "INSTALL_PLUGIN") {
auto result = Lua::BundleRequestConfig::load_from_json(msg);
if (!result.has_value()) {
SPDLOG_ERROR("Cannot parse message passed: {}", message);
nlohmann::json msg;
std::string action;
try {
msg = nlohmann::json::parse(message);
if (auto it = msg.find("action"); it != msg.end() && it->is_string()) {
it->get_to(action);
}
SPDLOG_INFO("Plugin Marketplace Install plugin: {}", result->plugin_id);
m_plugin_system.install_marketplace_bundle(result.value());
} else {
SPDLOG_INFO("Plugin Marketplace: Unknown action {}", action);
} catch (const nlohmann::json::exception& e) {
SPDLOG_ERROR("Plugin Marketplace: cannot parse webview message ({}): {}", e.what(), message);
return {};
}
if (action.empty()) {
SPDLOG_ERROR("Plugin Marketplace: webview message without an action: {}", message);
return {};
}
if (action == "WEBAPP_READY") {
SPDLOG_INFO("Plugin Marketplace: web app ready");
return {};
}
if (action == "REQUEST_CONFIG" || action == "REQUEST_ACCESS_TOKEN") {
SPDLOG_INFO("Plugin Marketplace: {}", action);
return send_config(action);
}
if (action == "INSTALL_PLUGIN") {
auto result = Lua::BundleRequestConfig::load_from_json(msg);
if (!result.has_value()) {
SPDLOG_ERROR("Plugin Marketplace: cannot parse INSTALL_PLUGIN ({}): {}", result.error(), message);
return {};
}
SPDLOG_INFO("Plugin Marketplace: install {}@{}", result->plugin_id, result->version);
m_plugin_system.install_marketplace_bundle(result.value());
return {};
}
SPDLOG_INFO("Plugin Marketplace: unknown action {}", action);
return {};
}
std::vector<BrowserLogicCommand> BrowserLogicPluginMarketplace::on_user_account_id_success(
bool is_refresh,
const std::string& current_url
)
{
const std::string access_token = m_project_interactor.user_account_interactor().access_token();
if (access_token.empty()) {
return {};
}
SPDLOG_INFO("Plugin Marketplace: pushing {} access token", is_refresh ? "refreshed" : "new");
return {{BrowserLogicCommandType::RunScript, init_script(access_token)}};
}
std::vector<BrowserLogicCommand> BrowserLogicPluginMarketplace::on_user_account_logged_out(
const std::string& current_url
)
{
return {
{BrowserLogicCommandType::RunScript,
"window._pluginMarketplace_v1 && window._pluginMarketplace_v1.logout()"}
};
}
std::vector<BrowserLogicCommand> BrowserLogicPluginMarketplace::
on_navigation_request_webview_event(const std::string& new_url, const std::string& current_url)
{

View file

@ -1,6 +1,7 @@
#include "Slic3r/App/Lua/MarketplaceClient.hpp"
#include "Slic3r/Directories.hpp"
#include "Slic3r/Log.hpp"
#include "Slic3r/Biz/CerealUtils.hpp"
#include "Slic3r/Biz/Network/IHttp.hpp"
#include "Slic3r/Biz/Platform/PlatformServices.hpp"
@ -46,6 +47,27 @@ auto make_retry_fn(Biz::JThread::StopToken& stop_token)
};
}
/**
* HttpCurl reports HTTP >= 400 with an empty `error` and the payload in `body`, and
* transport failures the other way round. Without this, a 404 arrives as an empty
* message. Note curl follows redirects, so the status can come from the storage
* backend the download URL redirects to, not from the marketplace API.
*/
std::string http_error_message(const std::string& body, const std::string& error, unsigned status)
{
constexpr std::size_t max_body = 300;
const std::string detail = body.size() > max_body ? body.substr(0, max_body) + "..." : body;
if (!error.empty()) {
return status != 0 ? fmt::format("{} (HTTP {})", error, status) : error;
}
if (status != 0) {
return detail.empty() ? fmt::format("HTTP {}", status)
: fmt::format("HTTP {}: {}", status, detail);
}
return detail.empty() ? std::string{"request failed for an unknown reason"} : detail;
}
tl::expected<void, std::string> save_file(const fs::path& dest, std::string_view data)
{
try {
@ -75,55 +97,65 @@ tl::expected<void, std::string> save_file(const fs::path& dest, std::string_view
void MarketplaceClient::perform_verify_step(const BundleRequestConfig& config)
{
using VerifyResult = tl::expected<VerifiedBundleData, std::string>;
auto job = [config = config, this](Biz::JThread::StopToken stop_token)
auto job = [config](Biz::JThread::StopToken stop_token) -> VerifyResult
{
auto retry_fn = make_retry_fn(stop_token);
auto http_ptr = Biz::Network::IHttp::
create(Biz::Network::IHttp::RequestMethod::Get, config.verify_url, retry_fn);
auto& http = *http_ptr;
std::optional<VerifiedBundleData> data;
VerifyResult result = tl::unexpected{std::string{"verify request did not complete"}};
http.on_complete([&](const std::string& body, unsigned status)
{
try {
nlohmann::json j = nlohmann::json::parse(body);
bool ok;
std::string asset_id;
std::string version;
std::string public_key;
std::string author_id;
j.at("ok").get_to(ok);
j.at("assetId").get_to(asset_id);
j.at("version").get_to(version);
j.at("publicKey").get_to(public_key);
j.at("authorId").get_to(author_id);
if (!j.value("ok", false)) {
result = tl::unexpected{fmt::format(
"bundle signature was refused: {}",
j.value("reason", std::string{"no reason given"})
)};
return;
}
data = {.plugin_id = asset_id, .version = version, .public_key = public_key};
VerifiedBundleData data;
j.at("assetId").get_to(data.plugin_id);
j.at("version").get_to(data.version);
j.at("publicKey").get_to(data.public_key);
result = std::move(data);
} catch (std::exception& e) {
report_error(config.plugin_id, e.what());
result = tl::unexpected{fmt::format("cannot parse verify response: {}", e.what())};
}
})
.on_error([&](const std::string& body, const std::string& error, unsigned status)
{
result = tl::unexpected{http_error_message(body, error, status)};
});
http_ptr->perform_sync();
http.perform_sync();
return data;
return result;
};
auto& job_manager = Biz::Platform::PlatformServices::instance().job_manager();
job_manager.create_job("plugin-verify", std::move(job))
.on_result(
[config = config, this](auto data)
[config, this](VerifyResult result)
{
if (data.has_value()) {
invoke_listeners<IMarketplaceClientListener>(
[&](IMarketplaceClientListener* l) { l->on_bundle_verified(data.value()); }
);
perform_download_step(config);
if (!result.has_value()) {
report_error(config.plugin_id, result.error());
return;
}
invoke_listeners<IMarketplaceClientListener>(
[&](IMarketplaceClientListener* l) { l->on_bundle_verified(result.value()); }
);
perform_download_step(config);
}
)
.on_exception(
[this, &config](const std::exception_ptr& eptr)
[config, this](const std::exception_ptr& eptr)
{
try {
std::rethrow_exception(eptr);
@ -137,63 +169,62 @@ void MarketplaceClient::perform_verify_step(const BundleRequestConfig& config)
void MarketplaceClient::perform_download_step(const BundleRequestConfig& config)
{
auto job = [config = config, this](Biz::JThread::StopToken stop_token)
using DownloadResult = tl::expected<std::string, std::string>;
auto job = [config, this](Biz::JThread::StopToken stop_token) -> DownloadResult
{
std::optional<std::string> download_path;
auto retry_fn = make_retry_fn(stop_token);
auto http_ptr = Biz::Network::IHttp::
create(Biz::Network::IHttp::RequestMethod::Get, config.download_url, retry_fn);
auto& http = *http_ptr;
http // setup handlers
.on_complete(
[this, &config, &download_path](const std::string& body, unsigned status)
{
auto dest_path =
download_dir() / fmt::format("{}@{}.zip", config.plugin_id, config.version);
if (auto result = save_file(dest_path, body); !result.has_value()) {
report_error(config.plugin_id, result.error());
return;
}
download_path = dest_path.string();
}
)
.on_error(
[this, &config](const std::string& body, const std::string& error, unsigned status)
{
Biz::Platform::PlatformServices::instance()
.main_thread_dispatcher()
.dispatch_on_main_thread(
[=, this] { report_error(config.plugin_id, error); }
);
}
);
DownloadResult result = tl::unexpected{std::string{"download request did not complete"}};
http.on_complete([&](const std::string& body, unsigned status)
{
if (body.empty()) {
result = tl::unexpected{fmt::format("downloaded bundle is empty (HTTP {})", status)};
return;
}
auto dest_path =
download_dir() / fmt::format("{}@{}.zip", config.plugin_id, config.version);
if (auto saved = save_file(dest_path, body); !saved.has_value()) {
result = tl::unexpected{saved.error()};
return;
}
result = dest_path.string();
})
.on_error([&](const std::string& body, const std::string& error, unsigned status)
{
result = tl::unexpected{http_error_message(body, error, status)};
});
http.perform_sync();
return download_path;
return result;
};
auto& job_manager = Biz::Platform::PlatformServices::instance().job_manager();
job_manager.create_job("plugin-download", std::move(job))
.on_result([config = config, this](const auto& download_path)
{
if (download_path.has_value()) {
.on_result(
[config, this](DownloadResult result)
{
if (!result.has_value()) {
report_error(config.plugin_id, result.error());
return;
}
invoke_listeners<IMarketplaceClientListener>(
[&download_path, &config](IMarketplaceClientListener* l)
[&](IMarketplaceClientListener* l)
{
l->on_bundle_downloaded(
config.plugin_id,
config.version,
download_path.value()
);
l->on_bundle_downloaded(config.plugin_id, config.version, result.value());
}
);
perform_download_step(config);
}
})
)
.on_exception(
[this, &config](const std::exception_ptr& eptr)
[config, this](const std::exception_ptr& eptr)
{
try {
std::rethrow_exception(eptr);
@ -203,11 +234,12 @@ void MarketplaceClient::perform_download_step(const BundleRequestConfig& config)
}
)
.start();
}
void MarketplaceClient::report_error(const std::string& plugin_id, const std::string& message)
{
// Only ever called from job on_result / on_exception, i.e. on the main thread.
SPDLOG_ERROR("Plugin Marketplace: {} failed: {}", plugin_id, message);
invoke_listeners<IMarketplaceClientListener>(
[&](IMarketplaceClientListener* l) { l->on_download_error(plugin_id, message); }
);

View file

@ -4,6 +4,7 @@
#include <Slic3r/Log.hpp>
#include <ranges>
#include <string_view>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
@ -86,9 +87,26 @@ Result<PluginBundleMeta> load_meta_from_text(std::string_view json_str)
{
PluginBundleMeta::ApiVersionMap ret;
std::map<std::string, std::string> raw_data;
if (auto err = get("required_apis", raw_data, true); err.has_value()) {
if (auto err = get("required_apis", raw_data, false); err.has_value()) {
return tl::unexpected(err.value());
}
if (raw_data.empty()) {
// Marketplace manifests declare a single plugin API semver
// (plugin_api_version) instead of a per-API map. Treat it as the
// requirement for the only API type we have.
std::string plugin_api_version;
if (auto err = get("plugin_api_version", plugin_api_version, false);
err.has_value()) {
return tl::unexpected(err.value());
}
if (plugin_api_version.empty()) {
return tl::unexpected(
std::string{"Missing required field 'required_apis' "
"(or 'plugin_api_version')"}
);
}
raw_data.emplace(to_string(PluginApiType::Project), plugin_api_version);
}
for (const auto& [raw_api, raw_ver] : raw_data) {
auto api = parse_plugin_api_type(raw_api);
if (!api.has_value()) {

View file

@ -162,13 +162,32 @@ Yoga::Passthrough<PluginDialog>& PluginSystem::init_dialog()
void PluginSystem::on_download_error(const std::string& plugin_id, const std::string& message)
{
SPDLOG_ERROR("Marketplace bundle download failed for {}: {}", plugin_id, message);
std::string error_message = fmt::format(
fmt::runtime(
// TRN {0} is a plugin id, {1} describes what went wrong
Biz::_u8L("Cannot download plugin {0}: {1}")
),
plugin_id,
message
);
invoke_listeners<IPluginInstallationListener>(
[&error_message](auto* listener)
{ listener->on_plugin_installation_error(error_message); }
);
}
void PluginSystem::on_bundle_verified(const VerifiedBundleData& data)
{
auto key_id = fmt::format("{}@{}", data.plugin_id, data.version);
m_registry.public_key_registry().store_key(key_id, data.public_key);
try {
m_registry.public_key_registry().store_key(key_id, data.public_key);
} catch (std::exception& e) {
// Runs on the main thread from the marketplace job callback - letting this
// escape would take the app down instead of failing the install.
SPDLOG_ERROR("Cannot store author public key {}: {}", key_id, e.what());
on_download_error(data.plugin_id, e.what());
}
}
void PluginSystem::on_bundle_downloaded(

View file

@ -112,7 +112,9 @@ HttpCurl::HttpCurl(RequestMethod request_method, std::string&& url, RetryFn fn)
throw Slic3r::RuntimeError(std::string("Could not construct Curl object"));
}
std::string user_agent = fmt::format("{}/{} ({})",SLIC3R_APP_NAME, SLIC3R_VERSION, platform_to_string(platform()));
// boost::format placeholders (%1%) do nothing in fmt::format - this used to send
// the literal "{}/{} ({})" as the User-Agent on every request.
std::string user_agent = fmt::format("{}/{} ({})", SLIC3R_APP_NAME, SLIC3R_VERSION, platform_to_string(platform()));
timeout_connection(DEFAULT_TIMEOUT_CONNECT);
timeout_total(DEFAULT_TIMEOUT_MAX);

View file

@ -39,7 +39,13 @@ void update_url_from_env(std::string& dest, const char* env_name, const std::vec
if (is_whitelisted_url(candidate, allowed_domains)) {
dest = std::move(candidate);
} else {
SPDLOG_WARN("Url was not set from env variable: {}. New adress is not whitelisted.", candidate);
SPDLOG_WARN(
"Ignoring {}={}: apex domain '{}' is not whitelisted, keeping {}.",
env_name,
candidate,
IHttp::get_apex_domain(candidate),
dest
);
}
}
}
@ -66,7 +72,9 @@ ServiceConfig::ServiceConfig() :
"prusa3d.dev",
"printables.com",
"testprusaverse.com",
#ifndef NDEBUG
#if !defined(NDEBUG) || defined(SLIC3R_ALLOW_LOCALHOST_SERVICES)
// Local development. get_apex_domain() keeps only the last two labels,
// so "localhost" passes but "127.0.0.1" does not - use localhost.
"localhost",
#endif
};

View file

@ -0,0 +1,255 @@
#include "Slic3r/App/Lua/MarketplaceClient.hpp"
#include "Slic3r/Biz/Network/MockHttp.hpp"
#include "Slic3r/Biz/Network/MockHttpFactory.hpp"
#include "Slic3r/App/Platform/StdMainThreadDispatcher.hpp"
#include "Slic3r/Biz/Platform/PlatformServices.hpp"
#include "Slic3r/Biz/Platform/JobManager/JobManager.hpp"
#include "Slic3r/Directories.hpp"
#include <catch2/catch_test_macros.hpp>
#include <boost/filesystem/operations.hpp>
#include <chrono>
#include <string>
#include <thread>
#include <vector>
/*
* MarketplaceClient drives verify -> download -> listeners over IHttp. Mocked
* here so the two failure modes that used to be invisible stay covered:
*
* - a successful download must notify listeners exactly once (it used to
* re-enter perform_download_step() from its own on_result, downloading and
* installing the plugin in an endless loop)
* - HttpCurl reports HTTP >= 400 with an EMPTY error string and the payload in
* the body, so reporting `error` verbatim produced empty error messages
*/
namespace fs = boost::filesystem;
using Slic3r::App::Lua::BundleRequestConfig;
using Slic3r::App::Lua::IMarketplaceClientListener;
using Slic3r::App::Lua::MarketplaceClient;
using Slic3r::App::Lua::VerifiedBundleData;
using Slic3r::App::Platform::StdMainThreadDispatcher;
using Slic3r::Biz::Platform::PlatformServices;
using Slic3r::Biz::Platform::JobManager::JobManager;
namespace {
constexpr auto VERIFY_URL = "http://localhost:4455/api/plugins/com.test.plugin/verify?version=1.0.0";
constexpr auto DOWNLOAD_URL = "http://localhost:4455/api/plugins/com.test.plugin/download?version=1.0.0";
constexpr auto ZIP_BODY = "PK\x03\x04-not-a-real-zip-but-non-empty";
BundleRequestConfig test_config()
{
BundleRequestConfig config;
config.plugin_id = "com.test.plugin";
config.version = "1.0.0";
config.verify_url = VERIFY_URL;
config.download_url = DOWNLOAD_URL;
config.api_origin = "http://localhost:4455";
return config;
}
struct RecordingListener : IMarketplaceClientListener
{
std::vector<std::string> verified;
std::vector<std::string> downloaded;
std::vector<std::string> errors;
void on_download_error(const std::string&, const std::string& message) override
{
errors.push_back(message);
}
void on_bundle_verified(const VerifiedBundleData& data) override
{
verified.push_back(data.plugin_id + "@" + data.version);
}
void on_bundle_downloaded(const std::string&, const std::string&, const std::string& zip_path)
override
{
downloaded.push_back(zip_path);
}
};
/** What the mocked verify / download endpoints answer with. */
struct Responses
{
unsigned verify_status{200};
std::string verify_body{
R"({"assetId":"com.test.plugin","version":"1.0.0","ok":true,"publicKey":"-----BEGIN PUBLIC KEY-----\nstub\n-----END PUBLIC KEY-----\n"})"
};
unsigned download_status{200};
std::string download_body{ZIP_BODY};
/** Requests the mock saw, in order. */
std::shared_ptr<std::vector<std::string>> seen{std::make_shared<std::vector<std::string>>()};
};
struct Fixture
{
std::string prev_data_dir;
fs::path temp_data_dir;
StdMainThreadDispatcher dispatcher;
RecordingListener listener;
MarketplaceClient client;
Fixture()
{
prev_data_dir = Slic3r::data_dir();
temp_data_dir = fs::temp_directory_path() / fs::unique_path("slic3r-mkt-%%%%-%%%%");
fs::create_directories(temp_data_dir);
Slic3r::set_data_dir(temp_data_dir.string());
Slic3r::Biz::Network::configure_http_factory_with_mock();
PlatformServices::instance().set_job_manager(std::make_unique<JobManager>(dispatcher));
client.add_listener<IMarketplaceClientListener>(&listener);
}
~Fixture()
{
client.remove_listener<IMarketplaceClientListener>(&listener);
PlatformServices::instance().set_job_manager(nullptr);
dispatcher.close();
Slic3r::set_data_dir(prev_data_dir);
boost::system::error_code ec;
fs::remove_all(temp_data_dir, ec);
}
void arrange_http(const Responses& responses)
{
Slic3r::Biz::Network::MockHttpProvider::get().set_create_fn(
[responses](
Slic3r::Biz::Network::IHttp::RequestMethod,
const std::string& url,
Slic3r::Biz::Network::IHttp::RetryFn retryfn
) -> std::unique_ptr<Slic3r::Biz::Network::MockHttp>
{
auto http = std::make_unique<Slic3r::Biz::Network::MockHttp>(url, retryfn);
http->set_perform_override_fn(
[responses,
url](Slic3r::Biz::Network::MockHttp* h, const Slic3r::Biz::Network::HttpRetryOpt&)
{
responses.seen->push_back(url);
const bool is_verify = url.find("/verify") != std::string::npos;
const unsigned status = is_verify ? responses.verify_status
: responses.download_status;
const std::string& body = is_verify ? responses.verify_body
: responses.download_body;
if (status >= 400) {
// Exactly how HttpCurl reports it: empty error, body carries the payload.
h->invoke_error(body, std::string{}, status);
} else {
h->invoke_complete(body, status);
}
}
);
return http;
}
);
}
/** Pump the main thread until `done` or the deadline. */
void pump_until(const std::function<bool()>& done, std::chrono::milliseconds budget)
{
const auto deadline = std::chrono::steady_clock::now() + budget;
while (std::chrono::steady_clock::now() < deadline) {
dispatcher.dispatch_enqueued();
if (done()) {
return;
}
std::this_thread::sleep_for(std::chrono::milliseconds(2));
}
dispatcher.dispatch_enqueued();
}
void pump_for(std::chrono::milliseconds budget)
{
pump_until([] { return false; }, budget);
}
};
} // namespace
TEST_CASE_METHOD(Fixture, "Successful install notifies listeners exactly once", "[marketplace]")
{
Responses responses;
arrange_http(responses);
client.download_bundle(test_config());
pump_until([&] { return !listener.downloaded.empty(); }, std::chrono::seconds(10));
REQUIRE(listener.errors.empty());
REQUIRE(listener.verified == std::vector<std::string>{"com.test.plugin@1.0.0"});
REQUIRE(listener.downloaded.size() == 1);
CHECK(fs::exists(listener.downloaded.front()));
CHECK(fs::file_size(listener.downloaded.front()) == std::string{ZIP_BODY}.size());
// The regression: perform_download_step() used to call itself from on_result,
// so the bundle was downloaded and installed over and over. Keep pumping and
// make sure nothing else arrives.
pump_for(std::chrono::milliseconds(1500));
CHECK(listener.downloaded.size() == 1);
CHECK(listener.verified.size() == 1);
CHECK(listener.errors.empty());
}
TEST_CASE_METHOD(Fixture, "A 404 on download is reported with a usable message", "[marketplace]")
{
Responses responses;
responses.download_status = 404;
responses.download_body = "Not Found";
arrange_http(responses);
client.download_bundle(test_config());
pump_until([&] { return !listener.errors.empty(); }, std::chrono::seconds(10));
REQUIRE(listener.errors.size() == 1);
const std::string& message = listener.errors.front();
CAPTURE(message);
// Used to be empty: HttpCurl passes "" as `error` for HTTP >= 400.
CHECK_FALSE(message.empty());
CHECK(message.find("404") != std::string::npos);
CHECK(message.find("Not Found") != std::string::npos);
CHECK(listener.downloaded.empty());
}
TEST_CASE_METHOD(Fixture, "A refused signature stops before downloading", "[marketplace]")
{
Responses responses;
responses.verify_body = R"({"assetId":"com.test.plugin","version":"1.0.0","ok":false,"reason":"signing key revoked"})";
arrange_http(responses);
client.download_bundle(test_config());
pump_until([&] { return !listener.errors.empty(); }, std::chrono::seconds(10));
REQUIRE(listener.errors.size() == 1);
CAPTURE(listener.errors.front());
CHECK(listener.errors.front().find("signing key revoked") != std::string::npos);
CHECK(listener.verified.empty());
CHECK(listener.downloaded.empty());
// Nothing may be fetched from the download endpoint after a refused verify.
for (const auto& url : *responses.seen) {
CHECK(url.find("/download") == std::string::npos);
}
}
TEST_CASE_METHOD(Fixture, "A 404 on verify is reported and stops the install", "[marketplace]")
{
Responses responses;
responses.verify_status = 404;
responses.verify_body = R"({"error":"version not found"})";
arrange_http(responses);
client.download_bundle(test_config());
pump_until([&] { return !listener.errors.empty(); }, std::chrono::seconds(10));
// Verify had no on_error handler at all before, so this failed silently.
REQUIRE(listener.errors.size() == 1);
CAPTURE(listener.errors.front());
CHECK(listener.errors.front().find("404") != std::string::npos);
CHECK(listener.downloaded.empty());
}

View file

@ -0,0 +1,139 @@
#include "Slic3r/App/Lua/PluginBundle.hpp"
#include "Slic3r/App/Lua/MarketplaceClient.hpp"
#include "Slic3r/Biz/Crypto/Types.hpp"
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <boost/filesystem/path.hpp>
#include <nlohmann/json.hpp>
#include <string>
/*
* Pins the install contract between the plugin marketplace and PrusaSlicer.
*
* The fixtures are real signed bundles taken from the marketplace API
* (GET /api/plugins/{id}/download) together with the author public key it hands
* over from GET /api/plugins/{id}/verify:
*
* marketplace-bundle.zip manifest.txt + manifest.sig
* checksum-named-bundle.zip checksum.sha256 + checksum.sha256.sign
*
* Both must install: the signature covers the checksum file's *content*, so the
* two namings are the same bundle repacked. Keep both until one naming wins.
*
* How to make a fresh keypair and bundle, and how to regenerate these files:
* test/data/plugin-bundle/README.md
*/
namespace fs = boost::filesystem;
using namespace Slic3r::App::Lua;
namespace {
fs::path bundle_dir()
{
return fs::path{TEST_DATA_DIR} / "plugin-bundle";
}
Slic3r::Biz::Crypto::KeyPair author_public_key()
{
const auto pem = Slic3r::Biz::Crypto::file_as_bytes((bundle_dir() / "public_key.pem").string());
return Slic3r::Biz::Crypto::KeyPair::load_pub_pem(pem);
}
PluginBundle open_bundle(const std::string& zip_name)
{
return PluginBundle{
Slic3r::Biz::Crypto::create_zip_source((bundle_dir() / zip_name).string())
};
}
} // namespace
TEST_CASE("Marketplace bundle passes load_meta + verify", "[plugin][marketplace]")
{
const auto zip_name = GENERATE(
std::string{"marketplace-bundle.zip"},
std::string{"checksum-named-bundle.zip"}
);
CAPTURE(zip_name);
auto bundle = open_bundle(zip_name);
SECTION("load_meta accepts a marketplace manifest.json")
{
const auto result = bundle.load_meta();
REQUIRE(result.has_value());
const auto& meta = bundle.meta();
CHECK(meta.id == "com.prusa3d.slicer.calibration");
CHECK(meta.version.to_string() == "1.1.0");
CHECK_FALSE(meta.author.empty());
// Marketplace manifests carry plugin_api_version instead of a
// required_apis map; it has to resolve to the project API requirement.
REQUIRE(meta.required_apis.size() == 1);
const auto it = meta.required_apis.find(PluginApiType::Project);
REQUIRE(it != meta.required_apis.end());
CHECK(it->second.to_string() == "1.0.0");
}
SECTION("verify accepts the signature made with the author key from /verify")
{
REQUIRE(bundle.load_meta().has_value());
CHECK(bundle.verify(author_public_key()));
}
SECTION("the key PluginRegistry looks up matches what /verify announced")
{
REQUIRE(bundle.load_meta().has_value());
// PluginRegistry::install builds "<id>@<version>" and PublicKeyRegistry
// stored it from the verify response - a mismatch means "cannot load
// public key" at install time.
const auto key_name = bundle.meta().id + "@" + bundle.meta().version.to_string();
CHECK(key_name == "com.prusa3d.slicer.calibration@1.1.0");
}
}
TEST_CASE("Marketplace bundle is rejected with the wrong key", "[plugin][marketplace]")
{
auto bundle = open_bundle("marketplace-bundle.zip");
REQUIRE(bundle.load_meta().has_value());
auto other = Slic3r::Biz::Crypto::KeyPair::generate(2048);
CHECK_FALSE(bundle.verify(other));
}
TEST_CASE("INSTALL_PLUGIN payload parsing", "[plugin][marketplace]")
{
SECTION("accepts what the marketplace web app posts")
{
// Mirrors InstallButton.tsx sendMessage({ action: 'INSTALL_PLUGIN', … }).
const auto msg = nlohmann::json::parse(R"({
"action": "INSTALL_PLUGIN",
"pluginId": "com.prusa3d.slicer.calibration",
"version": "1.1.0",
"downloadUrl": "http://localhost:4455/api/plugins/com.prusa3d.slicer.calibration/download?version=1.1.0",
"verifyUrl": "http://localhost:4455/api/plugins/com.prusa3d.slicer.calibration/verify?version=1.1.0",
"apiOrigin": "http://localhost:4455"
})");
const auto config = BundleRequestConfig::load_from_json(msg);
REQUIRE(config.has_value());
CHECK(config->plugin_id == "com.prusa3d.slicer.calibration");
CHECK(config->version == "1.1.0");
CHECK(config->api_origin == "http://localhost:4455");
CHECK(config->download_url.find("/download?version=1.1.0") != std::string::npos);
CHECK(config->verify_url.find("/verify?version=1.1.0") != std::string::npos);
}
SECTION("reports an error instead of yielding a half-filled config")
{
const auto msg = nlohmann::json::parse(R"({"action":"INSTALL_PLUGIN","pluginId":"x"})");
const auto config = BundleRequestConfig::load_from_json(msg);
REQUIRE_FALSE(config.has_value());
CHECK_FALSE(config.error().empty());
}
}

View file

@ -0,0 +1,98 @@
# Plugin bundle test fixtures
Used by `test/Slic3r/App/Lua/PluginBundleTests.cpp` to check that a signed plugin
bundle passes `PluginBundle::load_meta()` + `PluginBundle::verify()`.
| file | what it is |
|------|------------|
| `marketplace-bundle.zip` | a real bundle from the plugin marketplace — `manifest.txt` + `manifest.sig` |
| `checksum-named-bundle.zip` | the same bundle repacked as `checksum.sha256` + `checksum.sha256.sign` |
| `public_key.pem` | SPKI public key the signature was made with (`GET /api/plugins/{id}/verify` hands this to the Slicer) |
`public_key.pem` is the public half of a throwaway key; there is no private key here.
The two zips differ only in the names of the checksum + signature entries — the
signature covers the checksum file's **content**, not its name, so renaming is a
valid repack. Both exist because `PluginBundle` accepts either naming (see the
comment on `SIGNATURE_NAMES` in `PluginBundle.cpp`); if that shim is ever removed,
drop the fixture for the naming that lost.
The fixtures pin the format as of the day they were generated. They will **not**
catch the marketplace changing its output — that needs a live request, which does
not belong in the test suite.
## Making a fresh keypair and bundle by hand
No marketplace needed. This is also the flow a plugin author follows, and it is
what `src/lib/bundle/signing.ts` in the marketplace is byte-compatible with.
```bash
mkdir bundle && cd bundle
# 1. keypair (RSA-2048; private stays with the author, public goes to the marketplace)
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048
openssl rsa -pubout -in private_key.pem -out public_key.pem
# 2. bundle payload: manifest.json plus one or more .lua files (and whatever else)
# manifest.json needs at least id, author, version, and either required_apis
# or plugin_api_version. Each .lua that is a plugin needs a global `info`
# table - see doc/Plugin_API.md.
# 3. checksum file over every payload file, excluding itself and the signature
shasum -a256 manifest.json *.lua README.md | sort -k2 > checksum.sha256
# 4. sign the checksum file
openssl dgst -sha256 -sign private_key.pem -out checksum.sha256.sign checksum.sha256
# 5. zip it flat (no top-level directory)
zip -X ../bundle.zip manifest.json *.lua README.md checksum.sha256 checksum.sha256.sign
# verify the same way PluginBundle::verify() does
openssl dgst -sha256 -verify public_key.pem -signature checksum.sha256.sign checksum.sha256
shasum -a256 -c checksum.sha256
```
Things that will bite you:
- **Line format is `<sha256> <path>` with two spaces** — what `shasum -a256`
emits natively. `sha256sum` on Linux matches; do not hand-format it.
- **A trailing newline is fine.** `shasum` adds one and the marketplace does not;
`DirChecksum::load_from_file` drops empty lines, and both verify. But the
signature is over the exact bytes, so if you edit the checksum file at all you
must re-sign.
- **The checksum file must not list itself or the signature.** `verify()` runs
strict, so any file in the zip that is neither listed nor the checksum/signature
pair fails the bundle.
- **List the files explicitly, do not `zip -r .`** — a recursive zip of the working
directory sweeps in `private_key.pem` along with everything else. Besides leaking
the signing key, any file in the zip that the checksum file does not list fails
the strict check, so the bundle would not install anyway.
- **Paths are bundle-relative and the zip must be flat** — no top-level directory,
because the checksum paths have none.
## Regenerating these fixtures from the marketplace
With the marketplace stack up (`make up && make seed` in `slicer-plugin-marketplace`):
```bash
ID=com.prusa3d.slicer.calibration
V=1.1.0
curl -sL "http://localhost:4455/api/plugins/$ID/download?version=$V" -o marketplace-bundle.zip
curl -s "http://localhost:4455/api/plugins/$ID/verify?version=$V" \
| python3 -c 'import json,sys; print(json.load(sys.stdin)["publicKey"], end="")' > public_key.pem
```
Then repack the second variant with the two entries renamed:
```bash
python3 - <<'EOF'
import zipfile
rename = {"manifest.txt": "checksum.sha256", "manifest.sig": "checksum.sha256.sign"}
src = zipfile.ZipFile("marketplace-bundle.zip")
with zipfile.ZipFile("checksum-named-bundle.zip", "w", zipfile.ZIP_DEFLATED) as out:
for name in src.namelist():
out.writestr(rename.get(name, name), src.read(name))
EOF
```
`PluginBundleTests.cpp` asserts the plugin id and version, so regenerating from a
different plugin or version means updating those expectations too.

View file

@ -0,0 +1,9 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArKM2VemyhYsQ+GMtQbIk
IpNjoL1FqPvUcCAoMzQZmkHk4Tojan1KgHuXSV7q0n6Cbe1d5e+mHEwHX3N51egY
ASP+bSg7Gd4slFIP4DzNKxBcQcoM5PozCy6tfSeGAoye70bGAutE/pFvelaEvpza
KGL5rYiBeqlnr5U7+gU/Lg9Gp7rLdRaWFTa4qXV0SByQRnjpfug3ZZIqWbsmB2mP
yVXhqyz+k8mCJmntR35M5+EIBPjjujF0UgtJadXahPJpYs6hAwk6DJaNvwbLY2kp
0BKviF/HaqZLB6Ba48bDM3jUXWTl3YtNJqAhVmoo12hdI5dKwIIQOKeF3MqQ0f9a
vQIDAQAB
-----END PUBLIC KEY-----