Compare commits

..
23 changed files with 1671 additions and 866 deletions

No files matched your search

+1
View File
@@ -123,6 +123,7 @@ option(SLIC3R_ASAN "Enable ASan on Clang and GCC" 0)
# Python stubgen module
option(ORCA_BUILD_PYTHON_STUBGEN_MODULE "Build importable Python module for pybind11-stubgen" ON)
option(ORCA_BUILD_PLUGIN_PERMISSION_PROBE "Build the headless Python plugin permission probe (developer tool)" OFF)
set(ORCA_BUNDLED_UV_EXECUTABLE "" CACHE FILEPATH "Path to a uv executable to bundle for Python package installation. Leave empty to auto-download.")
# Auto-download uv if not provided by the user.
+1
View File
@@ -366,6 +366,7 @@ src/slic3r/Utils/MoonrakerPrinterAgent.cpp
src/slic3r/Utils/BBLNetworkPlugin.cpp
src/slic3r/Utils/OrcaCloudServiceAgent.cpp
src/slic3r/plugin/PluginAuditManager.cpp
src/slic3r/plugin/PluginAuditManagerGui.cpp
src/slic3r/plugin/PluginConfig.cpp
src/slic3r/plugin/PluginResolver.cpp
src/slic3r/plugin/CloudPluginService.cpp
+1 -1
View File
@@ -23,7 +23,7 @@ if %FULL_MODE%==1 (
call :prepareGettextList "%list_file%" "%filtered_list%" "%missing_list%"
if "!has_sources!"=="1" (
if not exist "%generated_i18n%" mkdir "%generated_i18n%"
.\tools\xgettext.exe --keyword=L --keyword=_L --keyword=_u8L --keyword=L_CONTEXT:1,2c --keyword=_L_CONTEXT:1,2c --keyword=_u8L_CONTEXT:1,2c --keyword=_L_PLURAL:1,2 --add-comments=TRN --from-code=UTF-8 --no-location --debug --boost --no-wrap -f "%filtered_list%" -o "%generated_pot%"
.\tools\xgettext.exe --keyword=L --keyword=_L --keyword=_u8L --keyword=PLUGIN_U8L --keyword=L_CONTEXT:1,2c --keyword=_L_CONTEXT:1,2c --keyword=_u8L_CONTEXT:1,2c --keyword=_L_PLURAL:1,2 --add-comments=TRN --from-code=UTF-8 --no-location --debug --boost --no-wrap -f "%filtered_list%" -o "%generated_pot%"
if errorlevel 1 (
set "script_exit_code=1"
) else (
+1 -1
View File
@@ -85,7 +85,7 @@ if $FULL_MODE; then
generated_pot_file="${generated_i18n_dir}/OrcaSlicer.pot"
mkdir -p "$generated_i18n_dir"
xgettext --keyword=L --keyword=_L --keyword=_u8L --keyword=L_CONTEXT:1,2c --keyword=_L_CONTEXT:1,2c --keyword=_u8L_CONTEXT:1,2c --keyword=_L_PLURAL:1,2 --add-comments=TRN --from-code=UTF-8 --no-location --debug --boost --no-wrap -f "$filtered_list" -o "$generated_pot_file"
xgettext --keyword=L --keyword=_L --keyword=_u8L --keyword=PLUGIN_U8L --keyword=L_CONTEXT:1,2c --keyword=_L_CONTEXT:1,2c --keyword=_u8L_CONTEXT:1,2c --keyword=_L_PLURAL:1,2 --add-comments=TRN --from-code=UTF-8 --no-location --debug --boost --no-wrap -f "$filtered_list" -o "$generated_pot_file"
python3 scripts/HintsToPot.py ./resources "$generated_i18n_dir"
if [ -f "$pot_file" ] && files_equal_ignoring_pot_date "$pot_file" "$generated_pot_file"; then
+62
View File
@@ -707,6 +707,10 @@ set(SLIC3R_GUI_SOURCES
plugin/PluginManager.hpp
plugin/PluginAuditManager.cpp
plugin/PluginAuditManager.hpp
plugin/PluginAuditManagerGui.cpp
plugin/PluginAuditManagerInternal.hpp
plugin/PluginModule.cpp
plugin/PluginText.hpp
plugin/PluginResolver.cpp
plugin/PluginResolver.hpp
plugin/pluginTypes/printerAgent/PrinterAgentPluginCapability.hpp
@@ -1092,3 +1096,61 @@ if (ORCA_BUILD_PYTHON_STUBGEN_MODULE)
PREFIX ""
)
endif()
# Headless plugin permission probe. A distinct executable so normal GUI loading and prompt
# behavior stay untouched. It compiles the GUI-free plugin sources directly instead of linking
# libslic3r_gui, so neither the GUI library nor wx is pulled into the probe. The permission
# front end is selected by source composition: PluginAuditManagerGui.cpp for the GUI app and
# probe/PluginAuditManagerHeadless.cpp here.
#
# Residual cost: the probe still links libslic3r (the large core library) for Utils,
# LifecycleEvents, the model/print types used by the GUI-free host bindings and libslic3r's own
# transitive dependencies. It does not link libslic3r_gui, wx or the GUI-only host/plugin sources.
# Developer/security-analysis tool, so it is off by default.
if (ORCA_BUILD_PLUGIN_PERMISSION_PROBE)
add_executable(orca-plugin-probe
plugin/PluginPermissionProbe.cpp
plugin/PluginProbeCollector.hpp
plugin/probe/NanoSvgImplementation.cpp
plugin/PluginAuditManager.cpp
plugin/PluginAuditManagerInternal.hpp
plugin/PluginModule.cpp
plugin/PluginText.hpp
plugin/probe/PluginAuditManagerHeadless.cpp
plugin/PluginFsUtils.cpp
plugin/PluginLoader.cpp
plugin/PythonInterpreter.cpp
plugin/PythonPluginBridge.cpp
plugin/probe/PluginHostProbe.cpp
plugin/probe/PluginProbeConfig.cpp
plugin/host/PluginHostGeometry.cpp
plugin/host/PluginHostMesh.cpp
plugin/host/PluginHostModel.cpp
plugin/host/PluginHostSlicing.cpp
plugin/pluginTypes/printerAgent/PrinterAgentPluginCapability.cpp
plugin/pluginTypes/pages/PagesPluginCapability.cpp
plugin/pluginTypes/resourceTexture/ResourceTexturePluginCapability.cpp
plugin/pluginTypes/script/ScriptPluginCapability.cpp
plugin/pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.cpp
)
target_compile_definitions(orca-plugin-probe PRIVATE ORCA_PLUGIN_PROBE_BUILD)
target_include_directories(orca-plugin-probe PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_SOURCE_DIR}/src
Utils
)
target_link_libraries(orca-plugin-probe PRIVATE
libslic3r
nanosvg
pybind11::embed
)
set_target_properties(orca-plugin-probe PROPERTIES
OUTPUT_NAME orca-plugin-probe
FOLDER "tools"
)
endif()
+134 -597
View File
@@ -1,42 +1,27 @@
#include "PluginAuditManager.hpp"
#include "PluginAuditManagerInternal.hpp"
#include "../Utils/OrcaCloudServiceAgent.hpp"
#include "libslic3r/Utils.hpp"
#include "libslic3r/libslic3r.h" // GCODEVIEWER_APP_KEY, and SLIC3R_APP_KEY via libslic3r_version.h
#include "libslic3r_version.h"
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/log/trivial.hpp>
#include <boost/system/error_code.hpp>
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdlib>
#include <future>
#include <mutex>
#include <memory>
#include <slic3r/GUI/BindDialog.hpp>
#include <slic3r/GUI/GUI_App.hpp>
#include <slic3r/plugin/PluginFsUtils.hpp>
#include <slic3r/plugin/PluginManager.hpp>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <wx/app.h>
#include <wx/event.h>
#include <wx/msgdlg.h>
#include <wx/string.h>
#include <wx/thread.h>
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/plugin/PluginDescriptor.hpp"
#include <Python.h>
namespace Slic3r {
@@ -164,182 +149,10 @@ static bool is_fs_category(AuditEventCategory category)
}
}
// HTTP and raw-socket events are governed by the same network permission: a declared host may be
// reached through either layer, and the layers nest for one plugin action (urllib -> http.client
// -> socket).
static bool is_network_category(AuditEventCategory category)
{
return category == AuditEventCategory::Http || category == AuditEventCategory::Socket;
}
// ---------------------------------------------------------------------------
// Network permission identity
// ---------------------------------------------------------------------------
static std::string ascii_lower(std::string value)
{
boost::algorithm::to_lower(value);
return value;
}
static std::string trim_ascii_space(std::string value)
{
boost::algorithm::trim(value);
return value;
}
// Canonical storage keeps IPv6 literals bracketed (https://[::1]), while a socket address
// exposes the bare literal (::1). Compare them without the brackets.
static std::string without_ipv6_brackets(std::string host)
{
if (host.size() >= 2 && host.front() == '[' && host.back() == ']')
host = host.substr(1, host.size() - 2);
return host;
}
// Returns the host part of a URL authority, dropping userinfo and port. IPv6 literals keep their
// brackets so that a URL and a bare address compare consistently.
static std::string host_from_authority(std::string authority)
{
const size_t at = authority.rfind('@');
if (at != std::string::npos)
authority.erase(0, at + 1);
if (authority.empty())
return {};
if (authority.front() == '[') {
const size_t close = authority.find(']');
if (close == std::string::npos)
return {};
authority.erase(close + 1);
return ascii_lower(authority);
}
const size_t colon = authority.find(':');
if (colon != std::string::npos)
authority.erase(colon);
if (authority.find_first_of(" \t\r\n/?#@") != std::string::npos)
return {};
return ascii_lower(authority);
}
// Extracts a host from a target that is not a URL: "host", "host:443", "[::1]:443", "('host',
// 443)" (the form older releases persisted for socket address events), or "'host'".
static std::string network_host_from_target(const std::string& target)
{
std::string value = trim_ascii_space(target);
if (value.empty())
return {};
if (value.front() == '(') {
// Legacy persisted address tuple: ("host", 443) or ("host", 443, 0, 0).
const size_t quote = value.find_first_of("'\"");
if (quote != std::string::npos) {
const char delimiter = value[quote];
const size_t end = value.find(delimiter, quote + 1);
if (end == std::string::npos)
return {};
value = value.substr(quote + 1, end - quote - 1);
} else {
value = value.substr(1);
const size_t comma = value.find(',');
if (comma != std::string::npos)
value.erase(comma);
}
} else if (value.front() == '[') {
const size_t close = value.find(']');
if (close == std::string::npos)
return {};
value.erase(close + 1);
} else {
// Strip a ":port" suffix, but leave a bare IPv6 literal ("::1") intact.
const size_t colon = value.find(':');
if (colon != std::string::npos && value.find(':', colon + 1) == std::string::npos)
value.erase(colon);
}
value = trim_ascii_space(value);
if (value.empty() || value.find_first_of(" \t\r\n/?#@") != std::string::npos)
return {};
return ascii_lower(value);
}
std::string PluginAuditManager::normalize_network_url(const std::string& url)
{
const size_t scheme_end = url.find("://");
if (scheme_end == std::string::npos || scheme_end == 0)
return {};
const std::string scheme = ascii_lower(url.substr(0, scheme_end));
if (scheme != "http" && scheme != "https")
return {};
const size_t authority_start = scheme_end + 3;
const size_t authority_end = url.find_first_of("/?#", authority_start);
const std::string authority = url.substr(authority_start, authority_end == std::string::npos
? std::string::npos
: authority_end - authority_start);
const std::string host = host_from_authority(authority);
if (host.empty())
return {};
return scheme + "://" + host;
}
bool PluginAuditManager::network_permission_matches(const std::vector<std::string>& granted,
const std::string& target)
{
if (target.empty())
return false;
const bool target_is_url = target.find("://") != std::string::npos;
const std::string target_url = normalize_network_url(target);
if (target_is_url && target_url.empty()) {
// A non-http(s) URL has no network identity we can generalize; only an exact grant
// recorded by an earlier approval stays valid, so an unrelated scheme never matches.
return std::find(granted.begin(), granted.end(), target) != granted.end();
}
const std::string target_host =
target_is_url ? std::string{} : without_ipv6_brackets(network_host_from_target(target));
if (!target_is_url && target_host.empty())
return false;
for (const std::string& entry : granted) {
// Preserve an exact grant recorded by an older release, e.g. a full URL with a query.
if (entry == target)
return true;
const std::string entry_url = normalize_network_url(entry);
if (target_is_url) {
// Canonical scheme://host grants are host-wide. Older grants that persisted a full
// URL remain scoped to that exact URL, preserving the operation-root URL check.
if (!entry_url.empty() && entry_url == entry && entry_url == target_url)
return true;
continue;
}
if (!entry_url.empty()) {
// Bare hosts carry no scheme: match the host part of a scheme://host grant.
const std::string entry_host = entry_url.substr(entry_url.find("://") + 3);
if (without_ipv6_brackets(entry_host) == target_host)
return true;
} else if (without_ipv6_brackets(network_host_from_target(entry)) == target_host) {
// Legacy persisted address tuples, e.g. "('host', 443)".
return true;
}
}
return false;
}
namespace plugin_audit {
// The category's name in a saved event grant, e.g. "FsRead" in "FsRead:open".
static const char* category_name(AuditEventCategory category)
const char* category_name(AuditEventCategory category)
{
switch (category) {
case AuditEventCategory::FsRead: return "FsRead";
@@ -356,6 +169,29 @@ static const char* category_name(AuditEventCategory category)
return "None";
}
int report_denied(PluginAuditManager& mgr,
const std::string& event_name,
const AuditDecision& decision,
const std::string& target)
{
AuditViolation violation;
violation.plugin_key = mgr.current_plugin();
violation.event_name = event_name;
violation.reason = decision.reason;
mgr.report_violation(violation);
std::string message = "Plugin attempted audited operation \"" + event_name + "\" without permission";
if (!decision.reason.empty())
message += ": " + decision.reason;
if (!target.empty())
message += ": " + target;
PyErr_SetString(PyExc_PermissionError, message.c_str());
return -1;
}
} // namespace plugin_audit
// ---------------------------------------------------------------------------
// Path safety
// ---------------------------------------------------------------------------
@@ -424,6 +260,7 @@ bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boos
thread_local std::string PluginAuditManager::m_current_plugin_key = "";
thread_local std::string PluginAuditManager::m_current_capability_name = "";
thread_local std::string PluginAuditManager::m_current_audit_phase = "";
thread_local std::vector<AllowedRoot> PluginAuditManager::m_scoped_allowed_roots;
thread_local std::vector<PyObject*> PluginAuditManager::m_root_frames;
thread_local int PluginAuditManager::m_releasing_frames = 0;
@@ -493,6 +330,76 @@ std::string PluginAuditManager::current_capability() const { return m_current_ca
void PluginAuditManager::clear_current_capability() { m_current_capability_name.clear(); }
void PluginAuditManager::set_current_audit_phase(const std::string& phase) { m_current_audit_phase = phase; }
const std::string& PluginAuditManager::current_audit_phase() const { return m_current_audit_phase; }
void PluginAuditManager::clear_current_audit_phase() { m_current_audit_phase.clear(); }
void PluginAuditManager::set_observation_observer(AuditObserver observer)
{
std::lock_guard<std::mutex> lock(m_observer_mutex);
m_observation_observer = std::move(observer);
}
void PluginAuditManager::clear_observation_observer()
{
std::lock_guard<std::mutex> lock(m_observer_mutex);
m_observation_observer = nullptr;
}
bool PluginAuditManager::observation_mode() const
{
std::lock_guard<std::mutex> lock(m_observer_mutex);
return static_cast<bool>(m_observation_observer);
}
// The audit hook holds the GIL here. Copy the observer out before invoking it so a callback that
// reads the manager cannot deadlock on m_observer_mutex.
bool PluginAuditManager::record_observation(const std::string& event_name,
const std::string& category,
const std::vector<std::string>& targets)
{
AuditObserver observer;
{
std::lock_guard<std::mutex> lock(m_observer_mutex);
observer = m_observation_observer;
}
if (!observer)
return false;
// The observer is called from a CPython C callback; a C++ exception must not unwind through
// the audit hook. The probe's collector only allocates, so a throw here is a lost observation,
// not a reason to abort the audited operation.
try {
AuditObservation observation;
observation.plugin_key = m_current_plugin_key;
observation.capability = m_current_capability_name;
observation.phase = m_current_audit_phase;
observation.event_name = event_name;
observation.category = category;
observation.targets = targets;
// Probe mode never denies: the hook returns 0 after recording. A later failure of the
// surrounding Python operation is reported by the probe's callback/load result, not here.
observation.continued = true;
observer(observation);
} catch (...) {
}
return true;
}
ScopedPluginAuditPhase::ScopedPluginAuditPhase(std::string phase)
: m_phase(std::move(phase))
, m_previous_phase(PluginAuditManager::instance().current_audit_phase())
{
PluginAuditManager::instance().set_current_audit_phase(m_phase);
}
ScopedPluginAuditPhase::~ScopedPluginAuditPhase()
{
PluginAuditManager::instance().set_current_audit_phase(m_previous_phase);
}
void PluginAuditManager::add_global_allowed_root(const boost::filesystem::path& root, bool allow_write)
{
if (root.empty())
@@ -530,16 +437,18 @@ void PluginAuditManager::add_denied_filename(const std::string& filename)
std::vector<std::string> PluginAuditManager::default_denied_filenames()
{
// AppConfig::config_path() picks .conf vs .ini on the USE_JSON_CONFIG ifdef and the app key
// on its mode, and is a non-static member we cannot call without an instance. Denying all
// on its mode, and is a non-static member we cannot call without an instance. Denying all
// four names is cheaper and more robust than replicating that; the two unused names cost one
// string comparison each. Single-sourced here so install_hook() and the tests seed from the
// same list and cannot drift apart.
// string comparison each. Keep the plugin install-state sidecar here too: it controls which
// packages load on startup and must remain host-managed. Single-sourced so install_hook() and
// the tests seed from the same list and cannot drift apart.
return {
SLIC3R_APP_KEY ".conf",
GCODEVIEWER_APP_KEY ".conf",
SLIC3R_APP_KEY ".ini",
GCODEVIEWER_APP_KEY ".ini",
secret_constants::USER_SECRET_FILENAME,
".install_state.json",
};
}
@@ -705,132 +614,20 @@ AuditDecision PluginAuditManager::check_open(const std::string& path_str, const
return check_path_access(boost::filesystem::path(path_str), is_write);
}
namespace {
// Builds and shows the modal confirmation. Must run on the GUI thread.
bool show_permission_dialog(const wxString& message, const wxString& title)
{
wxMessageDialog dialog(nullptr, message, title, wxYES_NO | wxICON_WARNING);
return dialog.ShowModal() == wxID_YES;
}
// Shows a permission prompt on the GUI thread and waits for the answer. The caller may be the
// plugin-load worker, so off the main thread the dialog is marshaled with CallAfter.
bool ask_permission(const wxString& message)
{
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
return false;
if (wxIsMainThread())
return show_permission_dialog(message, _L("Plugin permissions"));
auto result = std::make_shared<std::promise<bool>>();
auto future = result->get_future();
GUI::wxGetApp().CallAfter([result, message]() {
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) {
result->set_value(false);
return;
}
result->set_value(show_permission_dialog(message, _L("Plugin permissions")));
});
return future.get();
}
} // namespace
bool PluginAuditManager::request_filesystem_read_permissions(const std::string& plugin_key,
const std::vector<std::string>& paths)
{
if (plugin_key.empty() || paths.empty())
return true;
PluginDescriptor descriptor;
if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty())
return false;
PluginInstallState state;
read_install_state(boost::filesystem::path(descriptor.plugin_root), state);
std::vector<std::string> missing;
for (const std::string& path : paths) {
if (std::find(state.permissions.fs_read.begin(), state.permissions.fs_read.end(), path) == state.permissions.fs_read.end())
missing.push_back(path);
}
if (missing.empty())
// Probe mode records the declaration and proceeds. It must not consult the install state,
// open the permission dialog, or persist a grant.
if (observation_mode()) {
record_observation("orca.request_permissions", "FsRead", paths);
return true;
wxString requested_paths;
for (const std::string& path : missing)
requested_paths += wxString::FromUTF8(path.c_str()) + "\n";
if (!ask_permission(wxString::Format(_L("Plugin \"%s\" requests filesystem read access to:\n%s"),
wxString::FromUTF8(descriptor.name.c_str()), requested_paths)))
return false;
seed_install_metadata(state, descriptor);
state.permissions.fs_read.insert(state.permissions.fs_read.end(), missing.begin(), missing.end());
return write_install_state(boost::filesystem::path(descriptor.plugin_root), state);
}
bool PluginAuditManager::request_network_permissions(const std::string& plugin_key,
const std::vector<std::string>& urls)
{
if (plugin_key.empty() || urls.empty())
return true;
PluginDescriptor descriptor;
if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty())
return false;
// Reduce every request to scheme://host before comparing or persisting it, so a URL with a
// path or query cannot create a second grant for the same host.
std::vector<std::string> requested;
for (const std::string& url : urls) {
const std::string normalized = normalize_network_url(url);
if (normalized.empty()) {
BOOST_LOG_TRIVIAL(warning) << "[AUDIT] Invalid network permission request for plugin " << plugin_key << ": " << url;
return false;
}
if (std::find(requested.begin(), requested.end(), normalized) == requested.end())
requested.push_back(normalized);
}
PluginInstallState state;
read_install_state(boost::filesystem::path(descriptor.plugin_root), state);
std::vector<std::string> missing;
for (const std::string& entry : requested) {
if (!network_permission_matches(state.permissions.network_http, entry) &&
!network_permission_matches(state.permissions.network_socket, entry))
missing.push_back(entry);
}
if (missing.empty())
return true;
wxString requested_hosts;
for (const std::string& entry : missing)
requested_hosts += wxString::FromUTF8(entry.c_str()) + "\n";
if (!ask_permission(wxString::Format(_L("Plugin \"%s\" requests network access to:\n%s"),
wxString::FromUTF8(descriptor.name.c_str()), requested_hosts)))
return false;
seed_install_metadata(state, descriptor);
// A declared host is reachable through both HTTP and raw socket events. Recording the grant in
// both existing lists keeps the sidecar self-describing and means either event layer matches
// it without relying on the other list.
for (const std::string& entry : missing) {
if (std::find(state.permissions.network_http.begin(), state.permissions.network_http.end(), entry) ==
state.permissions.network_http.end())
state.permissions.network_http.push_back(entry);
if (std::find(state.permissions.network_socket.begin(), state.permissions.network_socket.end(), entry) ==
state.permissions.network_socket.end())
state.permissions.network_socket.push_back(entry);
}
return write_install_state(boost::filesystem::path(descriptor.plugin_root), state);
return plugin_audit::request_filesystem_read_permissions(plugin_key, paths);
}
void PluginAuditManager::report_violation(const AuditViolation& violation)
@@ -875,39 +672,6 @@ PyObject* tuple_item(PyObject* args, Py_ssize_t index)
return PyTuple_GET_ITEM(args, index);
}
std::string python_unicode(PyObject* object)
{
if (!object || !PyUnicode_Check(object))
return {};
const char* text = PyUnicode_AsUTF8(object);
if (!text) {
PyErr_Clear();
return {};
}
return text;
}
// Converts a str/bytes leaf to text, clearing a failed conversion. Returns false when `object` is
// neither str nor bytes, so callers can apply their own fallback.
bool python_text(PyObject* object, std::string& out)
{
if (PyUnicode_Check(object)) {
out = python_unicode(object);
return true;
}
if (PyBytes_Check(object)) {
const char* value = PyBytes_AsString(object);
if (!value) {
PyErr_Clear();
out.clear();
return true;
}
out = value;
return true;
}
return false;
}
std::string python_path(PyObject* object)
{
if (!object)
@@ -919,12 +683,26 @@ std::string python_path(PyObject* object)
return {};
}
std::string result;
python_text(path_object, result);
const char* path = PyUnicode_Check(path_object) ? PyUnicode_AsUTF8(path_object) : PyBytes_AsString(path_object);
std::string result = path ? path : "";
Py_DECREF(path_object);
if (!path)
PyErr_Clear();
return result;
}
std::string python_unicode(PyObject* object)
{
if (!object || !PyUnicode_Check(object))
return {};
const char* text = PyUnicode_AsUTF8(object);
if (!text) {
PyErr_Clear();
return {};
}
return text;
}
std::string python_str(PyObject* object)
{
if (!object)
@@ -1111,247 +889,18 @@ std::vector<std::string> audit_targets(const std::string& event_name, AuditEvent
return targets;
}
// The saved list that grants an event: its category's target list, or the event-grant list for
// an event with no target. Kept apart, so that no grant doubles as a target of the same name (an
// os.fork grant is not an os.exec of a command named "os.fork").
std::vector<std::string>* permission_list_for(AuditEventCategory category, bool by_event, PluginPermissions& permissions)
{
if (by_event)
return &permissions.events;
switch (category) {
case AuditEventCategory::FsRead: return &permissions.fs_read;
case AuditEventCategory::FsReadWrite: return &permissions.fs_readwrite;
case AuditEventCategory::Http: return &permissions.network_http;
case AuditEventCategory::Socket: return &permissions.network_socket;
case AuditEventCategory::ProcessCreate: return &permissions.process;
case AuditEventCategory::Threading: return &permissions.threading;
case AuditEventCategory::ProcessReplace: return &permissions.process;
default: return nullptr;
}
}
// An event with no target is granted by its effective category and name, e.g. "FsRead:open"
// for a read of a file descriptor, which does not grant a write of one ("FsReadWrite:open").
std::string event_grant_key(AuditEventCategory category, const std::string& event_name)
{
return std::string(category_name(category)) + ":" + event_name;
}
bool has_permission(const std::vector<std::string>& granted, const std::string& target)
{
return std::find(granted.begin(), granted.end(), target) != granted.end();
}
// A declared or previously approved network grant may live in either network list: an HTTP grant
// covers the sockets the same request opens, and a raw socket grant covers a later HTTP call to
// the same host.
bool has_network_permission(const PluginPermissions& permissions, const std::string& target)
{
return PluginAuditManager::network_permission_matches(permissions.network_http, target) ||
PluginAuditManager::network_permission_matches(permissions.network_socket, target);
}
bool has_any_network_permission(const PluginPermissions& permissions)
{
return !permissions.network_http.empty() || !permissions.network_socket.empty();
}
bool persist_permission(const std::string& plugin_key,
PluginInstallState& state,
std::vector<std::string>& permission_list,
const std::string& target)
{
PluginDescriptor descriptor;
if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty())
return false;
seed_install_metadata(state, descriptor);
if (!has_permission(permission_list, target))
permission_list.push_back(target);
return write_install_state(boost::filesystem::path(descriptor.plugin_root), state);
}
int report_denied(PluginAuditManager& mgr,
const std::string& event_name,
const AuditDecision& decision,
const std::string& target = {})
{
AuditViolation violation;
violation.plugin_key = mgr.current_plugin();
violation.event_name = event_name;
violation.reason = decision.reason;
mgr.report_violation(violation);
std::string message = "Plugin attempted audited operation \"" + event_name + "\" without permission";
if (!decision.reason.empty())
message += ": " + decision.reason;
if (!target.empty())
message += ": " + target;
PyErr_SetString(PyExc_PermissionError, message.c_str());
return -1;
}
wxString audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name,
const wxString& target_list, size_t target_count)
{
if (target_list.IsEmpty())
return wxString::Format(
_L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\".\n\n"
"This operation does not expose a target the audit hook can display."),
plugin_name, event_name);
switch (category) {
case AuditEventCategory::FsRead:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to read the following file:\n%s",
"Plugin \"%s\" is requesting to read the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::FsReadWrite:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to read/write the following file:\n%s",
"Plugin \"%s\" is requesting to read/write the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::FsCreate:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to create the following file:\n%s",
"Plugin \"%s\" is requesting to create the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::FsDelete:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to delete the following file:\n%s",
"Plugin \"%s\" is requesting to delete the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::Http:
return wxString::Format(_L("Plugin \"%s\" is requesting to make an HTTP request to:\n%s"), plugin_name, target_list);
case AuditEventCategory::Socket:
return wxString::Format(_L("Plugin \"%s\" is requesting to open a network connection to:\n%s"), plugin_name, target_list);
case AuditEventCategory::ProcessCreate:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s",
"Plugin \"%s\" is requesting to run the following commands:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::Threading:
return wxString::Format(_L("Plugin \"%s\" is requesting permission to create a thread."), plugin_name);
case AuditEventCategory::ProcessReplace:
return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s"), plugin_name, target_list);
default:
return wxString::Format(_L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\"."), plugin_name, event_name);
}
}
// Builds and shows the modal permission prompt. Must run on the GUI thread.
bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_name, const std::string& event_name,
const std::vector<std::string>& unresolved)
{
wxString target_list;
for (const auto& target : unresolved)
target_list += wxString::FromUTF8(target.c_str()) + "\n";
return show_permission_dialog(
audit_message(category, wxString::FromUTF8(plugin_name.c_str()), wxString::FromUTF8(event_name.c_str()),
target_list, unresolved.size()),
_L("Plugin permission request"));
}
// Records a grant in the plugin's sidecar so it is not asked again. Reads the install state
// freshly because the async prompt outlives the caller's stack copy of it.
void persist_grant(const std::string& plugin_key, AuditEventCategory category, bool by_event, const std::vector<std::string>& keys)
{
PluginInstallState state;
if (!PluginManager::instance().get_install_state(plugin_key, state))
return;
std::vector<std::string>* permission_list = permission_list_for(category, by_event, state.permissions);
if (!permission_list)
return;
for (const auto& key : keys)
persist_permission(plugin_key, state, *permission_list, key);
}
static PluginAuditManager::PermissionPrompt s_permission_prompt_for_testing;
// Asks the user to grant an audited event, returning true when they approve an inline prompt.
// `keys` are what a Yes saves: the unresolved targets, or the event-grant key when the event has
// no target (by_event), which the prompt does not show as a target.
//
// An audited event can fire on a thread the UI thread may itself be blocked waiting on: the
// SlicingPipeline hook runs on the slicing worker thread (see PluginHooks.cpp), and
// BackgroundSlicingProcess::stop()/stop_internal() park the UI thread until that worker stops.
// Blocking the worker on a marshaled modal -- which is safe for the plugin-load worker that
// request_filesystem_read_permissions runs on -- would therefore deadlock the application (the
// invariant PluginHostUi.cpp documents for slicing-hook UI calls). Off the main thread the prompt
// is therefore posted asynchronously and the current event denied (fail closed, like an unanswered
// prompt); the grant is persisted once the user accepts, so a later attempt succeeds without
// re-prompting.
bool request_permission(AuditEventCategory category, const std::string& plugin_key, const std::string& plugin_name,
const std::string& event_name, bool by_event, const std::vector<std::string>& keys)
{
const std::vector<std::string> shown = by_event ? std::vector<std::string>{} : keys;
if (s_permission_prompt_for_testing)
return s_permission_prompt_for_testing(event_name, shown);
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
return false;
if (wxIsMainThread())
return prompt_for_targets(category, plugin_name, event_name, shown);
GUI::wxGetApp().CallAfter([category, plugin_key, plugin_name, event_name, by_event, keys, shown]() {
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
return;
if (prompt_for_targets(category, plugin_name, event_name, shown))
persist_grant(plugin_key, category, by_event, keys);
});
return false;
}
// Decides an event that no allowed root or running operation covers: a saved grant allows it,
// otherwise the user is asked and a Yes is saved.
int decide_audited_event(PluginAuditManager& mgr,
PluginInstallState& state,
const std::string& plugin_key,
const std::string& plugin_name,
const std::string& event_name,
AuditEventCategory category,
const std::vector<std::string>& targets)
{
const bool by_event = targets.empty();
const std::vector<std::string> keys = by_event ? std::vector<std::string>{event_grant_key(category, event_name)} : targets;
std::vector<std::string>* permission_list = permission_list_for(category, by_event, state.permissions);
std::vector<std::string> unresolved = keys;
if (permission_list || is_network_category(category)) {
unresolved.clear();
for (const auto& key : keys)
if (!(permission_list && has_permission(*permission_list, key)) &&
!(is_network_category(category) &&
(by_event ? has_any_network_permission(state.permissions)
: has_network_permission(state.permissions, key))))
unresolved.push_back(key);
if (unresolved.empty())
return 0;
}
// Letting a root frame go runs finalizers inside a scope destructor or another event's hook,
// where no dialog may open: what they do must already be granted.
if (mgr.releasing_frames())
return report_denied(mgr, event_name, {false, "audit permission required"});
if (!request_permission(category, plugin_key, plugin_name, event_name, by_event, unresolved))
return report_denied(mgr, event_name, {false, "audit permission required"});
if (permission_list)
for (const auto& key : unresolved)
persist_permission(plugin_key, state, *permission_list, key);
return 0;
}
// Judges an audited event raised while a plugin context is active.
int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, AuditEventCategory event_type, PyObject* args)
{
const bool fs_category = is_fs_category(event_type);
const std::vector<std::string> targets = audit_targets(event_name, event_type, args);
// Probe mode: report the classified event and let it through. Deliberately before the deny
// registry and allowed-root checks, so the report covers operations that production would
// block as well as those it would allow. No grant is read or written.
if (mgr.record_observation(event_name, plugin_audit::category_name(event_type), targets))
return 0;
// A denied path (secrets, certificates, config files -- see is_denied_path) is an
// unconditional block: checked before the running-operation check below, so no granted
// operation can launder access to one, and before the allowed-root shortcut further down,
@@ -1360,7 +909,7 @@ int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, A
if (fs_category) {
for (const auto& target : targets) {
if (mgr.is_denied_path(boost::filesystem::path(target)))
return report_denied(mgr, event_name, {false, "denied path"}, target);
return plugin_audit::report_denied(mgr, event_name, {false, "denied path"}, target);
}
}
@@ -1385,15 +934,7 @@ int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, A
return 0;
}
PluginInstallState state;
const bool have_install_state = PluginManager::instance().get_install_state(mgr.current_plugin(), state);
if (!have_install_state) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << " Failed to get install state for " << mgr.current_plugin();
}
const std::string plugin_name = state.plugin_name.empty() ? mgr.current_plugin() : state.plugin_name;
const int result = decide_audited_event(mgr, state, mgr.current_plugin(), plugin_name, event_name, event_type, targets);
const int result = plugin_audit::decide_event(mgr, event_name, event_type, targets);
// A granted operation covers its nested events while it runs. A targetless grant names no
// operation, so it covers nothing else.
@@ -1480,11 +1021,6 @@ void PluginAuditManager::release_frames(std::vector<PyObject*>& frames)
PyErr_SetRaisedException(error);
}
void PluginAuditManager::set_permission_prompt_for_testing(PermissionPrompt prompt)
{
PluginAuditDetail::s_permission_prompt_for_testing = std::move(prompt);
}
int PluginAuditManager::audit_hook(const char* event, PyObject* args, void* user_data)
{
auto* mgr = static_cast<PluginAuditManager*>(user_data);
@@ -1540,8 +1076,9 @@ void PluginAuditManager::install_hook()
// "cert" denied-path keyword seeded below.
add_global_allowed_root(resources_dir(), /*allow_write=*/false);
// The user's app config and cloud credentials live directly inside data_dir(), so the
// root just granted would otherwise expose them to any plugin. Deny them by name.
// The user's app config and cloud credentials live directly inside data_dir(), and plugin
// install state lives beneath it, so the root just granted would otherwise expose them to
// plugins. Deny them by name.
//
// Seeded here rather than by each secret's owner because install_hook() runs during lazy
// interpreter init and therefore provably precedes any plugin bytecode, whereas
+56 -21
View File
@@ -24,6 +24,19 @@ struct AuditViolation {
std::string reason;
};
// One classified CPython audit event observed while the probe is in record-only mode. This is
// evidence about the code path that ran, not a grant request: the hook allowed the operation to
// continue and did not consult the permission dialog or the persisted install state.
struct AuditObservation {
std::string plugin_key;
std::string capability;
std::string phase;
std::string event_name;
std::string category;
std::vector<std::string> targets;
bool continued = true;
};
// A filesystem root a plugin may access while an audit context is active. allow_write is
// false for a root that only grants reads (e.g. the bundled, shared resources folder) --
// a write-shaped event never matches such a root, even though a read-shaped one does.
@@ -137,28 +150,29 @@ public:
bool request_filesystem_read_permissions(const std::string& plugin_key,
const std::vector<std::string>& paths);
// Ask the user to grant network access to the given http(s) URLs. Each URL is reduced to its
// scheme and host before prompting and persisting, so one approval covers every path, query
// and port on that host. The grant is written to both network_http and network_socket: the
// same declared host can surface through HTTP events (urllib/http.client) and raw socket
// events. Like request_filesystem_read_permissions, the request may originate on a plugin
// load worker; denial aborts the plugin load without adding a permission.
bool request_network_permissions(const std::string& plugin_key,
const std::vector<std::string>& urls);
// --- probe observation mode (thread-safe, never used by the GUI) ---
// When an observer is installed, every classified event raised by plugin-authored code is
// reported to it and then allowed through (the hook returns 0). The permission dialogs, saved
// grants and .install_state.json are never consulted, so this is not a containment boundary.
// The observer must not touch Python objects: it runs inside the audit hook with the GIL held.
using AuditObserver = std::function<void(const AuditObservation&)>;
void set_observation_observer(AuditObserver observer);
void clear_observation_observer();
bool observation_mode() const;
// Canonical scheme://host form used to store and match network permissions. Returns an empty
// string unless `url` is an absolute http(s) URL with a host. The path, query, fragment,
// userinfo and port are discarded; scheme and host are lowercased.
static std::string normalize_network_url(const std::string& url);
// Stop after classification/target extraction; true means an observer consumed the event.
// Exposed for the probe and its tests, not for production callers.
bool record_observation(const std::string& event_name,
const std::string& category,
const std::vector<std::string>& targets);
// True when a granted scheme://host entry covers `target`. `target` is a URL (urllib.Request),
// a bare host (http.client.connect, socket.getaddrinfo) or an address as exposed by the audit
// event (a hostname, a host:port pair, or a legacy persisted tuple such as "('host', 443)").
// URL targets must match both scheme and host. Canonical scheme://host grants cover all paths;
// older full-URL grants remain exact. A bare host carries no scheme, so it matches the host
// part of any grant; it never matches a different host.
static bool network_permission_matches(const std::vector<std::string>& granted,
const std::string& target);
// --- probe phase attribution (thread_local) ---
// Labels events for the probe's report. Production leaves it empty. A Python thread spawned by
// plugin code inherits no phase, so its events are reported as unattributed rather than being
// guessed at.
void set_current_audit_phase(const std::string& phase);
const std::string& current_audit_phase() const;
void clear_current_audit_phase();
void report_violation(const AuditViolation& violation);
bool audit_denial_pending() const;
@@ -201,6 +215,7 @@ private:
static thread_local std::string m_current_plugin_key;
static thread_local std::string m_current_capability_name;
static thread_local std::string m_current_audit_phase;
static thread_local std::vector<AllowedRoot> m_scoped_allowed_roots;
static thread_local std::vector<PyObject*> m_root_frames; // strong references
static thread_local int m_releasing_frames;
@@ -210,10 +225,14 @@ private:
// mutable: is_denied_filename() is a const query that must lock.
mutable std::mutex m_mutex;
std::vector<AllowedRoot> m_global_allowed_roots;
std::vector<std::string> m_denied_filenames;
std::vector<std::string> m_denied_path_keywords;
// Kept apart from m_mutex: observation_mode() is queried from the audit hook while the hook
// already holds the GIL, and the setter runs before plugin code starts.
mutable std::mutex m_observer_mutex;
AuditObserver m_observation_observer;
};
// RAII guard that sets the current plugin key and capability name, restoring the previous
@@ -244,6 +263,22 @@ private:
std::vector<PyObject*> m_previous_root_frames;
};
// Sets the probe's phase label on the current thread and restores the previous one on scope exit.
// Empty in production, where no phase is ever set.
class ScopedPluginAuditPhase
{
public:
explicit ScopedPluginAuditPhase(std::string phase);
~ScopedPluginAuditPhase();
ScopedPluginAuditPhase(const ScopedPluginAuditPhase&) = delete;
ScopedPluginAuditPhase& operator=(const ScopedPluginAuditPhase&) = delete;
private:
std::string m_phase;
std::string m_previous_phase;
};
} // namespace Slic3r
#endif // slic3r_PluginAuditManager_hpp_
+332
View File
@@ -0,0 +1,332 @@
#include "PluginAuditManagerInternal.hpp"
#include "PluginDescriptor.hpp"
#include "PluginFsUtils.hpp"
#include "PluginManager.hpp"
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/log/trivial.hpp>
#include <algorithm>
#include <cstddef>
#include <future>
#include <memory>
#include <slic3r/plugin/PluginAuditManager.hpp>
#include <string>
#include <utility>
#include <vector>
#include <slic3r/GUI/GUI_App.hpp>
#include <slic3r/GUI/I18N.hpp>
#include <wx/app.h>
#include <wx/msgdlg.h>
#include <wx/string.h>
#include <wx/thread.h>
namespace Slic3r {
namespace {
// The saved list that grants an event: its category's target list, or the event-grant list for
// an event with no target. Kept apart, so that no grant doubles as a target of the same name (an
// os.fork grant is not an os.exec of a command named "os.fork").
std::vector<std::string>* permission_list_for(AuditEventCategory category, bool by_event, PluginPermissions& permissions)
{
if (by_event)
return &permissions.events;
switch (category) {
case AuditEventCategory::FsRead: return &permissions.fs_read;
case AuditEventCategory::FsReadWrite: return &permissions.fs_readwrite;
case AuditEventCategory::Http: return &permissions.network_http;
case AuditEventCategory::Socket: return &permissions.network_socket;
case AuditEventCategory::ProcessCreate: return &permissions.process;
case AuditEventCategory::Threading: return &permissions.threading;
case AuditEventCategory::ProcessReplace: return &permissions.process;
default: return nullptr;
}
}
// An event with no target is granted by its effective category and name, e.g. "FsRead:open"
// for a read of a file descriptor, which does not grant a write of one ("FsReadWrite:open").
std::string event_grant_key(AuditEventCategory category, const std::string& event_name)
{
return std::string(plugin_audit::category_name(category)) + ":" + event_name;
}
bool has_permission(const std::vector<std::string>& granted, const std::string& target)
{
return std::find(granted.begin(), granted.end(), target) != granted.end();
}
bool persist_permission(const std::string& plugin_key,
PluginInstallState& state,
std::vector<std::string>& permission_list,
const std::string& target)
{
PluginDescriptor descriptor;
if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty())
return false;
// A sandbox plugin may not have a sidecar yet. Seed the small amount of install metadata
// needed by the writer so clicking Yes still creates the JSON file.
if (state.plugin_name.empty()) {
state.installed_from = descriptor.is_cloud_plugin() ? "cloud" : "local";
state.installed_version = !descriptor.installed_version.empty() ? descriptor.installed_version : descriptor.version;
state.plugin_name = descriptor.name;
state.cloud_uuid = descriptor.cloud_uuid();
state.enabled = true;
}
if (!has_permission(permission_list, target))
permission_list.push_back(target);
return write_install_state(boost::filesystem::path(descriptor.plugin_root), state);
}
wxString audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name,
const wxString& target_list, size_t target_count)
{
if (target_list.IsEmpty())
return wxString::Format(
_L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\".\n\n"
"This operation does not expose a target the audit hook can display."),
plugin_name, event_name);
switch (category) {
case AuditEventCategory::FsRead:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to read the following file:\n%s",
"Plugin \"%s\" is requesting to read the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::FsReadWrite:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to read/write the following file:\n%s",
"Plugin \"%s\" is requesting to read/write the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::FsCreate:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to create the following file:\n%s",
"Plugin \"%s\" is requesting to create the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::FsDelete:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to delete the following file:\n%s",
"Plugin \"%s\" is requesting to delete the following files:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::Http:
return wxString::Format(_L("Plugin \"%s\" is requesting to make an HTTP request to:\n%s"), plugin_name, target_list);
case AuditEventCategory::Socket:
return wxString::Format(_L("Plugin \"%s\" is requesting to open a network connection to:\n%s"), plugin_name, target_list);
case AuditEventCategory::ProcessCreate:
return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to run the following command:\n%s",
"Plugin \"%s\" is requesting to run the following commands:\n%s", target_count),
plugin_name, target_list);
case AuditEventCategory::Threading:
return wxString::Format(_L("Plugin \"%s\" is requesting permission to create a thread."), plugin_name);
case AuditEventCategory::ProcessReplace:
return wxString::Format(_L("Plugin \"%s\" is requesting to replace the running application with:\n%s"), plugin_name, target_list);
default:
return wxString::Format(_L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\"."), plugin_name, event_name);
}
}
// Builds and shows the modal permission prompt. Must run on the GUI thread.
bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_name, const std::string& event_name,
const std::vector<std::string>& unresolved)
{
wxString target_list;
for (const auto& target : unresolved)
target_list += wxString::FromUTF8(target.c_str()) + "\n";
wxMessageDialog dialog(nullptr,
audit_message(category, wxString::FromUTF8(plugin_name.c_str()),
wxString::FromUTF8(event_name.c_str()), target_list, unresolved.size()),
_L("Plugin permission request"), wxYES_NO | wxICON_WARNING);
return dialog.ShowModal() == wxID_YES;
}
// Records a grant in the plugin's sidecar so it is not asked again. Reads the install state
// freshly because the async prompt outlives the caller's stack copy of it.
void persist_grant(const std::string& plugin_key, AuditEventCategory category, bool by_event, const std::vector<std::string>& keys)
{
PluginInstallState state;
if (!PluginManager::instance().get_install_state(plugin_key, state))
return;
std::vector<std::string>* permission_list = permission_list_for(category, by_event, state.permissions);
if (!permission_list)
return;
for (const auto& key : keys)
persist_permission(plugin_key, state, *permission_list, key);
}
PluginAuditManager::PermissionPrompt s_permission_prompt_for_testing;
// Asks the user to grant an audited event, returning true when they approve an inline prompt.
// `keys` are what a Yes saves: the unresolved targets, or the event-grant key when the event has
// no target (by_event), which the prompt does not show as a target.
//
// An audited event can fire on a thread the UI thread may itself be blocked waiting on: the
// SlicingPipeline hook runs on the slicing worker thread (see PluginHooks.cpp), and
// BackgroundSlicingProcess::stop()/stop_internal() park the UI thread until that worker stops.
// Blocking the worker on a marshaled modal -- which is safe for the plugin-load worker that
// request_filesystem_read_permissions runs on -- would therefore deadlock the application (the
// invariant PluginHostUi.cpp documents for slicing-hook UI calls). Off the main thread the prompt
// is therefore posted asynchronously and the current event denied (fail closed, like an unanswered
// prompt); the grant is persisted once the user accepts, so a later attempt succeeds without
// re-prompting.
bool request_permission(AuditEventCategory category, const std::string& plugin_key, const std::string& plugin_name,
const std::string& event_name, bool by_event, const std::vector<std::string>& keys)
{
const std::vector<std::string> shown = by_event ? std::vector<std::string>{} : keys;
if (s_permission_prompt_for_testing)
return s_permission_prompt_for_testing(event_name, shown);
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
return false;
if (wxIsMainThread())
return prompt_for_targets(category, plugin_name, event_name, shown);
GUI::wxGetApp().CallAfter([category, plugin_key, plugin_name, event_name, by_event, keys, shown]() {
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
return;
if (prompt_for_targets(category, plugin_name, event_name, shown))
persist_grant(plugin_key, category, by_event, keys);
});
return false;
}
// Decides an event that no allowed root or running operation covers: a saved grant allows it,
// otherwise the user is asked and a Yes is saved.
int decide_audited_event(PluginAuditManager& mgr,
PluginInstallState& state,
const std::string& plugin_key,
const std::string& plugin_name,
const std::string& event_name,
AuditEventCategory category,
const std::vector<std::string>& targets)
{
const bool by_event = targets.empty();
const std::vector<std::string> keys = by_event ? std::vector<std::string>{event_grant_key(category, event_name)} : targets;
std::vector<std::string>* permission_list = permission_list_for(category, by_event, state.permissions);
std::vector<std::string> unresolved = keys;
if (permission_list) {
unresolved.clear();
for (const auto& key : keys)
if (!has_permission(*permission_list, key))
unresolved.push_back(key);
if (unresolved.empty())
return 0;
}
// Letting a root frame go runs finalizers inside a scope destructor or another event's hook,
// where no dialog may open: what they do must already be granted.
if (mgr.releasing_frames())
return plugin_audit::report_denied(mgr, event_name, {false, "audit permission required"});
if (!request_permission(category, plugin_key, plugin_name, event_name, by_event, unresolved))
return plugin_audit::report_denied(mgr, event_name, {false, "audit permission required"});
if (permission_list)
for (const auto& key : unresolved)
persist_permission(plugin_key, state, *permission_list, key);
return 0;
}
} // namespace
bool plugin_audit::request_filesystem_read_permissions(const std::string& plugin_key,
const std::vector<std::string>& paths)
{
PluginDescriptor descriptor;
if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty())
return false;
PluginInstallState state;
read_install_state(boost::filesystem::path(descriptor.plugin_root), state);
std::vector<std::string> missing;
for (const std::string& path : paths) {
if (std::find(state.permissions.fs_read.begin(), state.permissions.fs_read.end(), path) == state.permissions.fs_read.end())
missing.push_back(path);
}
if (missing.empty())
return true;
if (wxTheApp == nullptr || GUI::wxGetApp().is_closing())
return false;
auto show_dialog = [&descriptor, &missing]() {
wxString requested_paths;
for (const std::string& path : missing)
requested_paths += wxString::FromUTF8(path.c_str()) + "\n";
wxMessageDialog dialog(
nullptr,
wxString::Format(_L("Plugin \"%s\" requests filesystem read access to:\n%s"),
wxString::FromUTF8(descriptor.name.c_str()), requested_paths),
_L("Plugin permissions"),
wxYES_NO | wxICON_WARNING);
return dialog.ShowModal() == wxID_YES;
};
bool granted = false;
if (wxIsMainThread()) {
granted = show_dialog();
} else {
auto result = std::make_shared<std::promise<bool>>();
auto future = result->get_future();
GUI::wxGetApp().CallAfter([result, descriptor_name = descriptor.name, missing]() {
wxString requested_paths;
for (const std::string& path : missing)
requested_paths += wxString::FromUTF8(path.c_str()) + "\n";
wxMessageDialog dialog(
nullptr,
wxString::Format(_L("Plugin \"%s\" requests filesystem read access to:\n%s"),
wxString::FromUTF8(descriptor_name.c_str()), requested_paths),
_L("Plugin permissions"),
wxYES_NO | wxICON_WARNING);
result->set_value(dialog.ShowModal() == wxID_YES);
});
granted = future.get();
}
if (!granted)
return false;
if (state.plugin_name.empty()) {
state.installed_from = descriptor.is_cloud_plugin() ? "cloud" : "local";
state.installed_version = !descriptor.installed_version.empty() ? descriptor.installed_version : descriptor.version;
state.plugin_name = descriptor.name;
state.cloud_uuid = descriptor.cloud_uuid();
state.enabled = true;
}
state.permissions.fs_read.insert(state.permissions.fs_read.end(), missing.begin(), missing.end());
return write_install_state(boost::filesystem::path(descriptor.plugin_root), state);
}
int plugin_audit::decide_event(PluginAuditManager& mgr,
const std::string& event_name,
AuditEventCategory category,
const std::vector<std::string>& targets)
{
PluginInstallState state;
const bool have_install_state = PluginManager::instance().get_install_state(mgr.current_plugin(), state);
if (!have_install_state) {
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << " Failed to get install state for " << mgr.current_plugin();
}
const std::string plugin_name = state.plugin_name.empty() ? mgr.current_plugin() : state.plugin_name;
return decide_audited_event(mgr, state, mgr.current_plugin(), plugin_name, event_name, category, targets);
}
void PluginAuditManager::set_permission_prompt_for_testing(PermissionPrompt prompt)
{
s_permission_prompt_for_testing = std::move(prompt);
}
} // namespace Slic3r
@@ -0,0 +1,38 @@
#ifndef slic3r_PluginAuditManagerInternal_hpp_
#define slic3r_PluginAuditManagerInternal_hpp_
// Internal seam between the GUI-free audit core and the permission front end. The GUI library
// supplies the dialogs, prompts and .install_state.json persistence; the headless probe supplies
// a fail-closed implementation that never links wx. Production behavior lives in the GUI
// implementation, which is the code that used to be part of PluginAuditManager.cpp.
#include "PluginAuditManager.hpp"
#include <string>
#include <vector>
namespace Slic3r::plugin_audit {
const char* category_name(AuditEventCategory category);
int report_denied(PluginAuditManager& mgr,
const std::string& event_name,
const AuditDecision& decision,
const std::string& target = {});
// Used only when the manager is not in observation mode. The GUI implementation consults the
// install state, prompts and persists; the probe implementation fails closed.
bool request_filesystem_read_permissions(const std::string& plugin_key,
const std::vector<std::string>& paths);
// Decides an event that no allowed root or running operation covered. The GUI implementation
// reads the install state and prompts; the probe implementation fails closed. In observation
// mode the audit hook records and returns before reaching this seam.
int decide_event(PluginAuditManager& mgr,
const std::string& event_name,
AuditEventCategory category,
const std::vector<std::string>& targets);
} // namespace Slic3r::plugin_audit
#endif // slic3r_PluginAuditManagerInternal_hpp_
+31 -44
View File
@@ -14,8 +14,7 @@
#include "PluginAuditManager.hpp"
#include "PythonInterpreter.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/format.hpp"
#include "PluginText.hpp"
#include <exception>
#include <miniz.h>
@@ -92,7 +91,7 @@ bool resolve_allowed_plugin_root(const PluginDescriptor& descriptor,
const fs::path plugin_root = resolve_plugin_root_from_descriptor(descriptor);
if (plugin_root.empty()) {
error = _u8L("Plugin folder could not be determined.");
error = PLUGIN_U8L("Plugin folder could not be determined.");
return false;
}
@@ -103,7 +102,7 @@ bool resolve_allowed_plugin_root(const PluginDescriptor& descriptor,
resolved_root = fs::absolute(plugin_root, ec);
}
if (ec || resolved_root.empty()) {
error = GUI::format(_u8L("Failed to resolve plugin folder: %1%"), plugin_root.string());
error = PLUGIN_FORMAT(PLUGIN_U8L("Failed to resolve plugin folder: %1%"), plugin_root.string());
return false;
}
@@ -123,7 +122,7 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std:
const auto removed_count = fs::remove_all(resolved_root, ec);
if (ec) {
// TRN %1% is a folder path, %2% the system error message.
error = GUI::format(_u8L("Failed to delete plugin folder %1%: %2%"), resolved_root.string(), ec.message());
error = PLUGIN_FORMAT(PLUGIN_U8L("Failed to delete plugin folder %1%: %2%"), resolved_root.string(), ec.message());
return false;
}
@@ -833,29 +832,6 @@ bool read_install_state(const boost::filesystem::path& plugin_dir, PluginInstall
}
}
namespace {
// The single descriptor -> sidecar metadata mapping. Prefer installed_version (fetched at install
// time and preserved across rewrites) over a possibly stale manifest version.
void apply_install_metadata(PluginInstallState& state, const PluginDescriptor& entry)
{
state.installed_from = entry.is_cloud_plugin() ? "cloud" : "local";
state.installed_version = !entry.installed_version.empty() ? entry.installed_version : entry.version;
state.plugin_name = entry.name;
state.cloud_uuid = entry.cloud_uuid();
}
} // namespace
void seed_install_metadata(PluginInstallState& state, const PluginDescriptor& entry)
{
if (!state.plugin_name.empty())
return;
apply_install_metadata(state, entry);
state.enabled = true;
}
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginInstallState& state)
{
namespace fs = boost::filesystem;
@@ -899,9 +875,16 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin
// Loading a plugin updates its lifecycle/capability state, but must retain permissions granted
// during register_capabilities() or by a previous runtime audit prompt.
read_install_state(plugin_dir, state);
apply_install_metadata(state, entry);
state.enabled = enabled;
state.capabilities = capabilities;
state.installed_from = entry.is_cloud_plugin() ? "cloud" : "local";
// Prefer the descriptor's recorded installed_version (the version fetched from the cloud
// at install time, preserved across sidecar re-writes) so a stale manifest/PEP723 header
// never overwrites the source-of-truth version. Fall back to the manifest version for
// first-time/local installs where installed_version is not yet populated.
state.installed_version = !entry.installed_version.empty() ? entry.installed_version : entry.version;
state.plugin_name = entry.name;
state.cloud_uuid = entry.cloud_uuid();
state.enabled = enabled;
state.capabilities = capabilities;
return write_install_state(plugin_dir, state);
}
@@ -912,7 +895,11 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin
// permissions on a fresh install/reinstall. PluginManager writes the real per-capability flags
// while preserving permissions once the package is loaded, via the overload above.
PluginInstallState state;
seed_install_metadata(state, entry);
state.installed_from = entry.is_cloud_plugin() ? "cloud" : "local";
state.installed_version = !entry.installed_version.empty() ? entry.installed_version : entry.version;
state.plugin_name = entry.name;
state.cloud_uuid = entry.cloud_uuid();
state.enabled = true;
return write_install_state(plugin_dir, state);
}
@@ -1211,7 +1198,7 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat
namespace fs = boost::filesystem;
if (!fs::exists(plugin_dir) || !fs::is_directory(plugin_dir)) {
error = GUI::format(_u8L("Plugin directory does not exist: %1%"), plugin_dir.string());
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin directory does not exist: %1%"), plugin_dir.string());
return {};
}
@@ -1228,7 +1215,7 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat
if (ext == ".py") {
if (!py_entry.empty()) {
// TRN %1% and %2% are file names.
error = GUI::format(_u8L("Plugin directory contains multiple .py files: %1% and %2%"),
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin directory contains multiple .py files: %1% and %2%"),
py_entry.filename().string(), it->path().filename().string());
return {};
}
@@ -1236,7 +1223,7 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat
} else if (ext == ".whl") {
if (!whl_entry.empty()) {
// TRN %1% and %2% are file names.
error = GUI::format(_u8L("Plugin directory contains multiple .whl files: %1% and %2%"),
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin directory contains multiple .whl files: %1% and %2%"),
whl_entry.filename().string(), it->path().filename().string());
return {};
}
@@ -1245,7 +1232,7 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat
}
if (!py_entry.empty() && !whl_entry.empty()) {
error = _u8L("Plugin directory contains both .py and .whl entry files");
error = PLUGIN_U8L("Plugin directory contains both .py and .whl entry files");
return {};
}
@@ -1255,7 +1242,7 @@ boost::filesystem::path find_installed_plugin_entry(const boost::filesystem::pat
if (!whl_entry.empty())
return whl_entry;
error = _u8L("Plugin directory does not contain a .py or .whl entry file");
error = PLUGIN_U8L("Plugin directory does not contain a .py or .whl entry file");
return {};
}
@@ -1272,34 +1259,34 @@ std::vector<std::string> collect_resource_texture_files(const std::string& dir,
error.clear();
if (dir.empty()) {
error = _u8L("Resource texture directory is not set");
error = PLUGIN_U8L("Resource texture directory is not set");
return files;
}
if (plugin_root.empty()) {
error = _u8L("Plugin folder could not be determined.");
error = PLUGIN_U8L("Plugin folder could not be determined.");
return files;
}
boost::system::error_code ec;
const fs::path resolved_dir = fs::weakly_canonical(fs::path(dir), ec);
if (ec) {
error = _u8L("Resource texture directory could not be resolved");
error = PLUGIN_U8L("Resource texture directory could not be resolved");
return files;
}
if (!fs::is_directory(resolved_dir, ec) || ec) {
error = _u8L("Resource texture path is not a directory");
error = PLUGIN_U8L("Resource texture path is not a directory");
return files;
}
const fs::path resolved_root = fs::weakly_canonical(fs::path(plugin_root), ec);
if (ec) {
error = _u8L("Plugin folder could not be resolved");
error = PLUGIN_U8L("Plugin folder could not be resolved");
return files;
}
if (!is_inside_allowed_root(resolved_dir, resolved_root)) {
error = _u8L("Resource texture directory is outside the plugin folder");
error = PLUGIN_U8L("Resource texture directory is outside the plugin folder");
return files;
}
@@ -1324,7 +1311,7 @@ std::vector<std::string> collect_resource_texture_files(const std::string& dir,
}
if (ec) {
error = _u8L("Resource texture directory could not be read");
error = PLUGIN_U8L("Resource texture directory could not be read");
return {};
}
-7
View File
@@ -186,19 +186,12 @@ std::vector<std::string> collect_resource_texture_files(const std::string& dir,
// Canonical writer: emits the .install_state.json schema for the given state.
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginInstallState& state);
// Builds a PluginInstallState from the descriptor and delegates to the canonical writer.
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginDescriptor& entry, bool enabled,
const std::vector<std::pair<std::string, bool>>& capabilities);
// Convenience overload: write(dir, entry, /*enabled=*/true, /*capabilities=*/{}).
bool write_install_state(const boost::filesystem::path& plugin_dir, const PluginDescriptor& entry);
// Fill the descriptor-derived install metadata into a sidecar state that does not describe an
// installed plugin yet, and mark it enabled. Leaves permissions and capabilities untouched.
// Single source for the metadata mapping used by the install writer and by the audit prompt path
// that creates a sidecar on demand.
void seed_install_metadata(PluginInstallState& state, const PluginDescriptor& entry);
// Reads install state back into the descriptor; plugin_key is always derived. Returns whether the
// sidecar was present and valid.
bool read_install_state(const boost::filesystem::path& plugin_dir, PluginDescriptor& entry);
+24 -25
View File
@@ -11,8 +11,7 @@
#include "PythonPluginBridge.hpp"
#include "pluginTypes/resourceTexture/ResourceTexturePluginCapability.hpp"
#include "libslic3r/Utils.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/format.hpp"
#include "PluginText.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/case_conv.hpp>
@@ -102,7 +101,7 @@ bool read_local_plugin_package_metadata(const boost::filesystem::path& source_pa
const std::string ext = plugin_package_extension(source_path);
if (ext != ".py" && ext != ".whl") {
error = GUI::format(_u8L("Plugin package must be a .py or .whl file, got: %1%"), ext);
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin package must be a .py or .whl file, got: %1%"), ext);
return false;
}
@@ -179,14 +178,14 @@ bool add_wheel_dependencies_to_sys_path(const PluginDescriptor& descriptor,
std::string extract_error;
if (!extract_zip_to_directory(it->path(), dep_dir, extract_error)) {
// TRN %1% is the dependency file, %2% the error detail.
error = GUI::format(_u8L("Failed to extract plugin .whl dependency %1%: %2%"), it->path().string(), extract_error);
error = PLUGIN_FORMAT(PLUGIN_U8L("Failed to extract plugin .whl dependency %1%: %2%"), it->path().string(), extract_error);
return false;
}
}
std::string syspath_error;
if (!interpreter.add_plugin_sys_path(dep_dir.string(), syspath_error)) {
error = GUI::format(_u8L("Failed to add .whl dependency to sys.path: %1%"), syspath_error);
error = PLUGIN_FORMAT(PLUGIN_U8L("Failed to add .whl dependency to sys.path: %1%"), syspath_error);
return false;
}
plugin_paths.push_back(dep_dir.string());
@@ -248,12 +247,12 @@ bool load(const PluginDescriptor& descriptor,
PythonInterpreter& interpreter = PythonInterpreter::instance();
if (!interpreter.is_initialized()) {
error = GUI::format(_u8L("Python interpreter not initialized: %1%"), interpreter.last_error());
error = PLUGIN_FORMAT(PLUGIN_U8L("Python interpreter not initialized: %1%"), interpreter.last_error());
return false;
}
if (!descriptor.is_metadata_valid()) {
error = GUI::format(_u8L("Plugin manifest is invalid: %1%"), descriptor.plugin_key);
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin manifest is invalid: %1%"), descriptor.plugin_key);
if (descriptor.has_error())
error += " - " + descriptor.normalized_error();
return false;
@@ -274,7 +273,7 @@ bool load(const PluginDescriptor& descriptor,
if (!skip_deps) {
std::string pkg_install_error;
if (!install_packages(descriptor.dependencies, pkg_install_error)) {
error = GUI::format(_u8L("Failed to install plugin dependencies: %1%"), pkg_install_error);
error = PLUGIN_FORMAT(PLUGIN_U8L("Failed to install plugin dependencies: %1%"), pkg_install_error);
return false;
}
}
@@ -293,7 +292,7 @@ bool load(const PluginDescriptor& descriptor,
PyObject* module = import_plugin_module(descriptor, plugin.plugin_sys_paths, plugin.plugin_modules, load_error);
if (module == nullptr) {
bridge.cancel_plugin_capture(descriptor.entry_path);
error = GUI::format(_u8L("Failed to load plugin module: %1%"), load_error);
error = PLUGIN_FORMAT(PLUGIN_U8L("Failed to load plugin module: %1%"), load_error);
return false;
}
@@ -308,13 +307,13 @@ bool load(const PluginDescriptor& descriptor,
auto capabilities_found = bridge.finalize_plugin_capture(descriptor.entry_path, descriptor.plugin_key, bridge_error);
if (!bridge_error.empty()) {
capabilities_found.clear();
error = GUI::format(_u8L("Plugin registration failed: %1%"), bridge_error);
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin registration failed: %1%"), bridge_error);
if (registration_failed != nullptr)
*registration_failed = true;
return false;
}
if (capabilities_found.empty()) {
error = _u8L("Plugin module did not register any capabilities");
error = PLUGIN_U8L("Plugin module did not register any capabilities");
return false;
}
@@ -366,7 +365,7 @@ bool load(const PluginDescriptor& descriptor,
if (!seen_capabilities[type].insert(found.name).second) {
// TRN %1% is the capability name, %2% the capability type (e.g. Script).
materialization_error = GUI::format(_u8L("Plugin declares duplicate capability '%1%' for type %2%"),
materialization_error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin declares duplicate capability '%1%' for type %2%"),
found.name, PluginConfig::capability_type_label(type));
break;
}
@@ -422,9 +421,9 @@ bool load(const PluginDescriptor& descriptor,
capabilities.push_back(std::move(instance));
}
} catch (const std::exception& ex) {
materialization_error = GUI::format(_u8L("Plugin capability materialization failed: %1%"), ex.what());
materialization_error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin capability materialization failed: %1%"), ex.what());
} catch (...) {
materialization_error = _u8L("Plugin capability materialization failed");
materialization_error = PLUGIN_U8L("Plugin capability materialization failed");
}
}
@@ -466,11 +465,11 @@ bool load(const PluginDescriptor& descriptor,
} catch (const std::exception& ex) {
teardown_capabilities(plugin.capabilities, lifecycle_count);
// TRN on_load is the name of the plugin's startup function; keep it untranslated.
error = GUI::format(_u8L("Plugin on_load failed: %1%"), ex.what());
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin on_load failed: %1%"), ex.what());
return false;
} catch (...) {
teardown_capabilities(plugin.capabilities, lifecycle_count);
error = _u8L("Plugin on_load failed");
error = PLUGIN_U8L("Plugin on_load failed");
return false;
}
@@ -651,7 +650,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
bool backup_created = false;
auto fail = [&error](const std::string& message) {
error = GUI::format(_u8L("Plugin installation failed: %1%"), message);
error = PLUGIN_FORMAT(PLUGIN_U8L("Plugin installation failed: %1%"), message);
return false;
};
@@ -659,23 +658,23 @@ bool install_plugin(const boost::filesystem::path& filepath,
const fs::path source_path = canonical_or_absolute(filepath);
if (!fs::exists(source_path, ec) || !fs::is_regular_file(source_path, ec))
return fail(GUI::format(_u8L("Plugin package is not a file: %1%"), filepath.string()));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Plugin package is not a file: %1%"), filepath.string()));
const std::string ext = plugin_package_extension(source_path);
if (ext != ".py" && ext != ".whl")
return fail(GUI::format(_u8L("Plugin package must be a .py or .whl file, got: %1%"), ext));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Plugin package must be a .py or .whl file, got: %1%"), ext));
// The cloud UUID is concatenated into the install path (final_dir = plugin_root / cloud_uuid).
// It comes verbatim from the server's catalog JSON, so reject anything that could escape the
// per-user plugin root (traversal, leading dots, separators) before touching the filesystem.
if (is_cloud_install && !is_valid_plugin_id(cloud_uuid))
return fail(GUI::format(_u8L("Cloud plugin UUID is not a valid identifier: %1%"), cloud_uuid));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Cloud plugin UUID is not a valid identifier: %1%"), cloud_uuid));
const fs::path plugin_root = is_cloud_install && !cloud_user_id.empty() ? fs::path(get_cloud_plugin_dir(cloud_user_id)) :
local_plugin_root();
fs::create_directories(plugin_root, ec);
if (ec)
// TRN %1% is a folder path, %2% the system error message.
return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), plugin_root.string(), ec.message()));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Failed to create plugin directory %1%: %2%"), plugin_root.string(), ec.message()));
std::string meta_error;
if (is_cloud_install) {
@@ -718,7 +717,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
fs::rename(final_dir, backup_dir, ec);
if (ec)
// TRN %1% is a folder path, %2% the system error message.
return fail(GUI::format(_u8L("Failed to back up existing plugin %1%: %2%"), final_dir.string(), ec.message()));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Failed to back up existing plugin %1%: %2%"), final_dir.string(), ec.message()));
backup_created = true;
}
@@ -729,7 +728,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
boost::system::error_code restore_ec;
fs::rename(backup_dir, final_dir, restore_ec);
}
return fail(GUI::format(_u8L("Failed to create plugin directory %1%: %2%"), final_dir.string(), ec.message()));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Failed to create plugin directory %1%: %2%"), final_dir.string(), ec.message()));
}
fs::copy_file(source_path, dest_file, ec);
@@ -740,7 +739,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
fs::rename(backup_dir, final_dir, restore_ec);
}
// TRN %1% is a file path, %2% the system error message.
return fail(GUI::format(_u8L("Failed to copy plugin file to %1%: %2%"), dest_file.string(), ec.message()));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Failed to copy plugin file to %1%: %2%"), dest_file.string(), ec.message()));
}
// Update entry_path to the installed location.
@@ -760,7 +759,7 @@ bool install_plugin(const boost::filesystem::path& filepath,
fs::remove_all(final_dir, rollback_ec);
if (backup_created)
fs::rename(backup_dir, final_dir, rollback_ec);
return fail(GUI::format(_u8L("Failed to write plugin install state: %1%"), (final_dir / INSTALL_STATE_FILE).string()));
return fail(PLUGIN_FORMAT(PLUGIN_U8L("Failed to write plugin install state: %1%"), (final_dir / INSTALL_STATE_FILE).string()));
}
}
+6 -14
View File
@@ -53,18 +53,6 @@ const char* const LOAD_CANCELLED = "__plugin_load_cancelled__";
} // namespace
void Plugin::release_module()
{
if (module == nullptr && plugin_sys_paths.empty() && plugin_modules.empty())
return;
PythonInterpreter::instance().unload_module(module, module_name, plugin_sys_paths, plugin_modules);
module = nullptr;
module_name.clear();
plugin_sys_paths.clear();
plugin_modules.clear();
}
PluginManager& PluginManager::instance()
{
// Touch the interpreter first so its static outlives this one: ~Plugin needs it alive to
@@ -1180,8 +1168,12 @@ void PluginManager::mark_plugin_install_state_disabled(const std::string& plugin
const boost::filesystem::path root(descriptor.plugin_root);
PluginInstallState state;
if (!read_install_state(root, state))
seed_install_metadata(state, descriptor);
if (!read_install_state(root, state)) {
state.installed_from = descriptor.is_cloud_plugin() ? "cloud" : "local";
state.installed_version = !descriptor.installed_version.empty() ? descriptor.installed_version : descriptor.version;
state.plugin_name = descriptor.name;
state.cloud_uuid = descriptor.cloud_uuid();
}
state.enabled = false;
if (!write_install_state(root, state))
return;
+22
View File
@@ -0,0 +1,22 @@
// Plugin module ownership is part of the loader's contract, not of the registry's GUI-facing
// surface. Kept in its own translation unit so the headless probe can link the loader without
// pulling PluginManager.cpp (and therefore wx/GUI) into the probe.
#include "PluginManager.hpp"
#include "PythonInterpreter.hpp"
namespace Slic3r {
void Plugin::release_module()
{
if (module == nullptr && plugin_sys_paths.empty() && plugin_modules.empty())
return;
PythonInterpreter::instance().unload_module(module, module_name, plugin_sys_paths, plugin_modules);
module = nullptr;
module_name.clear();
plugin_sys_paths.clear();
plugin_modules.clear();
}
} // namespace Slic3r
+565
View File
@@ -0,0 +1,565 @@
// Headless, record-only plugin permission probe.
//
// This is a developer/security-analysis tool, not a second production loader. It reuses the
// embedded interpreter, the production plugin_loader sequence and the GUI-free `orca` bindings
// (capability types plus the geometry/model/slicing host domains), so the observations come from
// the same audit classification and target extraction as the GUI. It then lets every audited
// operation continue instead of consulting permission grants or dialogs. Host domains that need
// the live GUI (app, presets, ui) and plugin.storage are registered as explicit unsupported
// errors; the config API reports an empty config and refuses writes.
//
// It is NOT a sandbox. Plugin code runs with the probe's filesystem, network and process
// privileges. The temporary data directory only keeps OrcaSlicer's own state out of the user's
// tree; it does not confine plugin-authored code. Use OS-level restrictions (container, user,
// seccomp/AppArmor, firewall) when the package is not trusted.
//
// The report describes only the paths this run exercised. CPython audit events are observations of
// particular operations, not a notification for every Python call, so absence of a category in the
// report is not evidence that the plugin cannot perform it.
#include "PluginAuditManager.hpp"
#include "PluginDescriptor.hpp"
#include "PluginFsUtils.hpp"
#include "PluginLoader.hpp"
#include "PluginManager.hpp"
#include "PluginProbeCollector.hpp"
#include "PythonInterpreter.hpp"
#include "PythonPluginInterface.hpp"
#include "libslic3r/LifecycleEvents.hpp"
#include "libslic3r/Utils.hpp"
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/system/error_code.hpp>
#include <nlohmann/json.hpp>
#include <pybind11/embed.h>
#include <pybind11/gil.h>
#include <pybind11/pytypes.h>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace fs = boost::filesystem;
namespace py = pybind11;
using namespace Slic3r;
namespace {
constexpr const char* kLoadPhase = "load:import+registration+on_load";
struct Options
{
fs::path plugin_path;
bool json = false;
};
void print_usage(std::ostream& out)
{
out << "Usage: orca-plugin-probe [--json] <plugin.py|plugin.whl>\n"
"\n"
"Runs a plugin in a temporary data/working directory and reports the CPython audit\n"
"events observed while its import, registration, on_load and discoverable callbacks\n"
"execute. The probe does not prompt for permissions, write grants, install dependencies,\n"
"or start the OrcaSlicer GUI.\n"
"\n"
" --json Emit the report as JSON (default: human-readable text)\n"
" --help Show this message\n"
"\n"
"WARNING: this is not a sandbox. Plugin Python code runs with this process's privileges.\n"
"Results are observational and non-exhaustive. Use OS-level restrictions for untrusted\n"
"packages.\n"
"\n"
"Exit status: 0 plugin loaded, 1 initialization/load failure, 2 usage error.\n";
}
bool parse_options(int argc, char** argv, Options& options, std::string& error)
{
for (int index = 1; index < argc; ++index) {
const std::string argument = argv[index];
if (argument == "--help" || argument == "-h") {
print_usage(std::cout);
std::exit(0);
}
if (argument == "--json") {
options.json = true;
continue;
}
if (!argument.empty() && argument.front() == '-') {
error = "Unknown option: " + argument;
return false;
}
if (!options.plugin_path.empty()) {
error = "Only one plugin package may be probed at a time.";
return false;
}
options.plugin_path = fs::path(argument);
}
if (options.plugin_path.empty()) {
error = "No plugin package given.";
return false;
}
return true;
}
// Keep every write OrcaSlicer makes during the run inside a throwaway tree, and keep relative
// paths opened by plugin code out of the caller's working directory. This is hygiene, not
// confinement: an absolute path supplied by the plugin is still opened normally.
class ScopedProbeWorkspace
{
public:
ScopedProbeWorkspace()
: m_root(fs::temp_directory_path() / fs::unique_path("orca-plugin-probe-%%%%-%%%%-%%%%"))
, m_previous_data_dir(data_dir())
, m_previous_working_dir(fs::current_path())
{
fs::create_directories(m_root);
set_data_dir(m_root.string());
fs::current_path(m_root);
m_moved = true;
}
~ScopedProbeWorkspace()
{
boost::system::error_code ec;
set_data_dir(m_previous_data_dir);
if (m_moved)
fs::current_path(m_previous_working_dir, ec);
fs::remove_all(m_root, ec);
}
const fs::path& root() const { return m_root; }
private:
fs::path m_root;
std::string m_previous_data_dir;
fs::path m_previous_working_dir;
bool m_moved = false;
};
class ScopedObservationObserver
{
public:
explicit ScopedObservationObserver(PluginProbeCollector& collector) : m_collector(collector)
{
PluginAuditManager::instance().set_observation_observer(
[this](const AuditObservation& observation) { m_collector.record(observation); });
}
~ScopedObservationObserver() { PluginAuditManager::instance().clear_observation_observer(); }
ScopedObservationObserver(const ScopedObservationObserver&) = delete;
ScopedObservationObserver& operator=(const ScopedObservationObserver&) = delete;
private:
PluginProbeCollector& m_collector;
};
bool prepare_descriptor(const fs::path& plugin_path, PluginDescriptor& descriptor, std::string& error)
{
boost::system::error_code ec;
const fs::path canonical = fs::weakly_canonical(plugin_path, ec);
if (ec || !fs::exists(canonical) || !fs::is_regular_file(canonical)) {
error = "Plugin package is not a readable file: " + plugin_path.string();
return false;
}
std::string extension = canonical.extension().string();
boost::algorithm::to_lower(extension);
if (extension != ".py" && extension != ".whl") {
error = "Plugin package must be a .py or .whl file, got: " + extension;
return false;
}
if (extension == ".whl") {
if (!read_wheel_plugin_metadata(canonical, descriptor, error))
return false;
} else {
if (!read_python_plugin_metadata(canonical, descriptor, error))
return false;
}
descriptor.entry_path = canonical.string();
descriptor.plugin_key = make_local_plugin_key(canonical.stem().string());
descriptor.metadata_valid = true;
// Leaving plugin_root empty keeps the probe independent of any .install_state.json next to
// the package and avoids the production sidecar path.
descriptor.plugin_root.clear();
if (descriptor.name.empty())
descriptor.name = descriptor.plugin_key;
return true;
}
void redirect_python_stdout()
{
py::gil_scoped_acquire gil;
py::object sys = py::module_::import("sys");
// Keep plugin prints from corrupting the C++ report on stdout. sys.stderr is the interpreter's
// tee to the temporary log, so plugin output remains available there.
sys.attr("stdout") = sys.attr("stderr");
}
template<class Function>
void invoke_callback(const std::shared_ptr<PluginCapabilityInterface>& capability,
const std::string& phase,
const std::string& callback,
PluginProbeCollector& collector,
Function&& function)
{
ScopedPluginAuditPhase phase_scope(phase);
try {
std::forward<Function>(function)();
collector.record_callback({capability ? capability->name() : std::string{}, phase, callback, "invoked", {}});
} catch (const std::exception& error) {
collector.record_callback({capability ? capability->name() : std::string{}, phase, callback, "failed", error.what()});
} catch (...) {
collector.record_callback({capability ? capability->name() : std::string{}, phase, callback, "failed", "non-standard exception"});
}
}
struct ProbeCapability
{
std::string name;
std::string type;
bool enabled = true;
};
std::vector<ProbeCapability> describe_capabilities(const Plugin& plugin)
{
std::vector<ProbeCapability> capabilities;
capabilities.reserve(plugin.capabilities.size());
for (const auto& capability : plugin.capabilities) {
if (!capability)
continue;
capabilities.push_back({capability->name(), plugin_capability_type_to_string(capability->type()), capability->is_enabled()});
}
return capabilities;
}
void exercise_callbacks(const Plugin& plugin, PluginProbeCollector& collector)
{
// on_load() already ran inside plugin_loader::load. The callbacks below are the additional
// entry points a loaded capability exposes to the host. Synthetic inputs are used; a callback
// may behave differently with a real application state, which the report cannot capture.
static constexpr LifecycleEvent lifecycle_events[] = {
LifecycleEvent::NewProject, LifecycleEvent::ProjectOpened, LifecycleEvent::ProjectBeforeSave,
LifecycleEvent::ProjectAfterSave, LifecycleEvent::ProjectClosed, LifecycleEvent::ProjectDirtyChanged,
LifecycleEvent::SliceStarted, LifecycleEvent::SliceGeometryFinished, LifecycleEvent::GCodeExportStarted,
LifecycleEvent::GCodeExportFinished, LifecycleEvent::SlicingJobComplete, LifecycleEvent::ObjectAdded,
LifecycleEvent::ObjectDeleted, LifecycleEvent::ObjectTransformed, LifecycleEvent::ObjectChanged,
LifecycleEvent::ObjectRenamed, LifecycleEvent::PlateCreated, LifecycleEvent::PlateDeleted,
LifecycleEvent::PlateSelected, LifecycleEvent::PlateRenamed, LifecycleEvent::PresetSelected,
LifecycleEvent::PresetSaved, LifecycleEvent::PrintStateChanged, LifecycleEvent::DeviceOnline,
LifecycleEvent::DeviceOffline, LifecycleEvent::DeviceDiscovered, LifecycleEvent::DeviceSelected,
LifecycleEvent::UploadStarted, LifecycleEvent::UploadFinished, LifecycleEvent::PrintJobStarted,
LifecycleEvent::PrintJobFinished, LifecycleEvent::SendJobStarted, LifecycleEvent::SendJobFinished,
};
for (const auto& capability : plugin.capabilities) {
if (!capability)
continue;
invoke_callback(capability, "callback:get_default_config", "get_default_config", collector,
[&capability]() { (void) capability->get_default_config(); });
if (capability->config_ui_available()) {
invoke_callback(capability, "callback:get_config_ui", "get_config_ui", collector,
[&capability]() { (void) capability->get_config_ui(); });
} else {
collector.record_callback(
{capability->name(), "callback:get_config_ui", "get_config_ui", "skipped", "has_config_ui() is false"});
}
for (const LifecycleEvent event : lifecycle_events) {
const std::string event_name = lifecycle_event_to_string(event);
const std::string phase = "callback:on_lifecycle_event(" + event_name + ")";
LifecycleEventContext context;
context.source = "orca-plugin-probe";
context.msg = "synthetic event generated by the permission probe";
invoke_callback(capability, phase, "on_lifecycle_event(" + event_name + ")", collector,
[&capability, event, &context]() { capability->on_lifecycle_event(event, context); });
}
// Cancellation is a load-time path; calling it after a successful load would misrepresent
// the capability's real lifecycle. Report it as skipped instead.
collector.record_callback(
{capability->name(), "callback:on_cancelled", "on_cancelled", "skipped", "not invoked after a successful load"});
}
}
nlohmann::json observation_json(const AuditObservation& observation)
{
return {
{"plugin", observation.plugin_key},
{"capability", observation.capability},
{"phase", observation.phase.empty() ? "unattributed" : observation.phase},
{"event", observation.event_name},
{"category", observation.category},
{"targets", observation.targets},
{"continued", observation.continued},
};
}
nlohmann::json callback_json(const ProbeCallbackRecord& callback)
{
return {
{"capability", callback.capability}, {"phase", callback.phase}, {"callback", callback.callback},
{"status", callback.status}, {"detail", callback.detail},
};
}
nlohmann::json capability_json(const ProbeCapability& capability)
{
return {
{"name", capability.name},
{"type", capability.type},
{"enabled", capability.enabled},
};
}
nlohmann::json build_report(const Options& options,
const PluginProbeCollector& collector,
const std::vector<ProbeCapability>& capabilities,
const std::string& plugin_key,
bool python_initialized,
const std::string& python_error,
bool loaded,
const std::string& load_error,
const std::string& data_dir)
{
nlohmann::json observations = nlohmann::json::array();
for (const AuditObservation& observation : collector.observations())
observations.push_back(observation_json(observation));
nlohmann::json callbacks = nlohmann::json::array();
for (const ProbeCallbackRecord& callback : collector.callbacks())
callbacks.push_back(callback_json(callback));
nlohmann::json capability_list = nlohmann::json::array();
for (const ProbeCapability& capability : capabilities)
capability_list.push_back(capability_json(capability));
return {
{"tool", "orca-plugin-permission-probe"},
{"mode", "record-only"},
{"observed_by_this_run_only", true},
{"plugin",
{
{"path", options.plugin_path.string()},
{"key", plugin_key},
}},
{"environment",
{
{"python_initialized", python_initialized},
{"python_error", python_error},
{"temporary_data_dir", data_dir},
{"temporary_data_dir_removed_on_exit", true},
{"working_directory", data_dir},
{"interactive_prompts", false},
{"grants_persisted", false},
}},
{"load", {{"ok", loaded}, {"error", load_error}, {"capabilities", capability_list}}},
{"callbacks", callbacks},
{"observations", observations},
{"summary", collector.summary()},
{"coverage",
{
{"exhaustive", false},
{"sandbox", false},
{"plugin_code_executed", true},
{"notes",
{
"Only the code paths this probe exercised are represented. Audit events cover "
"particular operations, not every Python call.",
"The probe does not start the GUI. Host APIs that require a live application or "
"UI (orca.host.app/presets/ui) and plugin.storage report an explicit unsupported "
"error and are reported as failed callbacks.",
"The probe links libslic3r for core geometry/print types, but not libslic3r_gui "
"or wx.",
"The temporary data directory isolates OrcaSlicer state, not plugin-authored file, "
"network or process access. Use OS-level restrictions for untrusted packages.",
"The loader may extract adjacent .whl dependencies into the package's directory; "
"probe a copy of the package when that side effect is unwanted.",
"Import, registration and on_load share one loader phase; the production loader "
"does not expose a finer boundary without changing its behavior.",
"Callbacks run with synthetic inputs, which can change plugin control flow "
"compared with a real application session.",
"continued=true means the audit hook did not block the operation. A surrounding "
"callback or load step can still fail afterwards, as reported in callbacks/load.",
"Events raised on a plugin-spawned thread carry no phase label and are reported "
"as unattributed.",
"Plugin code can spawn threads/processes, write anywhere this process can, or "
"terminate the process. None of that is contained by the probe.",
}},
}},
};
}
void print_text_report(const nlohmann::json& report)
{
std::cout << "OrcaSlicer plugin permission probe (record-only)\n"
"WARNING: observational only; not exhaustive and not a sandbox.\n\n";
std::cout << "Plugin: " << report["plugin"]["path"].get<std::string>() << "\n";
std::cout << "Python initialized: " << (report["environment"]["python_initialized"].get<bool>() ? "yes" : "no") << "\n";
if (!report["environment"]["python_error"].get<std::string>().empty())
std::cout << "Python error: " << report["environment"]["python_error"].get<std::string>() << "\n";
std::cout << "Load: " << (report["load"]["ok"].get<bool>() ? "ok" : "failed") << "\n";
if (!report["load"]["error"].get<std::string>().empty())
std::cout << "Load error: " << report["load"]["error"].get<std::string>() << "\n";
std::cout << "\nCapabilities (" << report["load"]["capabilities"].size() << "):\n";
for (const auto& capability : report["load"]["capabilities"])
std::cout << " " << capability["name"].get<std::string>() << " [" << capability["type"].get<std::string>()
<< "] enabled=" << (capability["enabled"].get<bool>() ? "yes" : "no") << "\n";
std::cout << "\nCallbacks (" << report["callbacks"].size() << "):\n";
for (const auto& callback : report["callbacks"]) {
std::cout << " " << callback["status"].get<std::string>() << " " << callback["callback"].get<std::string>();
if (!callback["capability"].get<std::string>().empty())
std::cout << " capability=" << callback["capability"].get<std::string>();
if (!callback["detail"].get<std::string>().empty())
std::cout << " - " << callback["detail"].get<std::string>();
std::cout << "\n";
}
std::cout << "\nObserved audit events (" << report["observations"].size() << "):\n";
for (const auto& observation : report["observations"]) {
std::cout << " phase=" << observation["phase"].get<std::string>() << " event=" << observation["event"].get<std::string>()
<< " category=" << observation["category"].get<std::string>();
if (!observation["capability"].get<std::string>().empty())
std::cout << " capability=" << observation["capability"].get<std::string>();
if (!observation["targets"].empty()) {
std::cout << " targets=";
bool first = true;
for (const auto& target : observation["targets"]) {
if (!first)
std::cout << ",";
std::cout << target.get<std::string>();
first = false;
}
}
std::cout << " continued=" << (observation["continued"].get<bool>() ? "yes" : "no") << "\n";
}
std::cout << "\nObserved permission categories:\n";
for (const auto& [category, detail] : report["summary"]["categories"].items()) {
std::cout << " " << category << ":";
for (const auto& event : detail["events"])
std::cout << " " << event.get<std::string>();
if (!detail["targets"].empty()) {
std::cout << " -> ";
bool first = true;
for (const auto& target : detail["targets"]) {
if (!first)
std::cout << ", ";
std::cout << target.get<std::string>();
first = false;
}
}
std::cout << "\n";
}
if (report["summary"]["categories"].empty())
std::cout << " (none observed)\n";
std::cout << "\nCoverage limits:\n";
for (const auto& note : report["coverage"]["notes"])
std::cout << " - " << note.get<std::string>() << "\n";
}
} // namespace
int main(int argc, char** argv)
{
Options options;
std::string option_error;
if (!parse_options(argc, argv, options, option_error)) {
std::cerr << "orca-plugin-probe: " << option_error << "\n\n";
print_usage(std::cerr);
return 2;
}
boost::system::error_code ec;
const fs::path canonical_plugin = fs::weakly_canonical(options.plugin_path, ec);
if (!ec)
options.plugin_path = canonical_plugin;
ScopedProbeWorkspace workspace;
PluginProbeCollector collector;
ScopedObservationObserver observer(collector);
PluginDescriptor descriptor;
std::string descriptor_error;
const bool descriptor_ready = prepare_descriptor(options.plugin_path, descriptor, descriptor_error);
PythonInterpreter& interpreter = PythonInterpreter::instance();
bool python_initialized = false;
std::string python_error;
if (descriptor_ready) {
python_initialized = interpreter.initialize();
if (!python_initialized)
python_error = interpreter.last_error();
}
if (python_initialized) {
try {
redirect_python_stdout();
} catch (const std::exception& error) {
python_error = std::string("Could not redirect Python stdout: ") + error.what();
}
}
bool loaded = false;
std::string load_error = descriptor_error;
Plugin plugin;
std::vector<ProbeCapability> capabilities;
if (python_initialized && descriptor_ready) {
// The outer context covers import, registration and on_load in plugin_loader::load; the
// per-callback scopes below cover the follow-up calls. The production loader is unchanged.
ScopedPluginAuditContext audit_context(descriptor.plugin_key);
{
ScopedPluginAuditPhase load_phase(kLoadPhase);
loaded = plugin_loader::load(descriptor, /*skip_deps=*/true, /*capabilities_to_enable=*/{}, nullptr, plugin, load_error);
collector.record_callback({std::string{}, kLoadPhase, "plugin_loader::load", loaded ? "invoked" : "failed", load_error});
collector.record_callback({std::string{}, "callback:on_load", "on_load", loaded ? "invoked" : "skipped",
loaded ? "invoked by plugin_loader::load for each materialized capability" :
"plugin_loader::load failed before completing on_load"});
}
capabilities = describe_capabilities(plugin);
if (loaded)
exercise_callbacks(plugin, collector);
if (loaded) {
ScopedPluginAuditPhase unload_phase("callback:on_unload");
plugin_loader::unload(plugin);
collector.record_callback({std::string{}, "callback:on_unload", "on_unload", "invoked",
"invoked by plugin_loader::unload; per-capability failures are logged by the loader"});
}
}
if (interpreter.is_initialized())
interpreter.shutdown();
const nlohmann::json report = build_report(options, collector, capabilities,
descriptor.plugin_key.empty() ? make_local_plugin_key(options.plugin_path.stem().string()) :
descriptor.plugin_key,
python_initialized, python_error, loaded, load_error, workspace.root().string());
if (options.json)
std::cout << report.dump(2, ' ', false, nlohmann::json::error_handler_t::replace) << "\n";
else
print_text_report(report);
return loaded ? 0 : 1;
}
@@ -0,0 +1,97 @@
#ifndef slic3r_PluginProbeCollector_hpp_
#define slic3r_PluginProbeCollector_hpp_
// Record-only collection for the headless plugin permission probe. This is deliberately a plain
// in-memory store: it has no dialog, grant or persistence path, and it never decides whether an
// audited operation may proceed. Keeping it independent of wx/Python also makes its grouping and
// phase attribution testable without starting the interpreter.
#include "PluginAuditManager.hpp"
#include <nlohmann/json.hpp>
#include <map>
#include <mutex>
#include <set>
#include <string>
#include <utility>
#include <vector>
namespace Slic3r {
// What the probe attempted and what came back. `status` is one of "invoked", "failed" or
// "skipped"; a skipped callback is reported so the absence of observations is not mistaken for a
// clean result.
struct ProbeCallbackRecord
{
std::string capability;
std::string phase;
std::string callback;
std::string status;
std::string detail;
};
class PluginProbeCollector
{
public:
void record(const AuditObservation& observation)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_observations.push_back(observation);
}
void record_callback(ProbeCallbackRecord record)
{
std::lock_guard<std::mutex> lock(m_mutex);
m_callbacks.push_back(std::move(record));
}
std::vector<AuditObservation> observations() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_observations;
}
std::vector<ProbeCallbackRecord> callbacks() const
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_callbacks;
}
// Groups the run by the permission categories the audit hook already assigned, and lists the
// distinct targets and event names seen in each. This is a view of this run only; it says
// nothing about code paths the plugin did not exercise.
nlohmann::json summary() const
{
std::lock_guard<std::mutex> lock(m_mutex);
std::map<std::string, std::set<std::string>> events;
std::map<std::string, std::set<std::string>> targets;
for (const AuditObservation& observation : m_observations) {
events[observation.category].insert(observation.event_name);
targets[observation.category].insert(observation.targets.begin(), observation.targets.end());
}
nlohmann::json categories = nlohmann::json::object();
for (const auto& [category, category_events] : events) {
categories[category] = {
{"events", category_events},
{"targets", targets[category]},
};
}
return {
{"observed_event_count", m_observations.size()},
{"categories", categories},
};
}
private:
mutable std::mutex m_mutex;
std::vector<AuditObservation> m_observations;
std::vector<ProbeCallbackRecord> m_callbacks;
};
} // namespace Slic3r
#endif // slic3r_PluginProbeCollector_hpp_
+44
View File
@@ -0,0 +1,44 @@
#pragma once
// User-facing plugin messages are translated in the GUI build. The headless probe links neither
// libslic3r_gui nor wx, so it formats the same English text without wxGetTranslation. The GUI path
// expands to exactly the calls the plugin sources used before this header existed.
#if defined(ORCA_PLUGIN_PROBE_BUILD)
#include "libslic3r/format.hpp"
#include <string>
#include <utility>
namespace Slic3r::plugin_text {
inline std::string translate_utf8(const char* text) { return text == nullptr ? std::string{} : std::string(text); }
inline std::string translate_utf8(const std::string& text) { return text; }
template<typename... TArgs>
inline std::string format(const char* fmt, TArgs&&... args)
{
return Slic3r::format(fmt, std::forward<TArgs>(args)...);
}
template<typename... TArgs>
inline std::string format(const std::string& fmt, TArgs&&... args)
{
return Slic3r::format(fmt, std::forward<TArgs>(args)...);
}
} // namespace Slic3r::plugin_text
#define PLUGIN_U8L(text) ::Slic3r::plugin_text::translate_utf8(text)
#define PLUGIN_FORMAT(...) ::Slic3r::plugin_text::format(__VA_ARGS__)
#else
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/format.hpp"
#define PLUGIN_U8L(text) _u8L(text)
#define PLUGIN_FORMAT(...) GUI::format(__VA_ARGS__)
#endif
+11 -68
View File
@@ -30,7 +30,7 @@
#include "pluginTypes/slicingPipeline/SlicingPipelinePluginCapability.hpp"
#include <pybind11/pytypes.h>
#include <pybind11/gil.h>
#include "slic3r/GUI/I18N.hpp"
#include "PluginText.hpp"
namespace py = pybind11;
@@ -50,7 +50,6 @@ 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, std::vector<std::string>> g_pending_fs_read_permissions;
std::unordered_map<std::string, std::vector<std::string>> g_pending_network_permissions;
struct PluginInstanceHandle
{
// The C++ plugin interface points into a Python object. Keep both alive through one
@@ -90,7 +89,6 @@ void discard_pending_capture_without_python(const std::string& plugin_key)
}
g_pending_fs_read_permissions.erase(plugin_key);
g_pending_network_permissions.erase(plugin_key);
}
} // namespace
@@ -116,7 +114,6 @@ void PythonPluginBridge::begin_plugin_capture(const std::string& plugin_key)
g_pending_capabilities.erase(plugin_key);
g_pending_package.erase(plugin_key);
g_pending_fs_read_permissions.erase(plugin_key);
g_pending_network_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.
@@ -148,7 +145,6 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
g_pending_capabilities.erase(capture_key);
g_pending_package.erase(capture_key);
g_pending_fs_read_permissions.erase(capture_key);
g_pending_network_permissions.erase(capture_key);
};
try {
@@ -197,31 +193,7 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
granted = PluginAuditManager::instance().request_filesystem_read_permissions(plugin_key, fs_read_permissions);
}
if (!granted) {
error = _u8L("Plugin filesystem read permission request denied");
BOOST_LOG_TRIVIAL(warning) << error << " for key " << plugin_key;
discard_pending_for_key();
clear_active_key();
return {};
}
}
std::vector<std::string> network_permissions;
{
std::lock_guard<std::mutex> lock(g_registry_mutex);
auto it = g_pending_network_permissions.find(capture_key);
if (it != g_pending_network_permissions.end()) {
network_permissions = std::move(it->second);
g_pending_network_permissions.erase(it);
}
}
if (!network_permissions.empty()) {
bool granted = false;
{
py::gil_scoped_release release;
granted = PluginAuditManager::instance().request_network_permissions(plugin_key, network_permissions);
}
if (!granted) {
error = _u8L("Plugin network permission request denied");
error = PLUGIN_U8L("Plugin filesystem read permission request denied");
BOOST_LOG_TRIVIAL(warning) << error << " for key " << plugin_key;
discard_pending_for_key();
clear_active_key();
@@ -351,7 +323,6 @@ void PythonPluginBridge::cancel_plugin_capture(const std::string& plugin_key)
g_pending_capabilities.erase(plugin_key);
g_pending_package.erase(plugin_key);
g_pending_fs_read_permissions.erase(plugin_key);
g_pending_network_permissions.erase(plugin_key);
}
if (g_active_plugin_key == plugin_key)
@@ -379,7 +350,6 @@ void PythonPluginBridge::clear_pending_captures()
}
g_pending_package.clear();
g_pending_fs_read_permissions.clear();
g_pending_network_permissions.clear();
g_active_plugin_key.clear();
return;
}
@@ -389,7 +359,6 @@ void PythonPluginBridge::clear_pending_captures()
g_pending_capabilities.clear();
g_pending_package.clear();
g_pending_fs_read_permissions.clear();
g_pending_network_permissions.clear();
g_active_plugin_key.clear();
}
@@ -589,50 +558,24 @@ void bind_python_api(pybind11::module_& m)
m.def(
"request_permissions",
[](const std::vector<std::string>& fs_read, const std::vector<std::string>& network) {
[](const std::vector<std::string>& fs_read) {
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.
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);
auto& requested = g_pending_fs_read_permissions[g_active_plugin_key];
for (const std::string& path : fs_read) {
if (path.empty())
throw py::value_error("request_permissions(fs_read=...) does not accept empty paths");
}
std::lock_guard<std::mutex> lock(g_registry_mutex);
auto& requested_fs = g_pending_fs_read_permissions[g_active_plugin_key];
for (const std::string& path : fs_read) {
if (std::find(requested_fs.begin(), requested_fs.end(), path) == requested_fs.end())
requested_fs.push_back(path);
}
if (!normalized_network.empty()) {
auto& requested_network = g_pending_network_permissions[g_active_plugin_key];
for (const std::string& entry : normalized_network) {
if (std::find(requested_network.begin(), requested_network.end(), entry) == requested_network.end())
requested_network.push_back(entry);
}
if (std::find(requested.begin(), requested.end(), path) == requested.end())
requested.push_back(path);
}
},
py::arg("fs_read") = std::vector<std::string>{}, py::arg("network") = std::vector<std::string>{},
R"pbdoc(Request permissions while OrcaSlicer loads your module.
py::arg("fs_read") = std::vector<std::string>{},
R"pbdoc(Request filesystem read permissions while OrcaSlicer loads your module.
`fs_read` lists filesystem paths to read. `network` lists http(s) URLs; each is reduced to its
scheme and host, so one grant covers every path, query and port on that host. The host presents
the requests to the user after register_capabilities() returns. Denying a request aborts the
plugin load.)pbdoc");
The host presents the request to the user after register_capabilities() returns. Denying the
request aborts the plugin load.)pbdoc");
m.def("plugin", [](py::object cls) {
if (g_active_plugin_key.empty())
@@ -0,0 +1,4 @@
// libslic3r references NanoSVG without carrying its header-only implementation. This probe links
// libslic3r without the GUI BitmapCache.cpp that supplies the implementation in the application.
#define NANOSVG_IMPLEMENTATION
#include "nanosvg/nanosvg.h"
@@ -0,0 +1,32 @@
// Headless replacement for the GUI permission front end. The probe installs an observation
// observer, so the audit hook records and returns before reaching this seam. If that observer is
// ever absent, permission decisions fail closed instead of consulting GUI or install state.
#include "slic3r/plugin/PluginAuditManagerInternal.hpp"
#include <boost/log/trivial.hpp>
#include <string>
#include <vector>
namespace Slic3r::plugin_audit {
bool request_filesystem_read_permissions(const std::string& plugin_key,
const std::vector<std::string>& paths)
{
BOOST_LOG_TRIVIAL(warning) << "[PROBE] Refusing filesystem read permission request for " << plugin_key
<< " (" << paths.size() << " path(s)): the headless probe does not evaluate grants";
return false;
}
int decide_event(PluginAuditManager& mgr,
const std::string& event_name,
AuditEventCategory category,
const std::vector<std::string>& targets)
{
(void) category;
(void) targets;
return report_denied(mgr, event_name, {false, "permission decisions are unavailable in the headless probe"});
}
} // namespace Slic3r::plugin_audit
@@ -0,0 +1,75 @@
// Probe-only `orca.host` registration. The GUI-free domains use the production bindings; the
// domains that need a live GUI application, main window or preset bundle are exposed as explicit
// unsupported submodules instead of being compiled (and linked) into the probe.
//
// A plugin that touches one of those domains fails its own callback with a clear message; the
// failure is recorded by the probe's callback report rather than becoming a link dependency.
#include "slic3r/plugin/host/PluginHost.hpp"
#include "slic3r/plugin/host/PluginHostBindings.hpp"
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <stdexcept>
#include <string>
namespace py = pybind11;
namespace Slic3r {
namespace {
void add_unavailable_domain(py::module_& host, const char* name, const char* description)
{
py::module_ domain = host.def_submodule(name, description);
const std::string prefix = std::string("orca.host.") + name + ".";
domain.attr("__getattr__") = py::cpp_function([prefix](const std::string& attribute) -> py::object {
throw std::runtime_error(prefix + attribute +
" is not available in the headless plugin permission probe because it needs the GUI application");
});
}
void add_unavailable_function(py::module_& host, const char* name)
{
// Production registers these in PluginHostApp::register_app(). Do not overwrite a slot that
// another registrar already claimed (the model domain binds the Model class through
// register_model); the probe only fills the GUI-backed accessors that are absent here.
if (py::hasattr(host, name))
return;
const std::string detail = std::string("orca.host.") + name +
" is not available in the headless plugin permission probe because it needs the GUI application";
host.def(name, [detail](py::args, py::kwargs) -> py::object { throw std::runtime_error(detail); }, detail.c_str());
}
} // namespace
void PluginHost::RegisterBindings(py::module_& module)
{
auto host = module.def_submodule("host", "Host application API");
// Value types first so the docstring signatures of later registrars resolve to the bound names.
host_bindings::register_geometry(host);
host_bindings::register_mesh(host);
host_bindings::register_model(host);
host_bindings::register_slicing(host);
// These domains are backed by the live GUI, its Plater/MainFrame and the preset bundle.
add_unavailable_domain(host, "presets", "Preset bundle access (headless probe: unavailable)");
add_unavailable_domain(host, "app", "Live application and Plater access (headless probe: unavailable)");
add_unavailable_domain(host, "ui", "Native dialogs and HTML windows (headless probe: unavailable)");
for (const char* name : {"plater", "model", "preset_bundle", "app_info", "gl_info", "selected_printer"})
add_unavailable_function(host, name);
// Storage needs the PluginManager registry, which is not part of the headless probe.
auto plugin_host = host.def_submodule("plugin", "Plugin host API (headless probe: storage unavailable)");
plugin_host.def("storage", []() -> std::string {
throw std::runtime_error("orca.host.plugin.storage() is not available in the headless plugin permission probe");
}, "Return the installed folder of the current plugin.");
plugin_host.attr("__getattr__") = py::cpp_function([](const std::string& attribute) -> py::object {
throw std::runtime_error("orca.host.plugin." + attribute +
" is not available in the headless plugin permission probe");
});
}
} // namespace Slic3r
@@ -0,0 +1,32 @@
// Minimal replacement for the config API PythonPluginBridge binds into `orca`.
//
// The production implementation (PluginConfig.cpp) resolves presets, reads the sidebar's effective
// config and writes config.json through PluginManager, all of which pull in the GUI and the
// registry. The probe has neither: a capability reports an empty config, an empty version and a
// refused save. That keeps the bridge's Python surface intact without pretending to reproduce
// application state the probe does not have.
#include "slic3r/plugin/PluginConfig.hpp"
#include "slic3r/plugin/PythonPluginInterface.hpp"
#include <nlohmann/json.hpp>
#include <string>
namespace Slic3r {
nlohmann::json capability_get_config(const PluginCapabilityInterface&)
{
return nlohmann::json::object();
}
std::string capability_get_config_version(const PluginCapabilityInterface&) { return {}; }
bool capability_save_config(const PluginCapabilityInterface&, const nlohmann::json&) { return false; }
std::string PluginConfig::capability_type_label(PluginCapabilityType type)
{
return plugin_capability_type_display_name(type);
}
} // namespace Slic3r
+102 -88
View File
@@ -3,11 +3,13 @@
#include <boost/system/error_code.hpp>
#include <catch2/catch_all.hpp>
#include <cstddef>
#include <libslic3r/Utils.hpp>
#include <libslic3r/libslic3r.h> // GCODEVIEWER_APP_KEY, SLIC3R_APP_KEY (via libslic3r_version.h)
#include <slic3r/plugin/PluginAuditManager.hpp>
#include <slic3r/plugin/PluginFsUtils.hpp>
#include <slic3r/plugin/PluginManager.hpp>
#include <slic3r/plugin/PluginProbeCollector.hpp>
#include <slic3r/plugin/PythonInterpreter.hpp>
#include <slic3r/plugin/PythonPluginBridge.hpp>
#include <slic3r/plugin/PythonPluginInterface.hpp>
@@ -32,6 +34,7 @@
#include <pybind11/pytypes.h>
#include <pybind11/stl.h>
#include <algorithm>
#include <fstream>
#include <functional>
#include <ios>
@@ -67,9 +70,29 @@ void seed_denied_keywords()
mgr.add_denied_path_keyword(keyword);
}
// Installs the record-only observer for a test and always clears it, so a failed CHECK cannot
// leave a callback pointing at a destroyed collector for the next test in this process.
struct ScopedTestObservationObserver
{
explicit ScopedTestObservationObserver(PluginProbeCollector& collector)
: m_collector(collector)
{
PluginAuditManager::instance().set_observation_observer(
[this](const AuditObservation& observation) { m_collector.record(observation); });
}
~ScopedTestObservationObserver() { PluginAuditManager::instance().clear_observation_observer(); }
ScopedTestObservationObserver(const ScopedTestObservationObserver&) = delete;
ScopedTestObservationObserver& operator=(const ScopedTestObservationObserver&) = delete;
private:
PluginProbeCollector& m_collector;
};
} // namespace
TEST_CASE("Plugin audit denies app config and token filenames anywhere", "[audit]")
TEST_CASE("Plugin audit denies host-managed filenames anywhere", "[audit]")
{
seed_denied_names();
const PluginAuditManager& mgr = PluginAuditManager::instance();
@@ -81,6 +104,7 @@ TEST_CASE("Plugin audit denies app config and token filenames anywhere", "[audit
CHECK(mgr.is_denied_filename(fs::path(SLIC3R_APP_KEY ".ini")));
CHECK(mgr.is_denied_filename(fs::path(GCODEVIEWER_APP_KEY ".ini")));
CHECK(mgr.is_denied_filename(fs::path(secret_constants::USER_SECRET_FILENAME)));
CHECK(mgr.is_denied_filename(fs::path(".install_state.json")));
}
SECTION("companions holding the same secrets are denied by the prefix rule")
@@ -136,6 +160,7 @@ TEST_CASE("Plugin audit deny beats allowed roots", "[audit]")
const fs::path conf = fs::path(data_dir()) / (SLIC3R_APP_KEY ".conf");
const fs::path token = fs::path(data_dir()) / secret_constants::USER_SECRET_FILENAME;
const fs::path install_state = fs::path(data_dir()) / "plugins" / "example" / ".install_state.json";
SECTION("a non-denied file inside the allowed root is writable (root really grants writes)")
{
@@ -176,6 +201,17 @@ TEST_CASE("Plugin audit deny beats allowed roots", "[audit]")
CHECK_FALSE(decision.allowed);
}
SECTION("plugin install state is blocked for reads and writes despite the allowed root")
{
AuditDecision read_decision = mgr.check_open(install_state.string(), "r");
CHECK_FALSE(read_decision.allowed);
CHECK(read_decision.reason == "denied filename");
AuditDecision write_decision = mgr.check_open(install_state.string(), "w");
CHECK_FALSE(write_decision.allowed);
CHECK(write_decision.reason == "denied filename");
}
SECTION("a traversal path resolving to the config is blocked")
{
const fs::path traversal = fs::path(data_dir()) / "plugins" / ".." / (SLIC3R_APP_KEY ".conf");
@@ -351,93 +387,6 @@ TEST_CASE("Plugin audit a read-only allowed root blocks writes but not reads", "
}
}
TEST_CASE("Plugin audit network permissions match by scheme and host", "[audit]")
{
SECTION("a URL is reduced to its scheme and host")
{
CHECK(PluginAuditManager::normalize_network_url("https://API.Example.com:8443/v1/items?page=2#top") ==
"https://api.example.com");
CHECK(PluginAuditManager::normalize_network_url("http://example.com") == "http://example.com");
CHECK(PluginAuditManager::normalize_network_url("https://[2001:db8::1]:443/path") == "https://[2001:db8::1]");
}
SECTION("non-http schemes and targets without a scheme are not network URLs")
{
CHECK(PluginAuditManager::normalize_network_url("ftp://example.com").empty());
CHECK(PluginAuditManager::normalize_network_url("api.example.com").empty());
CHECK(PluginAuditManager::normalize_network_url("https://").empty());
}
SECTION("a URL target matches the same scheme and host regardless of path and port")
{
const std::vector<std::string> granted{"https://api.example.com"};
CHECK(PluginAuditManager::network_permission_matches(granted, "https://api.example.com/v1/items?page=2"));
CHECK(PluginAuditManager::network_permission_matches(granted, "https://api.example.com:8443/upload"));
}
SECTION("canonical host grants are broad but persisted full-URL grants stay exact")
{
const std::vector<std::string> declared_host{"https://api.example.com"};
CHECK(PluginAuditManager::network_permission_matches(declared_host, "https://api.example.com/v1"));
const std::vector<std::string> saved_url{"https://api.example.com/v1"};
CHECK(PluginAuditManager::network_permission_matches(saved_url, "https://api.example.com/v1"));
CHECK_FALSE(PluginAuditManager::network_permission_matches(saved_url, "https://api.example.com/v2"));
}
SECTION("a URL target does not match a different host or a different scheme")
{
const std::vector<std::string> granted{"https://api.example.com"};
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "https://evil.example.com/v1"));
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "http://api.example.com/v1"));
}
SECTION("a bare host target matches the host of a grant")
{
const std::vector<std::string> granted{"https://api.example.com"};
CHECK(PluginAuditManager::network_permission_matches(granted, "api.example.com"));
CHECK(PluginAuditManager::network_permission_matches(granted, "api.example.com:443"));
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "other.example.com"));
}
SECTION("legacy persisted address tuples keep matching their host")
{
const std::vector<std::string> legacy_granted{"('api.example.com', 443)"};
CHECK(PluginAuditManager::network_permission_matches(legacy_granted, "api.example.com"));
const std::vector<std::string> granted{"https://api.example.com"};
CHECK(PluginAuditManager::network_permission_matches(granted, "('api.example.com', 443)"));
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "('93.184.216.34', 443)"));
}
SECTION("an IPv6 literal matches across bracketed and bare forms")
{
const std::vector<std::string> granted{"https://[2001:db8::1]"};
CHECK(PluginAuditManager::network_permission_matches(granted, "2001:db8::1"));
CHECK(PluginAuditManager::network_permission_matches(granted, "[2001:db8::1]:443"));
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "2001:db8::2"));
}
SECTION("a non-http URL only matches an exact grant")
{
const std::vector<std::string> granted{"ftp://example.com/file"};
CHECK(PluginAuditManager::network_permission_matches(granted, "ftp://example.com/file"));
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "ftp://example.com/other"));
const std::vector<std::string> https{"https://api.example.com"};
CHECK_FALSE(PluginAuditManager::network_permission_matches(https, "ftp://api.example.com/file"));
}
SECTION("an empty grant list or an empty target never matches")
{
const std::vector<std::string> granted{};
CHECK_FALSE(PluginAuditManager::network_permission_matches(granted, "https://api.example.com"));
const std::vector<std::string> any{"https://api.example.com"};
CHECK_FALSE(PluginAuditManager::network_permission_matches(any, ""));
}
}
TEST_CASE("Plugin audit a scoped root can also be registered read-only", "[audit]")
{
ScopedDataDir data_dir_guard("plugin-audit-scoped-readonly");
@@ -741,6 +690,71 @@ const char* const PLUGIN = "AuditPlugin";
} // namespace
TEST_CASE("Probe phase scope restores the previous phase", "[audit]")
{
PluginAuditManager& mgr = PluginAuditManager::instance();
mgr.set_current_audit_phase("outer");
{
ScopedPluginAuditPhase inner("inner");
CHECK(mgr.current_audit_phase() == "inner");
}
CHECK(mgr.current_audit_phase() == "outer");
mgr.clear_current_audit_phase();
CHECK(mgr.current_audit_phase().empty());
}
TEST_CASE("Record-only probe observations bypass prompts and retain phase attribution", "[audit][Python]")
{
AuditHarness harness;
if (!harness.initialized)
SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error());
harness.add_plugin(PLUGIN);
py::gil_scoped_acquire gil;
PythonSide python(harness);
PluginProbeCollector collector;
ScopedTestObservationObserver observer(collector);
// A declared read permission is recorded and allowed, but must not be written to the sidecar.
{
ScopedPluginAuditContext context(PLUGIN);
CHECK(PluginAuditManager::instance().request_filesystem_read_permissions(PLUGIN, {"/tmp/probe-declared"}));
}
{
ScopedPluginAuditPhase phase("probe:callback");
python.run_as(PLUGIN, "outcome = attempt(lambda: open(PRIVATE).close())");
}
CHECK(python.str("outcome") == "ok");
CHECK(harness.prompts.empty());
CHECK(harness.saved_permissions(PLUGIN).fs_read.empty());
const std::vector<AuditObservation> observations = collector.observations();
const auto open_event = std::find_if(
observations.begin(), observations.end(), [](const AuditObservation& observation) {
return observation.event_name == "open";
});
REQUIRE(open_event != observations.end());
CHECK(open_event->plugin_key == PLUGIN);
CHECK(open_event->phase == "probe:callback");
CHECK(open_event->category == "FsRead");
CHECK(open_event->continued);
CHECK(std::find(open_event->targets.begin(), open_event->targets.end(), python.str("PRIVATE")) !=
open_event->targets.end());
const auto declared = std::find_if(observations.begin(), observations.end(), [](const AuditObservation& observation) {
return observation.event_name == "orca.request_permissions";
});
REQUIRE(declared != observations.end());
CHECK(declared->category == "FsRead");
CHECK(std::find(declared->targets.begin(), declared->targets.end(), "/tmp/probe-declared") != declared->targets.end());
const nlohmann::json summary = collector.summary();
CHECK(summary["categories"].contains("FsRead"));
CHECK(summary["observed_event_count"].get<std::size_t>() == observations.size());
}
TEST_CASE("A saved request grant covers the request's own connection in a later session", "[audit][Python]")
{
AuditHarness harness;