Files
OrcaSlicer/src/slic3r/plugin/PythonPluginBridge.cpp
T
Ian Chua 5cf5ef881e fix: audit process by executable (#17671)
* fix: audit process execution by name, ignore args

* test: fix stale test expectations

* fix: resolve Windows subprocess audit targets from command line

* fix: preserve quoted Windows paths in process audit grants

* fix: grant shell permissions for os.system commands

* fix: require grants for all possible os.system shells

* fix: clarify process permission scope in prompts

* refactor: simplify audit target handling

* fix: handle ambiguous Windows process commands

* test: fix for ambigous calls on windows
2026-11-20 05:24:22 +08:00

829 lines
42 KiB
C++

#include "PythonPluginBridge.hpp"
#include <algorithm>
#include <boost/log/trivial.hpp>
#include <exception>
#include "libslic3r/LifecycleEvents.hpp"
#include <memory>
#include <mutex>
#include <slic3r/plugin/PluginAuditManager.hpp>
#include "slic3r/plugin/PythonPluginInterface.hpp"
#include <string>
#include <unordered_map>
#include <pybind11/embed.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
#include <utility>
#include "PythonInterpreter.hpp"
#include "PluginFsUtils.hpp"
#include "PluginConfig.hpp"
#include "host/PluginHost.hpp"
#include "PyPluginPackage.hpp"
#include "PyPluginTrampoline.hpp"
#include "pluginTypes/printerAgent/PrinterAgentPluginCapability.hpp"
#include "pluginTypes/pages/PagesPluginCapability.hpp"
#include "pluginTypes/resourceTexture/ResourceTexturePluginCapability.hpp"
#include "pluginTypes/script/ScriptPluginCapability.hpp"
#include "pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp"
#include <pybind11/pytypes.h>
#include <pybind11/gil.h>
#include "slic3r/GUI/I18N.hpp"
#include <nlohmann/json.hpp>
namespace py = pybind11;
namespace Slic3r {
namespace {
// Python plugin discovery is a two-step capture:
// 1) PluginLoader sets an active plugin key and imports the Python module.
// 2) Python decorators/API calls enter these pybind callbacks without receiving the
// C++ PluginDescriptor, so the callbacks use the active key to attach Python classes
// to the plugin currently being loaded.
//
// The pending maps hold Python class objects, not plugin instances. Instances are created
// only after the package class has had a chance to register every capability.
thread_local std::string g_active_plugin_key;
std::mutex g_registry_mutex;
std::unordered_map<std::string, std::vector<py::object>> g_pending_capabilities;
std::unordered_map<std::string, py::object> g_pending_package;
std::unordered_map<std::string, PluginPermissions> g_pending_permissions;
struct PluginInstanceHandle
{
// The C++ plugin interface points into a Python object. Keep both alive through one
// shared control block; CapturedCapability later exposes an aliasing shared_ptr to plugin.
std::shared_ptr<PluginCapabilityInterface> plugin;
py::object keep_alive;
~PluginInstanceHandle()
{
if (keep_alive) {
// Dropping a py::object decrefs the Python object, so acquire a runtime lease and
// the GIL. If shutdown has already won the lease, intentionally abandon the wrapper.
PythonGILState gil;
if (gil) {
keep_alive = py::object();
} else {
(void) keep_alive.release();
}
}
}
};
void discard_pending_capture_without_python(const std::string& plugin_key)
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
auto capabilities = g_pending_capabilities.find(plugin_key);
if (capabilities != g_pending_capabilities.end()) {
for (py::object& capability : capabilities->second)
(void) capability.release();
g_pending_capabilities.erase(capabilities);
}
auto package = g_pending_package.find(plugin_key);
if (package != g_pending_package.end()) {
(void) package->second.release();
g_pending_package.erase(package);
}
g_pending_permissions.erase(plugin_key);
}
} // namespace
PythonPluginBridge& PythonPluginBridge::instance()
{
static PythonPluginBridge bridge;
return bridge;
}
void PythonPluginBridge::begin_plugin_capture(const std::string& plugin_key)
{
PythonGILState gil;
if (!gil) {
BOOST_LOG_TRIVIAL(warning) << "Cannot begin Python plugin capture while the interpreter is shutting down";
return;
}
BOOST_LOG_TRIVIAL(info) << "Beginning Python plugin capture for key " << plugin_key;
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
// Start from a clean slot in case a previous failed load left pending Python classes
// for this same entry path.
g_pending_capabilities.erase(plugin_key);
g_pending_package.erase(plugin_key);
g_pending_permissions.erase(plugin_key);
}
// From now until finalize/cancel, @orca.plugin and register_capability() calls made by
// Python code on this thread are attributed to this plugin.
g_active_plugin_key = plugin_key;
}
std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(const std::string& capture_key,
const std::string& plugin_key,
std::string& error)
{
PythonGILState gil;
if (!gil) {
error = "Python interpreter is shutting down";
return {};
}
BOOST_LOG_TRIVIAL(info) << "Finalizing Python plugin capture for key " << capture_key;
// Phase 1: run the package class's register_capabilities() while the active key is
// still set. That method is expected to call orca.register_capability() once per
// capability class, and register_capability() needs g_active_plugin_key to know which
// pending bucket to append to.
{
auto clear_active_key = [&capture_key]() {
if (g_active_plugin_key == capture_key)
g_active_plugin_key.clear();
};
auto discard_pending_for_key = [&capture_key]() {
std::lock_guard<std::mutex> lock(g_registry_mutex);
g_pending_capabilities.erase(capture_key);
g_pending_package.erase(capture_key);
g_pending_permissions.erase(capture_key);
};
try {
// The @orca.plugin decorator records the package class during module import.
// Move it into a local py::object and remove it from the pending map so the
// registry no longer owns it once finalization starts.
py::object package_cls;
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
auto it = g_pending_package.find(capture_key);
if (it != g_pending_package.end()) {
package_cls = it->second;
g_pending_package.erase(it);
}
}
if (!package_cls) {
error = "Plugin did not register a package class; decorate it with @orca.plugin";
BOOST_LOG_TRIVIAL(error) << error << " for key " << plugin_key;
discard_pending_for_key();
clear_active_key();
return {};
}
// The package instance is only a registration coordinator. It is not returned
// to the rest of the plugin system; only the capability classes it registers
// are kept.
py::object package = package_cls();
package.attr("register_capabilities")();
// Permission declarations are collected while register_capabilities() runs so the
// plugin can describe its needs without touching wx from the Python load worker. Ask
// only after registration returns, before capability instances are materialized.
PluginPermissions requested_permissions;
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
auto it = g_pending_permissions.find(capture_key);
if (it != g_pending_permissions.end()) {
requested_permissions = std::move(it->second);
g_pending_permissions.erase(it);
}
}
const bool has_permission_request =
!requested_permissions.fs_read.empty() || !requested_permissions.fs_readwrite.empty() ||
!requested_permissions.fs_create.empty() || !requested_permissions.fs_delete.empty() ||
!requested_permissions.network_http.empty() || !requested_permissions.network_socket.empty() ||
!requested_permissions.process.empty() || requested_permissions.threading;
if (has_permission_request) {
bool granted = false;
{
py::gil_scoped_release release;
granted = PluginAuditManager::instance().request_permissions(plugin_key, requested_permissions);
}
if (!granted) {
error = _u8L("Plugin permission request denied");
BOOST_LOG_TRIVIAL(warning) << error << " for key " << plugin_key;
discard_pending_for_key();
clear_active_key();
return {};
}
}
} catch (py::error_already_set& err) {
log_python_exception_keep(err);
error = err.what();
BOOST_LOG_TRIVIAL(error) << "Plugin register_capabilities raised Python exception for key " << plugin_key
<< " error=" << error;
discard_pending_for_key();
clear_active_key();
return {};
} catch (const std::exception& ex) {
error = ex.what();
BOOST_LOG_TRIVIAL(error) << "Plugin register_capabilities raised exception for key " << plugin_key
<< " error=" << error;
discard_pending_for_key();
clear_active_key();
return {};
}
}
// Phase 2: move the capability classes that register_capabilities() appended into a
// local vector. From this point the pending registry no longer owns these py::objects.
std::vector<py::object> classes;
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
auto it = g_pending_capabilities.find(capture_key);
if (it != g_pending_capabilities.end()) {
classes = std::move(it->second);
g_pending_capabilities.erase(it);
}
}
// Registration is complete. Later register_capability() calls should fail instead of
// accidentally attaching themselves to this plugin.
if (g_active_plugin_key == capture_key)
g_active_plugin_key.clear();
BOOST_LOG_TRIVIAL(info) << "Collected " << classes.size() << " registered capability class(es) for key " << capture_key;
std::vector<CapturedCapability> capabilities;
capabilities.reserve(classes.size());
// Phase 3: instantiate each registered capability class and convert it to the common
// C++ interface used by the rest of OrcaSlicer.
for (auto& cls : classes) {
try {
py::object instance = cls();
if (!py::isinstance<PluginCapabilityInterface>(instance)) {
error = "Registered capability must inherit from a PluginCapability base";
BOOST_LOG_TRIVIAL(error) << "Python plugin capture failed type check for key " << capture_key
<< " error=" << error;
return {};
}
auto capability_iface = instance.cast<std::shared_ptr<PluginCapabilityInterface>>();
if (!capability_iface) {
error = "Failed to cast Python capability to PluginCapabilityInterface";
BOOST_LOG_TRIVIAL(error) << "Python plugin capture failed cast for key " << capture_key
<< " error=" << error;
return {};
}
// This is a registered capability, not the transient orca.base package.
// get_name() is required on capabilities and is cached for preset lookup.
std::string name = capability_iface->get_name();
// Capability names feed ';'-delimited config/preset serialization and drive
// dispatch, so unlike display names they cannot be silently rewritten — a ';'
// here is a hard error that rejects the whole plugin capture.
if (name.find(';') != std::string::npos) {
error = "Capability name must not contain ';': " + name;
BOOST_LOG_TRIVIAL(error) << "Python plugin capture rejected capability for key " << capture_key
<< " error=" << error;
return {};
}
auto handle = std::make_shared<PluginInstanceHandle>();
handle->keep_alive = instance;
handle->plugin = std::move(capability_iface);
CapturedCapability captured;
// Return a shared_ptr<PluginCapabilityInterface> while keeping PluginInstanceHandle
// as the owner, so the Python instance stays alive as long as the C++ interface does.
captured.instance = std::shared_ptr<PluginCapabilityInterface>(handle, handle->plugin.get());
captured.name = std::move(name);
capabilities.emplace_back(std::move(captured));
} catch (py::error_already_set& err) {
// Direct Python call (cls() / get_name() above), not a trampoline override —
// log the traceback here. GIL is held for the duration of finalize_plugin_capture.
log_python_exception_keep(err);
error = err.what();
BOOST_LOG_TRIVIAL(error) << "Python plugin capture raised Python exception for key " << capture_key
<< " error=" << error;
return {};
} catch (const std::exception& ex) {
error = ex.what();
BOOST_LOG_TRIVIAL(error) << "Python plugin capture raised exception for key " << capture_key
<< " error=" << error;
return {};
}
}
BOOST_LOG_TRIVIAL(info) << "Instantiated " << capabilities.size() << " Python capability instance(s) for key " << plugin_key;
return capabilities;
}
void PythonPluginBridge::cancel_plugin_capture(const std::string& plugin_key)
{
PythonGILState gil;
BOOST_LOG_TRIVIAL(warning) << "Cancelling Python plugin capture for key " << plugin_key;
if (!gil) {
discard_pending_capture_without_python(plugin_key);
if (g_active_plugin_key == plugin_key)
g_active_plugin_key.clear();
return;
}
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
// Import or dependency setup failed before finalization. Drop anything the module
// may already have registered under this key.
g_pending_capabilities.erase(plugin_key);
g_pending_package.erase(plugin_key);
g_pending_permissions.erase(plugin_key);
}
if (g_active_plugin_key == plugin_key)
g_active_plugin_key.clear();
}
void PythonPluginBridge::clear_pending_captures()
{
PythonGILState gil;
if (!gil) {
std::lock_guard<std::mutex> lock(g_registry_mutex);
BOOST_LOG_TRIVIAL(info) << "Clearing " << g_pending_capabilities.size()
<< " pending Python plugin capture(s) without Python interpreter";
// py::object destruction would decref Python objects. If the interpreter is already
// gone, release the wrappers instead and intentionally skip decref.
for (auto& [plugin_key, plugins] : g_pending_capabilities) {
(void) plugin_key;
for (py::object& plugin : plugins)
(void) plugin.release();
}
g_pending_capabilities.clear();
for (auto& [plugin_key, pkg] : g_pending_package) {
(void) plugin_key;
(void) pkg.release();
}
g_pending_package.clear();
g_pending_permissions.clear();
g_active_plugin_key.clear();
return;
}
std::lock_guard<std::mutex> lock(g_registry_mutex);
BOOST_LOG_TRIVIAL(info) << "Clearing " << g_pending_capabilities.size() << " pending Python plugin capture(s)";
g_pending_capabilities.clear();
g_pending_package.clear();
g_pending_permissions.clear();
g_active_plugin_key.clear();
}
void bind_python_api(pybind11::module_& m)
{
m.doc() = "OrcaSlicer plugin API";
py::enum_<PluginCapabilityType>(m, "PluginType", "Available plugin capability groups")
.value("PrinterConnection", PluginCapabilityType::PrinterConnection)
.value("Pages", PluginCapabilityType::Pages)
.value("Analysis", PluginCapabilityType::Analysis)
.value("Importer", PluginCapabilityType::Importer)
.value("Exporter", PluginCapabilityType::Exporter)
.value("Visualization", PluginCapabilityType::Visualization)
.value("Script", PluginCapabilityType::Script)
.value("SlicingPipeline", PluginCapabilityType::SlicingPipeline)
.value("ResourceTexture", PluginCapabilityType::ResourceTexture)
.value("Unknown", PluginCapabilityType::Unknown)
.export_values();
py::enum_<PluginResult>(m, "PluginResult", "Execution summary code")
.value("Success", PluginResult::Success)
.value("Skipped", PluginResult::Skipped)
.value("RecoverableError", PluginResult::RecoverableError)
.value("FatalError", PluginResult::FatalError)
.export_values();
py::enum_<LifecycleEvent>(m, "LifecycleEvent", "Application lifecycle moment passed to on_lifecycle_event")
.value("NewProject", LifecycleEvent::NewProject)
.value("ProjectOpened", LifecycleEvent::ProjectOpened)
.value("ProjectBeforeSave", LifecycleEvent::ProjectBeforeSave)
.value("ProjectAfterSave", LifecycleEvent::ProjectAfterSave)
.value("ProjectClosed", LifecycleEvent::ProjectClosed)
.value("ProjectDirtyChanged", LifecycleEvent::ProjectDirtyChanged)
.value("SliceStarted", LifecycleEvent::SliceStarted)
.value("SliceGeometryFinished", LifecycleEvent::SliceGeometryFinished)
.value("GCodeExportStarted", LifecycleEvent::GCodeExportStarted)
.value("GCodeExportFinished", LifecycleEvent::GCodeExportFinished)
.value("SlicingJobComplete", LifecycleEvent::SlicingJobComplete)
.value("ObjectAdded", LifecycleEvent::ObjectAdded)
.value("ObjectDeleted", LifecycleEvent::ObjectDeleted)
.value("ObjectTransformed", LifecycleEvent::ObjectTransformed)
.value("ObjectChanged", LifecycleEvent::ObjectChanged)
.value("ObjectRenamed", LifecycleEvent::ObjectRenamed)
.value("PlateCreated", LifecycleEvent::PlateCreated)
.value("PlateDeleted", LifecycleEvent::PlateDeleted)
.value("PlateSelected", LifecycleEvent::PlateSelected)
.value("PlateRenamed", LifecycleEvent::PlateRenamed)
.value("PresetSelected", LifecycleEvent::PresetSelected)
.value("PresetSaved", LifecycleEvent::PresetSaved)
.value("PrintStateChanged", LifecycleEvent::PrintStateChanged)
.value("DeviceOnline", LifecycleEvent::DeviceOnline)
.value("DeviceOffline", LifecycleEvent::DeviceOffline)
.value("DeviceDiscovered", LifecycleEvent::DeviceDiscovered)
.value("DeviceSelected", LifecycleEvent::DeviceSelected)
.value("UploadStarted", LifecycleEvent::UploadStarted)
.value("UploadFinished", LifecycleEvent::UploadFinished)
.value("PrintJobStarted", LifecycleEvent::PrintJobStarted)
.value("PrintJobFinished", LifecycleEvent::PrintJobFinished)
.value("SendJobStarted", LifecycleEvent::SendJobStarted)
.value("SendJobFinished", LifecycleEvent::SendJobFinished)
.export_values();
py::enum_<LifecycleEvtCode>(m, "LifecycleEvtCode", "Outcome code accompanying a LifecycleEventContext")
.value("Ok", LifecycleEvtCode::Ok)
.value("Error", LifecycleEvtCode::Error)
.value("Warn", LifecycleEvtCode::Warn)
.export_values();
py::class_<LifecycleEventContext>(m, "LifecycleEventContext", "Payload accompanying a LifecycleEvent")
.def(py::init<>())
.def_readonly("name", &LifecycleEventContext::name)
.def_readonly("code", &LifecycleEventContext::code)
.def_readonly("msg", &LifecycleEventContext::msg)
.def_readonly("id", &LifecycleEventContext::id)
.def_readonly("previous_name", &LifecycleEventContext::previous_name)
.def_readonly("device_id", &LifecycleEventContext::device_id)
.def_readonly("job_id", &LifecycleEventContext::job_id)
.def_readonly("source", &LifecycleEventContext::source)
.def_readonly("index", &LifecycleEventContext::index)
.def_readonly("dirty", &LifecycleEventContext::dirty);
py::class_<PluginContext>(m, "PluginContext", "Context shared with plugin entry points")
.def(py::init<>())
.def_readwrite("orca_version", &PluginContext::orca_version);
py::class_<ExecutionResult>(m, "ExecutionResult", "Structured execution outcome")
.def(py::init<>())
.def(py::init<PluginResult, std::string, std::string>())
.def_readwrite("status", &ExecutionResult::status)
.def_readwrite("message", &ExecutionResult::message)
.def_readwrite("data", &ExecutionResult::data)
.def_static("success", &ExecutionResult::success, py::arg("message") = std::string(), py::arg("data") = std::string())
.def_static("skipped", &ExecutionResult::skipped, py::arg("message") = std::string())
.def_static("failure", &ExecutionResult::failure, py::arg("status"), py::arg("message"), py::arg("data") = std::string());
// Config lives at the capability level, not as a global orca.* function: the host reads the
// owning (plugin_key, capability) straight off the instance the call arrived on, so a
// capability can only ever address its own config and never has to name itself.
// Registered on the base, so every capability type (script/gcode/printer-agent) inherits it.
py::class_<PluginCapabilityInterface, PyPluginInterfaceTrampoline, std::shared_ptr<PluginCapabilityInterface>>(m, "PythonPluginBase")
.def(py::init<>())
.def("get_name", &PluginCapabilityInterface::get_name)
.def("get_type", &PluginCapabilityInterface::get_type)
.def("on_load", &PluginCapabilityInterface::on_load)
.def("on_unload", &PluginCapabilityInterface::on_unload)
.def("on_lifecycle_event", &PluginCapabilityInterface::on_lifecycle_event,
"Override to react to an application lifecycle moment (LifecycleEvent) and its\n"
"LifecycleEventContext payload. Available on every capability type.")
.def("has_config_ui", &PluginCapabilityInterface::has_config_ui,
"Override to return True to replace the host's default JSON editor with your own HTML\n"
"UI, returned by get_config_ui(). Every capability is configurable and appears in the\n"
"Plugins dialog's Config tab regardless; this only chooses how its config is edited.")
.def("get_config_ui", &PluginCapabilityInterface::get_config_ui,
"Override to return the custom configuration UI as an HTML string. Only called when\n"
"has_config_ui() is True; an empty result falls back to the default JSON editor.\n"
"Inside the page, use window.orca.getConfig()/saveConfig() to reach this same config.")
.def(
"get_default_config",
[](const PluginCapabilityInterface& self) {
nlohmann::json config = self.get_default_config();
return config.dump();
},
"Override to return the config that the Config tab's \"Restore defaults\" action writes\n"
"back, as a dict. Optional: without it the action stores an empty config, which already\n"
"restores the defaults of a capability that keeps its stored config sparse and applies\n"
"its own defaults on read. Override it to write an explicit starting config instead.\n"
"Calling it returns that config as a JSON string.")
.def(
"get_config",
[](const PluginCapabilityInterface& self) {
nlohmann::json config = capability_get_config(self);
return config.dump();
},
"Return this capability's stored config as a JSON string — json.loads() it to use.\n"
"\"{}\" if it has never been saved, so the parsed result is always indexable.")
.def(
"get_config_version", [](const PluginCapabilityInterface& self) { return capability_get_config_version(self); },
"Return the plugin version that last wrote this capability's config, so a newer\n"
"release can spot a stale config and migrate it. Empty string if never saved.")
.def(
"save_config",
[](const PluginCapabilityInterface& self, const std::string& config_str) {
nlohmann::json config = nlohmann::json::parse(config_str, nullptr, /* allow_exceptions */ false);
if (config.is_discarded()) {
// Refused rather than stored: the caller gets False, and the previously stored
// config is left alone. Logged because False alone does not say why.
BOOST_LOG_TRIVIAL(error) << "save_config: capability '" << self.get_name() << "' passed a config that is not valid JSON";
return false;
}
return capability_save_config(self, config);
},
py::arg("config"),
"Persist this capability's config, given as a JSON string (e.g. json.dumps(cfg)).\n"
"The plugin key, capability name and version are supplied by the host. Returns False if\n"
"the string is not valid JSON, or if the config file could not be written.");
// Expose the package marker base as orca.base. @orca.plugin later verifies that the
// decorated class derives from this exact pybind-registered C++ type.
py::class_<PyPluginPackage, PyPluginPackageTrampoline>(m, "base")
.def(py::init<>())
.def("register_capabilities", &PyPluginPackage::register_capabilities);
BOOST_LOG_TRIVIAL(debug) << "Registering embedded Python plugin type bindings";
// Make sure you register your bindings here
PrinterAgentPluginCapability::RegisterBindings(m);
PagesPluginCapability::RegisterBindings(m);
ScriptPluginCapability::RegisterBindings(m);
SlicingPipelinePluginCapability::RegisterBindings(m);
ResourceTexturePluginCapability::RegisterBindings(m);
PluginHost::RegisterBindings(m);
BOOST_LOG_TRIVIAL(debug) << "Registered ScriptPluginCapability Python bindings";
m.def(
"register_capability",
[](py::object plugin_cls) {
if (g_active_plugin_key.empty()) {
throw py::value_error("register_capability() called outside plugin discovery context");
}
// Store capability classes only, not instances. Finalization instantiates them
// after the package has registered the full set for this plugin.
py::handle base = py::type::of<PluginCapabilityInterface>();
const int is_subclass = PyObject_IsSubclass(plugin_cls.ptr(), base.ptr());
if (is_subclass != 1) {
if (is_subclass < 0)
PyErr_Clear();
throw py::value_error("Registered class must inherit from a PluginCapability base");
}
std::lock_guard<std::mutex> lock(g_registry_mutex);
g_pending_capabilities[g_active_plugin_key].push_back(std::move(plugin_cls));
BOOST_LOG_TRIVIAL(debug) << "Registered Python plugin capability class for key " << g_active_plugin_key;
},
R"pbdoc(Register a PluginCapability subclass while OrcaSlicer loads your module.)pbdoc");
m.def(
"request_permissions",
[](const std::vector<std::string>& fs_read,
const std::vector<std::string>& fs_readwrite,
const std::vector<std::string>& network_http,
const std::vector<std::string>& network_socket,
const std::vector<std::string>& process,
bool threading,
const std::vector<std::string>& network,
const std::vector<std::string>& fs_create,
const std::vector<std::string>& fs_delete) {
if (g_active_plugin_key.empty())
throw py::value_error("request_permissions() called outside plugin discovery context");
// Validate and canonicalize everything before touching the pending registry, so a
// partially invalid call cannot leave a half-recorded request behind.
const auto reject_empty = [](const char* name, const std::vector<std::string>& targets) {
for (const std::string& target : targets)
if (target.empty())
throw py::value_error(std::string("request_permissions(") + name +
"=...) does not accept empty values");
};
reject_empty("fs_read", fs_read);
reject_empty("fs_readwrite", fs_readwrite);
reject_empty("fs_create", fs_create);
reject_empty("fs_delete", fs_delete);
reject_empty("network_http", network_http);
reject_empty("network_socket", network_socket);
reject_empty("process", process);
// Create/delete declarations name folders. A trailing "/*" is a tree grant covering
// the folder and its subfolders; a sole "*" is the full-access form. Any other
// wildcard is rejected instead of being stored as a literal folder name or widened
// into a grant. request_permissions() resolves and validates the path itself.
const auto validate_folder_entries = [](const char* name, const std::vector<std::string>& folders) {
const bool full_access = folders.size() == 1 && folders.front() == "*";
for (const std::string& folder : folders) {
if (folder == "*") {
if (!full_access)
throw py::value_error(std::string("request_permissions(") + name +
"=...) accepts \"*\" only on its own");
continue;
}
if (folder.find('*') != std::string::npos &&
!PluginAuditManager::is_create_delete_tree_grant(folder))
throw py::value_error(std::string("request_permissions(") + name +
"=...) accepts \"*\" only as the final /* of a folder tree");
}
};
validate_folder_entries("fs_create", fs_create);
validate_folder_entries("fs_delete", fs_delete);
// A network URL is reduced to scheme://host, so one grant covers every path, query
// and port on that host. It is recorded as an HTTP grant; network_permission_matches
// applies that grant to raw socket events for the same host too.
std::vector<std::string> normalized_network;
normalized_network.reserve(network.size());
for (const std::string& url : network) {
const std::string normalized = PluginAuditManager::normalize_network_url(url);
if (normalized.empty())
throw py::value_error(
"request_permissions(network=...) requires an http:// or https:// URL with a host");
if (std::find(normalized_network.begin(), normalized_network.end(), normalized) ==
normalized_network.end())
normalized_network.push_back(normalized);
}
std::lock_guard<std::mutex> lock(g_registry_mutex);
PluginPermissions& requested = g_pending_permissions[g_active_plugin_key];
const auto add_targets = [](std::vector<std::string>& bucket, const std::vector<std::string>& targets) {
for (const std::string& target : targets)
if (std::find(bucket.begin(), bucket.end(), target) == bucket.end())
bucket.push_back(target);
};
add_targets(requested.fs_read, fs_read);
add_targets(requested.fs_readwrite, fs_readwrite);
add_targets(requested.fs_create, fs_create);
add_targets(requested.fs_delete, fs_delete);
add_targets(requested.network_http, network_http);
add_targets(requested.network_http, normalized_network);
add_targets(requested.network_socket, network_socket);
add_targets(requested.process, process);
if (threading && !requested.threading)
requested.threading = true;
},
py::arg("fs_read") = std::vector<std::string>{},
py::arg("fs_readwrite") = std::vector<std::string>{},
py::arg("network_http") = std::vector<std::string>{},
py::arg("network_socket") = std::vector<std::string>{},
py::arg("process") = std::vector<std::string>{},
py::arg("threading") = false,
py::arg("network") = std::vector<std::string>{},
py::arg("fs_create") = std::vector<std::string>{},
py::arg("fs_delete") = std::vector<std::string>{},
R"pbdoc(Request permissions while OrcaSlicer loads your module.
Each bucket takes the target strings the plugin expects the corresponding audit event to
report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, socket addresses
for network_socket, and executables or command names for process. threading=True requests
permission to start threads. Targets already granted to the plugin are not asked for again.
fs_create and fs_delete take folders rather than files. A literal folder entry grants creating
or deleting entries directly inside that folder, not inside its subfolders. An entry ending in
"/*" is a tree grant: it grants the same for that folder and for every folder below it, at any
depth, for example "/path/to/folder/*". A tree rooted at a filesystem, drive, or network share
root, such as "/*", "C:\\*", or a UNC share root, covers that entire filesystem, drive, or
network share. A relative folder or tree root is
resolved against the working directory when the request is made. Pass "*" on its own for
unrestricted create or delete access; a "*" mixed with other entries is rejected, and a "*"
anywhere other than the final /* of a folder tree is rejected. At runtime, approving a create or
delete prompt stores the parent folder of the approved target as a direct grant, and the prompt
lists that canonical folder; a parent folder whose own name contains "*" is refused rather than
stored. On the main thread the operation then proceeds; a request raised on a worker thread
denies the current operation, so the plugin has to retry it after approval.
A recursive delete (shutil.rmtree) is a subtree operation. A literal folder grant is not
enough, even when it names the target folder or its parent. A saved fs_delete tree grant covers
the entries inside its root; deleting the root folder itself is covered only when the folder
containing that root is also granted. Otherwise the user is asked for one-time consent for the
canonical target subtree before the walk starts. That consent is never saved, covers only that
operation, and a prompt that has to be posted to a worker thread applies to one matching retry
within its short lifetime. Nested deletes inside the approved subtree proceed without another
prompt; denied paths stay blocked. A permission edit, revocation, or reinstall discards any
pending recursive-delete consent, so an old prompt cannot grant access to the reinstalled code.
A filesystem target may end in "/*" to grant a whole directory tree, for example
"/path/to/folder/*". That covers the folder itself and every path beneath it, at any depth.
"*" is the only wildcard and is recognized only as the final path component; a "*" anywhere
else in a target is an ordinary character. Tree grants apply to fs_read, fs_readwrite,
fs_create and fs_delete, and a grant in one bucket never authorizes another direction. For
fs_delete, the tree covers deleting entries inside the folder and below, not deleting the
folder root itself; that removal needs the parent folder granted. Tree
grants are matched on canonical paths, so a symlink below the granted folder does not extend
the grant outside it. Paths the host denies by name or keyword stay denied even when a
wildcard covers them.
`network` also lists http(s) URLs, but each is reduced to its scheme and host, so one grant covers
every path, query and port on that host and also authorizes raw socket events for it. The host
presents one request to the user after register_capabilities() returns and before any capability
instance is created. Denying the request aborts the plugin load.)pbdoc");
m.def("plugin", [](py::object cls) {
if (g_active_plugin_key.empty())
throw py::value_error("@orca.plugin used outside plugin discovery context");
if (!PyType_Check(cls.ptr()))
throw py::value_error("@orca.plugin must decorate a class");
// The decorator is only a marker/capture hook. It records the package class now;
// finalize_plugin_capture() instantiates it later and calls register_capabilities().
py::handle base = py::type::of<PyPluginPackage>();
const int is_subclass = PyObject_IsSubclass(cls.ptr(), base.ptr());
if (is_subclass != 1) {
if (is_subclass < 0)
PyErr_Clear();
throw py::value_error("@orca.plugin must decorate a subclass of orca.base");
}
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
auto& slot = g_pending_package[g_active_plugin_key];
if (slot)
throw py::value_error("multiple @orca.plugin classes registered; exactly one is allowed per plugin");
slot = cls;
}
return cls; // decorator returns the class unchanged
}, R"pbdoc(Mark the single plugin package class (the orca.base subclass) for this file.)pbdoc");
}
void install_python_thread_audit_shim()
{
// Runs with the GIL held from PythonInterpreter::initialize(). CPython's own thread bootstrap
// calls the target with no knowledge of the audit context that created it: the calling
// thread is the only place the plugin key and capability are still available. Capture them
// here, then re-establish the same ScopedPluginAuditContext inside the spawned thread before
// the plugin body runs. The identity lives only in this C++ closure -- no Python-visible
// setter is added.
try {
py::object thread_module = py::module_::import("_thread");
const int installed = PyObject_HasAttrString(thread_module.ptr(), "_orca_thread_audit_shim_installed");
if (installed == 1) {
BOOST_LOG_TRIVIAL(debug) << "[AUDIT] Python thread attribution shim already installed";
return;
}
if (installed < 0)
PyErr_Clear();
py::object original = py::reinterpret_steal<py::object>(
PyObject_GetAttrString(thread_module.ptr(), "start_new_thread"));
if (!original || !PyCallable_Check(original.ptr())) {
PyErr_Clear();
BOOST_LOG_TRIVIAL(error) << "[AUDIT] _thread.start_new_thread is missing or not callable; "
"plugin threads will run without audit attribution";
return;
}
py::object shim = py::cpp_function(
[original](py::object function, py::object args, py::object kwargs) -> py::object {
const std::string plugin_key = PluginAuditManager::instance().current_plugin();
if (plugin_key.empty()) {
// Not called from a plugin: preserve the stock implementation untouched.
return kwargs.is_none() ? original(function, args) : original(function, args, kwargs);
}
const std::string capability = PluginAuditManager::instance().current_capability();
py::object guarded = py::cpp_function(
[function, plugin_key, capability](py::args call_args, py::kwargs call_kwargs) -> py::object {
ScopedPluginAuditContext audit_scope(plugin_key, capability);
PyObject* result = PyObject_Call(function.ptr(), call_args.ptr(), call_kwargs.ptr());
if (result == nullptr)
throw py::error_already_set();
return py::reinterpret_steal<py::object>(result);
});
return kwargs.is_none() ? original(guarded, args) : original(guarded, args, kwargs);
},
py::arg("function"), py::arg("args"), py::arg("kwargs") = py::none());
if (PyObject_SetAttrString(thread_module.ptr(), "start_new_thread", shim.ptr()) < 0) {
PyErr_Clear();
BOOST_LOG_TRIVIAL(error)
<< "[AUDIT] Failed to install Python thread attribution shim on _thread.start_new_thread";
return;
}
if (PyObject_SetAttrString(thread_module.ptr(), "_orca_thread_audit_shim_installed", Py_True) < 0)
PyErr_Clear();
// threading.py caches the function at import time (as `_start_new_thread` in 3.12, and as
// `start_new_thread` in older versions). Patch the cached reference too when the module is
// already loaded; otherwise its Thread.start() would keep calling the unwrapped original.
py::object sys_modules = py::module_::import("sys").attr("modules");
PyObject* threading_module = PyDict_GetItemString(sys_modules.ptr(), "threading");
if (threading_module && threading_module != Py_None) {
const char* cached_names[] = {"_start_new_thread", "start_new_thread"};
for (const char* cached_name : cached_names) {
const int has_cached_name = PyObject_HasAttrString(threading_module, cached_name);
if (has_cached_name < 0) {
PyErr_Clear();
continue;
}
if (has_cached_name != 1)
continue;
if (PyObject_SetAttrString(threading_module, cached_name, shim.ptr()) < 0) {
PyErr_Clear();
BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Failed to update threading." << cached_name
<< " with the Python thread attribution shim";
}
}
}
BOOST_LOG_TRIVIAL(info) << "[AUDIT] Python thread attribution shim installed";
} catch (const std::exception& ex) {
BOOST_LOG_TRIVIAL(error) << "[AUDIT] Failed to install Python thread attribution shim: " << ex.what();
}
}
} // namespace Slic3r
#ifdef ORCA_PYTHON_STUBGEN_MODULE
PYBIND11_MODULE(orca, m) { Slic3r::bind_python_api(m); }
#else
PYBIND11_EMBEDDED_MODULE(orca, m) { Slic3r::bind_python_api(m); }
#endif