diff --git a/docs/HLSD/plugin-permissions.md b/docs/HLSD/plugin-permissions.md index ceb84ff901..b1a42a0d16 100644 --- a/docs/HLSD/plugin-permissions.md +++ b/docs/HLSD/plugin-permissions.md @@ -125,9 +125,11 @@ nested events of the same operation are not asked again. A plugin declares its needs from Python with `orca.request_permissions(...)` while `register_capabilities` runs. The bridge collects the declarations per plugin. After registration returns and before any capability instance is created, OrcaSlicer presents -one combined prompt for the targets not already stored. Denying the request aborts the -load. A readable sidecar with `full_access` accepts the declaration without a prompt and -without adding a grant. +one combined prompt for the targets not already stored. The request joins the same +`AuditPromptQueue` as runtime prompts: a load worker waits for the answer, while a +GUI-thread caller is rejected when another prompt is active instead of blocking the GUI. +Denying the request aborts the load. A readable sidecar with `full_access` accepts the +declaration without a prompt and without adding a grant. Network URLs passed to `request_permissions(network=...)` are normalized to `scheme://host` before prompting or storing, so one approval covers every path and port @@ -138,16 +140,29 @@ sidecar show the absolute scope it covers. ### Runtime prompts An event that is not covered by a saved grant or an implicit rule is either put to the -user or denied. If the caller is on the wx main thread, the modal runs inline. If it is -not, as on the Script workflow, the plugin-load worker, or the slicing worker, the current -event is denied and the outcome is reported asynchronously. For a category with a persistent -grant list, a Yes/No prompt is posted to the main thread with `CallAfter`; if the user -accepts, the grant is saved and a later matching attempt can succeed without another prompt. -Create and delete do not support persistent grants: on the main thread they use the inline -prompt described above, while off the main thread they are denied and only an informational -denial is posted. That path offers no Yes/No choice and does not claim that the operation can -be approved on a retry. Blocking a worker on a marshalled modal is avoided because the UI -thread can itself be parked on the slicing worker. +user or denied. If the caller is on the wx main thread and no audit prompt is active, the +modal runs inline. Otherwise, as on the Script workflow, the plugin-load worker, or the +slicing worker, the current event is denied and the prompt is queued for the GUI thread. +`AuditPromptQueue` serializes every audit prompt -- runtime events, create/delete +informational denials, and load-time declarations -- so at most one is shown at a time, +including during a modal dialog's nested event loop. An event raised inside that loop is +queued and denied instead of opening a second dialog; the queued prompt opens after the +active dialog has closed. + +For a category with a persistent grant list, a Yes saves the grant and a later matching +attempt can succeed without another prompt. Create and delete do not support persistent +grants: they use the inline Yes/No prompt only when it can be shown immediately on the GUI +thread, while a queued request for them is an OK-only informational denial with no Yes/No +choice. Blocking a worker on a marshalled modal is avoided because the UI thread can itself +be parked on the slicing worker. A load worker does block on its declared-permission answer: +shutdown or plugin unload cancels queued requests and active requests whose accepted answer +has not begun committing, releasing waiting workers with a denial. An admission that races +that cancellation is discarded as soon as it becomes visible. A cancelled load stops being +treated as a live plugin even while its worker is still unwinding. A cancellation observed before +display suppresses the prompt; a dialog racing with cancellation may still appear or remain on +screen, but its answer is ignored unless committing won the race. An ordinary load failure is not +a cancellation: its queued runtime prompt stays actionable, so the user can approve the event +whose denial aborted the load and then retry with the saved grant. Runtime approvals store the target observed by the audit hook. A URL with a path, port or query is therefore an exact grant; a bare host remains usable for raw sockets. The @@ -209,6 +224,14 @@ Anything else at the sidecar path is left in place: a link or a directory, or a that cannot be opened or read in full, since a read error can look like truncated contents. +Declared permissions are added in one locked read-modify-write, including the `threading` +boolean. A successful write notifies an open Plugins dialog so its Permissions tab +refreshes; a failed write notifies nothing. If the sidecar was readable when the declaration +was read but is absent when the answer is saved, the write is refused instead of recreating +it: that is lost state, not a new install. Only a sidecar absent at both reads is seeded. +Runtime grants use the same per-target helper, which takes the lock and re-reads the sidecar +for every target. + Each audit decision reads the current sidecar through `PluginManager::get_install_state`, so a grant persisted by a prompt applies to subsequent top-level operations. A root frame that was already recorded is not @@ -313,8 +336,9 @@ never treated as an opt-out. - `src/slic3r/plugin/PluginAuditManager.hpp` / `.cpp` - `PluginAuditManager`, `install_hook`, `audit_plugin_event`, `decide_audited_event`, `request_permissions`, - `request_permission`, `check_path_access`, `network_permission_matches`, - `default_denied_filenames`, `default_denied_path_keywords`, `ScopedPluginAuditContext`. + `request_permission`, `AuditPromptQueue`, `check_path_access`, + `network_permission_matches`, `default_denied_filenames`, `default_denied_path_keywords`, + `ScopedPluginAuditContext`. - `src/slic3r/plugin/PluginFsUtils.hpp` / `.cpp` - `PluginPermissions`, `PluginInstallState`, `read_install_state`, `write_install_state`. - `src/slic3r/plugin/PythonPluginBridge.cpp` - `request_permissions` binding, diff --git a/docs/HLSD/python-plugin-async-bridge.md b/docs/HLSD/python-plugin-async-bridge.md index 5d54a66235..791e3ba63f 100644 --- a/docs/HLSD/python-plugin-async-bridge.md +++ b/docs/HLSD/python-plugin-async-bridge.md @@ -141,12 +141,21 @@ dropping the pybind holder from a non-Python thread would `DECREF` without the G closed and `tl_script_loop` cleared before the worker exits. A consequence of running Script on a non-main thread: the audit permission prompt is fail-closed off -the main thread. `request_permission` in `src/slic3r/plugin/PluginAuditManager.cpp` posts the dialog -with `CallAfter` and denies the current event. For a category with a persistent grant list, the grant -is saved when the user accepts, so a Script sees a denial on the first attempt and can succeed on a -later one. Create and delete have no persistent grant list, so their off-main-thread path posts only -an informational denial with no Yes/No choice and does not promise a retry. This matches the existing -behavior for the plugin-load worker and the slicing worker. +the main thread. `request_permission` in `src/slic3r/plugin/PluginAuditManager.cpp` queues the dialog +for the GUI thread and denies the current event. For permissions with persistent grants, accepting +the prompt saves a grant for a later attempt, so a Script sees a denial on the first attempt and can +succeed on a later one. Create and delete have no persistent grant: an asynchronous denial instead +shows an informational dialog, without offering an approval and without promising a retry. This +matches the behavior for the plugin-load worker and the slicing worker. + +`AuditPromptQueue` serializes runtime prompts, informational denials and load-time declared-permission +prompts. Only one is shown at a time, including during a modal dialog's nested event loop. A load +worker waits for its declared-permission answer; shutdown or plugin unload cancels pending requests +and active requests whose accepted answers have not started committing, releasing waiting workers +with a denial. An accepted answer already being persisted completes before its worker is released. +A declared-permission request on the GUI thread is +denied if another prompt is active or pending, rather than blocking the GUI or opening a deferred +dialog. The queue outlives static destruction so shutdown can discard requests safely. ### Blocking UI continuation diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index b90e7e5486..c853d07aa2 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -1,8 +1,8 @@ #include "PluginAuditManager.hpp" #include "../Utils/OrcaCloudServiceAgent.hpp" -#include "libslic3r/Utils.hpp" #include "libslic3r/AppConfig.hpp" +#include "libslic3r/Utils.hpp" #include "libslic3r/libslic3r.h" // GCODEVIEWER_APP_KEY, and SLIC3R_APP_KEY via libslic3r_version.h #include "libslic3r_version.h" @@ -19,10 +19,13 @@ #include #include #include +#include #include +#include #include #include #include +#include #include #include #include @@ -35,8 +38,9 @@ #include #include #include -#include #include +#include +#include #include #include #include @@ -44,6 +48,7 @@ #include #include #include +#include #include "slic3r/GUI/I18N.hpp" #include "slic3r/plugin/PluginDescriptor.hpp" #include @@ -394,8 +399,8 @@ struct PermissionMessage { class PermissionDialog : public GUI::MsgDialog { public: - PermissionDialog(const PermissionMessage& message, const wxString& title, bool show_tip) - : MsgDialog(nullptr, title, wxEmptyString, wxYES_NO | wxICON_WARNING) + PermissionDialog(wxWindow* parent, const PermissionMessage& message, const wxString& title, bool show_tip) + : MsgDialog(parent, title, wxEmptyString, wxYES_NO | wxICON_WARNING) { auto* html = new wxHtmlWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxHW_SCROLLBAR_AUTO); const wxFont prose = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); @@ -901,6 +906,14 @@ AuditDecision PluginAuditManager::check_open(const std::string& path_str, const namespace { +// A live top-level window keeps the audit dialog ordered with the app and lets wx tear it down +// with its parent on shutdown. Null only before the main window exists or after it is gone; the +// callers check is_closing() first. +wxWindow* audit_prompt_parent() +{ + return wxTheApp != nullptr ? wxTheApp->GetTopWindow() : nullptr; +} + // A complete sentence of its own, so a translator can place it independently of the request // body. Informational only: a prompt never navigates to, or opens, the Plugins dialog. void append_permission_dialog_tip(wxString& message) @@ -918,11 +931,17 @@ bool show_permission_dialog(PermissionMessage message, const wxString& title) if (show_tip) append_permission_dialog_tip(message.text); - PermissionDialog dialog(message, title, show_tip); + PermissionDialog dialog(audit_prompt_parent(), message, title, show_tip); const int result = dialog.ShowModal(); if (show_tip && config != nullptr && (result == wxID_YES || result == wxID_NO) && dialog.get_checkbox_state()) { - config->set("hide_plugin_permission_tip", "1"); - config->save(); + try { + config->set("hide_plugin_permission_tip", "1"); + config->save(); + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(warning) << "[AUDIT PROMPT] Failed to save the permission-tip preference: " << ex.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(warning) << "[AUDIT PROMPT] Failed to save the permission-tip preference: unknown exception"; + } } return result == wxID_YES; } @@ -1637,6 +1656,27 @@ bool prompt_for_permission_message(const PermissionMessage& message) return show_permission_dialog(message, _L("Plugin permissions")); } +// Builds the combined body for a load-time declaration. Each bucket keeps its own formatted target +// block, so a translated sentence can place its target list independently. +PermissionMessage build_permission_message(const std::string& plugin_name, const std::vector& buckets) +{ + PermissionMessage message; + for (const AuditPromptBucket& bucket : buckets) { + wxString targets; + for (const std::string& target : bucket.targets) + targets += wxString::FromUTF8(target.c_str()) + "\n"; + + if (!message.text.IsEmpty()) + message.text += "\n\n"; + PermissionMessage part = formatted_audit_message(bucket.category, wxString::FromUTF8(plugin_name.c_str()), + wxEmptyString, targets, bucket.targets.size()); + for (const auto& range : part.targets) + message.targets.emplace_back(message.text.length() + range.first, range.second); + message.text += part.text; + } + return message; +} + // Builds the informational message shown when an off-main-thread create/delete event is denied. // There is no Yes/No choice: that path cannot grant create/delete permission, so the dialog must // not imply that approving it would make a later attempt succeed. @@ -1680,7 +1720,7 @@ void show_permission_denied_dialog(AuditEventCategory category, const std::strin const wxString message = permission_denied_message(category, wxString::FromUTF8(plugin_name.c_str()), target_list, targets.size()); - GUI::MessageDialog(nullptr, message, _L("Plugin operation denied"), wxOK | wxICON_WARNING).ShowModal(); + GUI::MessageDialog(audit_prompt_parent(), message, _L("Plugin operation denied"), wxOK | wxICON_WARNING).ShowModal(); } // Records a grant in the plugin's sidecar so it is not asked again. Each persist helper re-reads @@ -1704,9 +1744,209 @@ bool persist_grant(const std::string& plugin_key, AuditEventCategory category, b return persisted; } +// Persists every missing target of a declaration in one sidecar write. Takes the shared lock and +// re-reads the sidecar so a grant saved while the queued dialog was open is kept. The +// sidecar_was_readable flag records the status seen when the declaration was read: a sidecar that +// was readable then and is absent now must not be recreated, since that is lost state rather than +// a new install. Only a sidecar absent at both reads is seeded. Notifies an existing Plugins +// dialog when a write succeeded; a failed write leaves its Permissions tab accurate. +bool persist_declared_permissions(const std::string& plugin_key, const std::vector& buckets, + bool sidecar_was_readable) +{ + PluginDescriptor descriptor; + if (!PluginManager::instance().try_get_plugin_descriptor(plugin_key, descriptor) || descriptor.plugin_root.empty()) + return false; + + bool persisted = false; + { + std::lock_guard state_lock(install_state_mutex()); + + PluginInstallState state; + const boost::filesystem::path root(descriptor.plugin_root); + const InstallStateReadStatus status = read_install_state_status(root, state); + // A malformed file is never replaced, and a sidecar that disappeared after a readable read + // is treated as lost state, not as a new install. + if (status == InstallStateReadStatus::Unreadable) + return false; + if (status == InstallStateReadStatus::Absent && sidecar_was_readable) + return false; + + seed_install_metadata(descriptor, state); + for (const AuditPromptBucket& bucket : buckets) { + if (bucket.category == AuditEventCategory::Threading) { + state.permissions.threading = true; + continue; + } + std::vector* permission_list = + permission_list_for(bucket.category, /*by_event=*/false, state.permissions); + if (!permission_list) + continue; + for (const std::string& target : bucket.targets) + if (std::find(permission_list->begin(), permission_list->end(), target) == permission_list->end()) + permission_list->push_back(target); + } + + persisted = write_install_state(root, state); + } + + // Notify outside the lock: the refresh is posted to the GUI thread, and a dialog must not wait + // on a sidecar writer. A failed write changed nothing, so only a stored grant notifies. + if (persisted) + post_permission_changed_notification(plugin_key); + return persisted; +} + static PluginAuditManager::PermissionPrompt s_permission_prompt_for_testing; static PluginAuditManager::PermissionMessagePrompt s_permission_message_prompt_for_testing; +AuditPromptQueue& runtime_audit_prompts() +{ + // Deliberately leaked. A worker can be waiting on a queued prompt while static destructors + // run; the queue itself must stay valid until process exit, and its destructor has no work + // that is safe to order against wx teardown. + static AuditPromptQueue* queue = new AuditPromptQueue(); + return *queue; +} + +bool show_queued_prompt(const AuditPromptRequest& request) +{ + switch (request.kind) { + case AuditPromptKind::RuntimeEvent: + return prompt_for_targets(request.category, request.plugin_name, request.event_name, request.shown); + case AuditPromptKind::DeclaredPermissions: + return prompt_for_permission_message(build_permission_message(request.plugin_name, request.buckets)); + case AuditPromptKind::DeniedOperation: + show_permission_denied_dialog(request.category, request.plugin_name, request.shown); + return false; + } + return false; +} + +void drain_runtime_prompts(); + +void schedule_runtime_prompt_drain() +{ + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) { + runtime_audit_prompts().discard_all(); + return; + } + GUI::wxGetApp().CallAfter([]() { drain_runtime_prompts(); }); +} + +// Schedules the next prompt. A failure here cannot be allowed to strand queued workers: discard +// everything still waiting and log why, so every completion is released with a denial. +bool schedule_runtime_prompt_drain_checked() +{ + try { + schedule_runtime_prompt_drain(); + return true; + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to schedule the next prompt: " << ex.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to schedule the next prompt: unknown exception"; + } + runtime_audit_prompts().discard_all(); + return false; +} + +// Ends the active prompt exactly once, in queue order: complete first, then release the waiting +// worker, then schedule the next prompt. Used from normal and exceptional paths alike. +bool finish_audit_prompt(const std::shared_ptr& completion, bool satisfied) +{ + if (runtime_audit_prompts().complete()) + satisfied = false; + if (completion) + completion->resolve(satisfied); + if (runtime_audit_prompts().has_pending()) + schedule_runtime_prompt_drain_checked(); + return satisfied; +} + +// Shows the oldest queued prompt. The next one is scheduled only after this dialog has returned, +// so its modal event loop cannot deliver another prompt that opens a second dialog. +void drain_runtime_prompts() +{ + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) { + runtime_audit_prompts().discard_all(); + return; + } + + std::optional request = runtime_audit_prompts().take_next(); + if (!request) + return; + + // A request may have been enqueued concurrently with plugin unload, after its queued + // requests were discarded. Keep requests raised during plugin loading valid as well: plugin + // code can run before the manager commits it as loaded. A cancelled load keeps its in-progress + // slot until its worker unwinds, but an observed cancellation makes it ineligible for a new + // prompt or a grant that has not begun committing; the queue cancels a dialog already up. + // An ordinary load failure is different: its queued runtime prompt survives so the user can + // approve the event whose denial aborted the load and then retry with the saved grant. + PluginManager& manager = PluginManager::instance(); + const auto plugin_available = [&manager](const AuditPromptRequest& prompt) { + AuditPromptPluginState state; + state.loaded = manager.is_plugin_loaded(prompt.plugin_key); + state.load_in_progress = manager.is_plugin_load_in_progress(prompt.plugin_key); + state.load_cancelled = manager.is_plugin_load_cancelled(prompt.plugin_key); + state.load_failed = manager.is_plugin_load_failed(prompt.plugin_key); + state.shutting_down = manager.is_shutting_down(); + return prompt_plugin_is_available(state, prompt.kind); + }; + + bool satisfied = false; + try { + const bool alive = plugin_available(*request); + const bool granted = alive && show_queued_prompt(*request); + + // Decide under the still-active queue entry so a shutdown/unload that arrives before the + // sidecar write cancels this request. begin_commit() makes an accepted answer atomic + // against cancellation: if cancel wins, nothing is persisted; if commit wins, the answer is + // valid and complete() cannot report it as cancelled afterwards. + const bool alive_after_prompt = plugin_available(*request); + satisfied = granted && alive_after_prompt && !PluginManager::instance().is_shutting_down() && + runtime_audit_prompts().begin_commit(); + + if (satisfied) { + switch (request->kind) { + case AuditPromptKind::RuntimeEvent: + persist_grant(request->plugin_key, request->category, request->by_event, request->keys); + break; + case AuditPromptKind::DeclaredPermissions: + satisfied = persist_declared_permissions(request->plugin_key, request->buckets, + request->sidecar_was_readable); + if (!satisfied) + BOOST_LOG_TRIVIAL(warning) << "[AUDIT PROMPT] Failed to persist declared permissions for " + << request->plugin_key; + break; + case AuditPromptKind::DeniedOperation: + break; + } + } + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Permission prompt failed for plugin=" << request->plugin_key + << ": " << ex.what(); + satisfied = false; + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Permission prompt failed for plugin=" << request->plugin_key + << ": unknown exception"; + satisfied = false; + } + + // While a commit is active, discards above leave it alone; finish_audit_prompt() completes + // first, then resolves the worker, then schedules the next prompt. + finish_audit_prompt(request->completion, satisfied); +} + +void discard_runtime_prompts() +{ + runtime_audit_prompts().discard_all(); +} + +void discard_runtime_prompts_for(const std::string& plugin_key) +{ + runtime_audit_prompts().discard_plugin(plugin_key); +} + static const char* audit_category_name(AuditEventCategory category) { switch (category) { @@ -1737,9 +1977,12 @@ static const char* audit_category_name(AuditEventCategory category) // prompt); the grant is persisted once the user accepts, so a later attempt succeeds without // re-prompting. // -// Create and delete are the exception: they have no persistent grant to save, so an off-main- -// thread request is denied and only an informational denial is shown. Showing a Yes/No prompt -// would falsely imply that accepting it could authorize the operation or a later retry. +// Runtime prompts are serialized by AuditPromptQueue: at most one is modal at a time, and the next +// is scheduled only after the active dialog has closed. An event delivered inside that dialog's +// nested event loop is queued and denied instead of opening a second dialog. Create and delete +// have no persistent grant to save, so a queued request for them becomes an informational denial: +// a Yes/No prompt would falsely imply that accepting it could authorize the operation or a later +// retry. 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& keys) { @@ -1758,28 +2001,60 @@ bool request_permission(AuditEventCategory category, const std::string& plugin_k if (s_permission_prompt_for_testing) return s_permission_prompt_for_testing(event_name, shown); - if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing() || PluginManager::instance().is_shutting_down() || + PluginManager::instance().is_plugin_load_cancelled(plugin_key)) return false; - if (wxIsMainThread()) - return prompt_for_targets(category, plugin_name, event_name, shown); + const bool on_gui_thread = wxIsMainThread() != 0; + // A queued create/delete prompt cannot grant anything: that path has no persistent permission. + // Show the inline Yes/No prompt only when it can be presented immediately on the GUI thread; + // any queued fallback is the OK-only informational denial, wherever the event originated. + AuditPromptRequest request; + request.kind = AuditPromptKind::RuntimeEvent; + request.category = category; + request.plugin_key = plugin_key; + request.plugin_name = plugin_name; + request.event_name = event_name; + request.by_event = by_event; + request.keys = keys; + request.shown = shown; + + AuditPromptQueue::Admission admission; if (is_create_delete_category(category)) { - GUI::wxGetApp().CallAfter([category, plugin_name, shown]() { - if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) - return; - show_permission_denied_dialog(category, plugin_name, shown); - }); + AuditPromptRequest denied = request; + denied.kind = AuditPromptKind::DeniedOperation; + admission = runtime_audit_prompts().admit_with_fallback(request, std::move(denied), on_gui_thread); + } else { + admission = runtime_audit_prompts().admit(request, on_gui_thread); + } + + if (admission == AuditPromptQueue::Admission::Duplicate || admission == AuditPromptQueue::Admission::Rejected) + return false; + + if (admission == AuditPromptQueue::Admission::Queued) { + // A prompt is already active (this event arrived inside its modal loop) or an earlier one + // is waiting. The current operation stays denied, as for an unanswered prompt; the + // queued prompt is shown once the active dialog has fully closed. + schedule_runtime_prompt_drain_checked(); return false; } - 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; + // ShowNow: no other audit prompt is active, so present this one synchronously. The event is + // approved only when the user says Yes to it and no unload cancelled it while it was up. + bool granted = false; + try { + const bool alive = !PluginManager::instance().is_shutting_down() && + !PluginManager::instance().is_plugin_load_cancelled(plugin_key); + granted = alive && show_queued_prompt(request); + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to show permission prompt for plugin=" << plugin_key + << ": " << ex.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to show permission prompt for plugin=" << plugin_key + << ": unknown exception"; + } + return finish_audit_prompt(request.completion, granted); } // Decides an event that no allowed root or running operation covers: a saved grant allows it, @@ -1838,6 +2113,8 @@ int decide_audited_event(PluginAuditManager& mgr, if (!request_permission(category, plugin_key, plugin_name, event_name, by_event, unresolved)) return report_denied(mgr, event_name, {false, "audit permission required"}); + // persist_grant re-reads the sidecar under the shared lock and handles the threading + // boolean; it notifies an existing Plugins dialog only when a write succeeded. if (threading_category || permission_list) { persist_grant(plugin_key, category, by_event, unresolved); } @@ -1902,6 +2179,189 @@ int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, A } // namespace PluginAuditDetail +AuditPromptQueue& runtime_prompt_queue_for_testing() { return PluginAuditDetail::runtime_audit_prompts(); } + +bool prompt_plugin_is_available(const AuditPromptPluginState& state, AuditPromptKind kind) +{ + if (state.shutting_down || state.load_cancelled) + return false; + + if (state.loaded || state.load_in_progress) + return true; + + // No worker is left to answer a load-time declaration after its load failed, and an + // informational denial was never an approval request. A runtime event has no worker: its + // denial may be what aborted the load, so an ordinary failure keeps it actionable. + return kind == AuditPromptKind::RuntimeEvent && state.load_failed; +} + +bool AuditPromptBucket::operator==(const AuditPromptBucket& other) const +{ + return category == other.category && targets == other.targets; +} + +void AuditPromptCompletion::resolve(bool value) +{ + std::lock_guard lock(m_mutex); + if (m_resolved) + return; + m_resolved = true; + m_promise.set_value(value); +} + +std::future AuditPromptCompletion::get_future() { return m_promise.get_future(); } + +AuditPromptQueue::Admission AuditPromptQueue::admit_synchronous(AuditPromptRequest request) +{ + std::lock_guard lock(m_mutex); + if (m_active || !m_pending.empty()) + return Admission::Rejected; + + m_active = std::move(request); + m_active_cancelled = false; + m_active_committing = false; + return Admission::ShowNow; +} + +AuditPromptQueue::Admission AuditPromptQueue::admit(AuditPromptRequest request, bool may_show_now) +{ + AuditPromptRequest queued = request; + return admit_with_fallback(std::move(request), std::move(queued), may_show_now); +} + +AuditPromptQueue::Admission AuditPromptQueue::admit_with_fallback(AuditPromptRequest immediate_request, + AuditPromptRequest queued_request, bool may_show_now) +{ + std::lock_guard lock(m_mutex); + + if (may_show_now && !m_active && m_pending.empty()) { + m_active = std::move(immediate_request); + m_active_cancelled = false; + m_active_committing = false; + return Admission::ShowNow; + } + + if (contains_locked(queued_request)) + return Admission::Duplicate; + + m_pending.push_back(std::move(queued_request)); + return Admission::Queued; +} + +std::optional AuditPromptQueue::take_next() +{ + std::lock_guard lock(m_mutex); + if (m_active || m_pending.empty()) + return std::nullopt; + + m_active = std::move(m_pending.front()); + m_pending.pop_front(); + m_active_cancelled = false; + m_active_committing = false; + return m_active; +} + +bool AuditPromptQueue::begin_commit() +{ + std::lock_guard lock(m_mutex); + if (!m_active || m_active_cancelled) + return false; + m_active_committing = true; + return true; +} + +bool AuditPromptQueue::complete() +{ + std::lock_guard lock(m_mutex); + const bool cancelled = m_active_cancelled; + m_active.reset(); + m_active_cancelled = false; + m_active_committing = false; + return cancelled; +} + +bool AuditPromptQueue::has_pending() const +{ + std::lock_guard lock(m_mutex); + return !m_pending.empty(); +} + +bool AuditPromptQueue::idle() const +{ + std::lock_guard lock(m_mutex); + return !m_active && m_pending.empty(); +} + +std::size_t AuditPromptQueue::pending_count() const +{ + std::lock_guard lock(m_mutex); + return m_pending.size(); +} + +void AuditPromptQueue::discard_all() +{ + const std::vector> completions = + discard_matching([](const AuditPromptRequest&) { return true; }); + + // Never resolve under the queue lock: the wake-up is another thread that may re-enter. + for (const auto& completion : completions) + completion->resolve(false); +} + +void AuditPromptQueue::discard_plugin(const std::string& plugin_key) +{ + const std::vector> completions = + discard_matching([&plugin_key](const AuditPromptRequest& request) { return request.plugin_key == plugin_key; }); + + for (const auto& completion : completions) + completion->resolve(false); +} + +std::vector> +AuditPromptQueue::discard_matching(const std::function& matches) +{ + std::vector> completions; + std::lock_guard lock(m_mutex); + + // Collect before erasing so the workers are released oldest first. + for (const AuditPromptRequest& request : m_pending) + if (matches(request) && request.completion) + completions.push_back(request.completion); + m_pending.erase(std::remove_if(m_pending.begin(), m_pending.end(), matches), m_pending.end()); + + // A commit already begun is left to finish, matching the active prompt's contract. + if (m_active && matches(*m_active) && !m_active_committing) { + m_active_cancelled = true; + if (m_active->completion) + completions.push_back(m_active->completion); + } + return completions; +} + +bool AuditPromptQueue::same_request(const AuditPromptRequest& a, const AuditPromptRequest& b) +{ + if (a.kind != b.kind || a.plugin_key != b.plugin_key) + return false; + + switch (a.kind) { + case AuditPromptKind::RuntimeEvent: + return a.category == b.category && a.by_event == b.by_event && a.keys == b.keys; + case AuditPromptKind::DeclaredPermissions: + return a.buckets == b.buckets; + case AuditPromptKind::DeniedOperation: + return a.category == b.category && a.shown == b.shown; + } + return false; +} + +bool AuditPromptQueue::contains_locked(const AuditPromptRequest& request) const +{ + if (m_active && same_request(*m_active, request)) + return true; + return std::any_of(m_pending.begin(), m_pending.end(), + [&request](const AuditPromptRequest& pending) { return same_request(pending, request); }); +} + bool PluginAuditManager::request_permissions(const std::string& plugin_key, const PluginPermissions& requested) { if (plugin_key.empty()) @@ -1932,11 +2392,7 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons // Per bucket, keep only the targets that no earlier grant already covers. Dropping these // before prompting keeps a repeated declaration from asking again for what is on disk. - struct MissingBucket { - AuditEventCategory category; - std::vector targets; - }; - std::vector missing_buckets; + std::vector missing_buckets; // A network target counts as granted when either network list covers it, matched the same // way the audit hook matches it (canonical scheme://host, bare host, legacy address tuple), @@ -1948,7 +2404,7 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons // remaining buckets verbatim. const bool tree_grant_bucket = category == AuditEventCategory::FsRead || category == AuditEventCategory::FsReadWrite; - MissingBucket bucket{category, {}}; + AuditPromptBucket bucket{category, {}}; for (const std::string& requested_target : requested_targets) { if (requested_target.empty()) continue; @@ -1985,86 +2441,117 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons if (missing_buckets.empty()) return true; - const auto build_message = [](const std::string& plugin_name, const std::vector& buckets) { - PermissionMessage message; - for (const MissingBucket& bucket : buckets) { - wxString targets; - for (const std::string& target : bucket.targets) - targets += wxString::FromUTF8(target.c_str()) + "\n"; + // A cancelled load no longer represents a live plugin: do not ask, and do not save a grant + // that the discarded load would otherwise leave behind. Re-checked after enqueue below. + if (PluginManager::instance().is_plugin_load_cancelled(plugin_key)) + return false; - if (!message.text.IsEmpty()) - message.text += "\n\n"; - PermissionMessage part = PluginAuditDetail::formatted_audit_message( - bucket.category, wxString::FromUTF8(plugin_name.c_str()), wxEmptyString, targets, bucket.targets.size()); - for (const auto& range : part.targets) - message.targets.emplace_back(message.text.length() + range.first, range.second); - message.text += part.text; - } - return message; - }; - - bool granted = false; if (PluginAuditDetail::s_permission_message_prompt_for_testing) { // Tests run without a wxApp to host the dialog: hand the seam the message it would show. - wxString message = build_message(descriptor.name, missing_buckets).text; - append_permission_dialog_tip(message); - granted = PluginAuditDetail::s_permission_message_prompt_for_testing(message.utf8_string()); - } else if (wxTheApp == nullptr || GUI::wxGetApp().is_closing()) { - return false; - } else if (wxIsMainThread()) { - granted = PluginAuditDetail::prompt_for_permission_message(build_message(descriptor.name, missing_buckets)); - } else { - auto result = std::make_shared>(); - auto future = result->get_future(); - GUI::wxGetApp().CallAfter([result, plugin_name = descriptor.name, missing_buckets, build_message]() { - result->set_value(PluginAuditDetail::prompt_for_permission_message(build_message(plugin_name, missing_buckets))); - }); - granted = future.get(); - } - - if (!granted) - return false; - - // The dialog can stay open while another grant is persisted; take the shared lock and re-read - // before saving so this request adds to the current state instead of replacing it. - bool persisted = false; - { - std::lock_guard state_lock(install_state_mutex()); - PluginInstallState latest_state; - InstallStateReadStatus latest_status = - read_install_state_status(boost::filesystem::path(descriptor.plugin_root), latest_state); - // A malformed file is never replaced. A sidecar that was readable when prompting started - // must not be recreated if it disappears meanwhile: that is lost state, not a new install. - // Only a sidecar absent at both reads is seeded. - if (latest_status == InstallStateReadStatus::Unreadable) - return false; - if (latest_status == InstallStateReadStatus::Absent && state_status == InstallStateReadStatus::Readable) - return false; - state = std::move(latest_state); - - PluginAuditDetail::seed_install_metadata(descriptor, state); - - for (const MissingBucket& bucket : missing_buckets) { - if (bucket.category == AuditEventCategory::Threading) { - state.permissions.threading = true; - continue; - } - std::vector* permission_list = - PluginAuditDetail::permission_list_for(bucket.category, /*by_event=*/false, state.permissions); - if (!permission_list) - continue; - for (const std::string& target : bucket.targets) - if (std::find(permission_list->begin(), permission_list->end(), target) == permission_list->end()) - permission_list->push_back(target); + try { + PermissionMessage message = PluginAuditDetail::build_permission_message(descriptor.name, missing_buckets); + append_permission_dialog_tip(message.text); + if (!PluginAuditDetail::s_permission_message_prompt_for_testing(message.text.utf8_string())) + return false; + return PluginAuditDetail::persist_declared_permissions(plugin_key, missing_buckets, + state_status == InstallStateReadStatus::Readable); + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to handle permission test seam for plugin=" << plugin_key + << ": " << ex.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to handle permission test seam for plugin=" << plugin_key + << ": unknown exception"; } - - persisted = write_install_state(boost::filesystem::path(descriptor.plugin_root), state); + return false; } - // Only a stored grant changes what the dialog would read back; a failed write changed nothing. - if (persisted) - post_permission_changed_notification(plugin_key); - return persisted; + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing() || PluginManager::instance().is_shutting_down() || + PluginManager::instance().is_plugin_load_cancelled(plugin_key)) + return false; + + const bool on_gui_thread = wxIsMainThread() != 0; + + const bool sidecar_was_readable = state_status == InstallStateReadStatus::Readable; + + AuditPromptRequest request; + request.kind = AuditPromptKind::DeclaredPermissions; + request.plugin_key = plugin_key; + request.plugin_name = descriptor.name; + request.buckets = missing_buckets; + request.sidecar_was_readable = sidecar_was_readable; + + // A load worker blocks on this completion. A GUI-thread caller cannot wait inside another + // modal dialog, so it is admitted synchronously or rejected without leaving a deferred prompt + // that could later grant a permission for a load that already failed. + std::shared_ptr completion; + std::future future; + AuditPromptQueue::Admission admission; + if (on_gui_thread) { + admission = PluginAuditDetail::runtime_audit_prompts().admit_synchronous(std::move(request)); + } else { + completion = std::make_shared(); + future = completion->get_future(); + request.completion = completion; + admission = PluginAuditDetail::runtime_audit_prompts().admit(std::move(request), /*may_show_now=*/false); + } + + if (admission == AuditPromptQueue::Admission::Duplicate || admission == AuditPromptQueue::Admission::Rejected) + return false; + + if (admission == AuditPromptQueue::Admission::ShowNow) { + bool satisfied = false; + try { + const bool alive = !PluginManager::instance().is_shutting_down() && + !PluginManager::instance().is_plugin_load_cancelled(plugin_key); + const bool granted = + alive && PluginAuditDetail::prompt_for_permission_message( + PluginAuditDetail::build_permission_message(descriptor.name, missing_buckets)); + satisfied = granted && !PluginManager::instance().is_shutting_down() && + !PluginManager::instance().is_plugin_load_cancelled(plugin_key) && + PluginAuditDetail::runtime_audit_prompts().begin_commit(); + if (satisfied) { + satisfied = PluginAuditDetail::persist_declared_permissions( + plugin_key, missing_buckets, sidecar_was_readable); + if (!satisfied) + BOOST_LOG_TRIVIAL(warning) << "[AUDIT PROMPT] Failed to store declared permissions for plugin=" + << plugin_key; + } + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to handle declared permissions for plugin=" << plugin_key + << ": " << ex.what(); + satisfied = false; + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to handle declared permissions for plugin=" << plugin_key + << ": unknown exception"; + satisfied = false; + } + return PluginAuditDetail::finish_audit_prompt(nullptr, satisfied); + } + + // Queued: only a load worker reaches this branch. The GUI callback will answer, persist, and + // release the worker. + if (!PluginAuditDetail::schedule_runtime_prompt_drain_checked()) + return false; + + // A load that began before shutdown or was cancelled by unload must not wait forever on a + // prompt that will not open. Re-check after enqueue so a discard racing this admission cannot + // strand the worker, and a request admitted after unload's discard still learns it is dead. + if (PluginManager::instance().is_shutting_down() || + PluginManager::instance().is_plugin_load_cancelled(plugin_key)) { + PluginAuditDetail::discard_runtime_prompts_for(plugin_key); + return false; + } + + try { + return future.get(); + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Permission wait failed for plugin=" << plugin_key << ": " << ex.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Permission wait failed for plugin=" << plugin_key + << ": unknown exception"; + } + PluginAuditDetail::discard_runtime_prompts_for(plugin_key); + return false; } void PluginAuditManager::record_root_frame() @@ -2165,6 +2652,16 @@ void PluginAuditManager::set_permission_message_prompt_for_testing(PermissionMes PluginAuditDetail::s_permission_message_prompt_for_testing = std::move(prompt); } +void PluginAuditManager::discard_pending_permission_prompts() +{ + PluginAuditDetail::discard_runtime_prompts(); +} + +void PluginAuditManager::discard_pending_permission_prompts_for(const std::string& plugin_key) +{ + PluginAuditDetail::discard_runtime_prompts_for(plugin_key); +} + int PluginAuditManager::audit_hook(const char* event, PyObject* args, void* user_data) { auto* mgr = static_cast(user_data); diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index ba369a3f42..de3343ff4f 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -4,8 +4,13 @@ // Via pybind11 so this file requests the same python3xx.lib as everything else. #include #include +#include +#include #include +#include +#include #include +#include #include #include @@ -144,11 +149,13 @@ public: AuditDecision check_open(const std::string& path, const std::string& mode); // Ask the user to grant the requested permissions. The request may originate on a plugin - // load worker, so the implementation marshals the modal dialog to the wx main thread. - // Targets already persisted for the plugin are not shown or asked for again. Returns true - // only when every missing target was granted and persisted; denial aborts the plugin load - // without adding a permission. A plugin with full access stored in its sidecar is never - // prompted: the declaration is accepted and no grant is added. + // load worker, so it goes through the same serialized prompt queue as runtime events; a worker + // waits for the answer, while a GUI-thread caller only shows it when no other prompt is active + // and is otherwise rejected without queueing a deferred declaration. Targets already persisted + // for the plugin are not shown or asked for again. Returns true only when every missing target + // was granted and persisted; denial aborts the plugin load without adding a permission. A + // plugin with full access stored in its sidecar is never prompted: the declaration is accepted + // and no grant is added. // // A filesystem target may name a directory tree: a trailing "/*" (e.g. "/path/to/folder/*") // grants the folder itself and every path beneath it, at any depth. "*" is the only wildcard @@ -226,6 +233,13 @@ public: using PermissionMessagePrompt = std::function; static void set_permission_message_prompt_for_testing(PermissionMessagePrompt prompt); + // Drops runtime audit prompts that have not been shown yet, and cancels any blocked worker + // waiting on one (including the prompt currently on screen: its late answer is ignored). Called + // when the application shuts down so a queued prompt cannot open after the GUI is gone, and + // when a plugin is unloaded or its in-flight load is cancelled so its prompts cannot outlive it. + static void discard_pending_permission_prompts(); + static void discard_pending_permission_prompts_for(const std::string& plugin_key); + bool verbose_events = true; private: @@ -288,6 +302,164 @@ private: std::vector m_previous_root_frames; }; +// What a queued prompt asks the user. A runtime event and a permission declaration can both grant +// what they show; an informational denial cannot, so it has no Yes/No choice. +enum class AuditPromptKind { + RuntimeEvent, + DeclaredPermissions, + DeniedOperation, +}; + +// The plugin lifecycle facts the prompt drain consults. Plain data so the lifetime decision is +// testable without a GUI or a live plugin system. +struct AuditPromptPluginState +{ + bool loaded = false; + bool load_in_progress = false; + bool load_cancelled = false; + bool load_failed = false; + bool shutting_down = false; +}; + +// True when a queued prompt may still be shown and its answer persisted. An ordinary load +// failure leaves a runtime prompt actionable: the event that was denied is what the user can +// approve now, and the saved grant lets a retry load succeed. Explicit cancellation and unload, +// as well as application shutdown, make a prompt ineligible; those paths also discard its queue +// entries. +bool prompt_plugin_is_available(const AuditPromptPluginState& state, AuditPromptKind kind); + +// One permission bucket of a load-time declaration. Kept plain (no wx types) so the queue can be +// owned by production code that outlives static destruction. +struct AuditPromptBucket +{ + AuditEventCategory category = AuditEventCategory::None; + std::vector targets; + + bool operator==(const AuditPromptBucket& other) const; +}; + +// Resolves a blocked load worker exactly once. The queue may cancel a request from another thread +// (plugin unload, shutdown) while the GUI thread is still showing its dialog; the second resolve +// must be a no-op. Held by shared_ptr so a request copy and the queue's active slot share it. +struct AuditPromptCompletion +{ + void resolve(bool value); + + std::future get_future(); + +private: + std::mutex m_mutex; + std::promise m_promise; + bool m_resolved = false; +}; + +// One audit decision awaiting a user answer. `keys` is what a Yes persists; `shown` is what the +// dialog lists (empty for an event that is granted by name, with no target to show). +struct AuditPromptRequest +{ + AuditPromptKind kind = AuditPromptKind::RuntimeEvent; + AuditEventCategory category = AuditEventCategory::None; + std::string plugin_key; + std::string plugin_name; + std::string event_name; + bool by_event = false; + std::vector keys; + std::vector shown; + // DeclaredPermissions only: the missing buckets the combined dialog lists. + std::vector buckets; + // DeclaredPermissions only: whether the sidecar was readable when the declaration was read. + // The queued write must not recreate a sidecar that was readable then but has since + // disappeared; only one absent at both reads is treated as a new install to seed. + bool sidecar_was_readable = false; + // Set only when a worker is blocked waiting for the answer. + std::shared_ptr completion; +}; + +// Serializes audit prompts on the GUI thread. At most one request is active: the next one is +// handed out by take_next() only after the previous dialog has returned from ShowModal(), so a +// modal dialog's nested event loop cannot open another audit prompt. +// +// Thread-safe: audit events enqueue from plugin worker threads, the GUI thread drains. Requests +// are never merged unless they are exactly equivalent, so coalescing cannot widen a grant. +class AuditPromptQueue +{ +public: + enum class Admission { + ShowNow, // idle and allowed to prompt here: present this request, then complete() + Queued, // a prompt is active or waiting: the current audit event stays denied + Duplicate, // an equivalent request is already active or waiting: this one is dropped + Rejected // a synchronous-only caller found the queue busy: nothing was stored + }; + + // Presents a request synchronously only when the queue is idle. Busy callers are rejected + // atomically instead of leaving a deferred prompt behind: used by GUI-thread callers whose + // operation is already being denied and cannot wait for a later Yes. + Admission admit_synchronous(AuditPromptRequest request); + + // `may_show_now` is true only on the GUI thread: it lets an idle queue hand the request back + // for a synchronous prompt instead of queueing it for a later GUI callback. + Admission admit(AuditPromptRequest request, bool may_show_now); + + // For a create/delete request: show the immediate Yes/No prompt when idle on the GUI thread, + // but queue `queued_request` (an OK-only informational denial) when that is not possible. The + // kind cannot be switched after admission, so the fallback is chosen under the queue lock. + Admission admit_with_fallback(AuditPromptRequest immediate_request, AuditPromptRequest queued_request, + bool may_show_now); + + // Claims the oldest queued request when no prompt is active, and marks it active. + std::optional take_next(); + + // Claims the active answer for persistence. Cancellation and commit are mutually exclusive: + // once this returns true, discard_all()/discard_plugin() leave the request alone so a user's + // accepted answer cannot be dropped midway through the sidecar write. A request already + // cancelled (shutdown or unload won the race) returns false and must not be persisted. + bool begin_commit(); + + // Marks the active request done. Returns true when it was cancelled while its dialog was up, + // so the caller must not persist an accepted grant. Idempotent. + bool complete(); + + bool has_pending() const; + + bool idle() const; + + std::size_t pending_count() const; + + // Drops every queued request and cancels any blocked worker. An active prompt stays on screen + // (it may be mid-modal), but its completion is released now and its late answer must not be + // persisted. A commit already begun is left to finish. Used on application shutdown. + void discard_all(); + + // Drops queued requests for one plugin and cancels a blocked worker of that plugin. An active + // prompt is cancelled but stays on screen until its dialog returns, unless its commit already + // started. Used when a plugin is unloaded or removed. + void discard_plugin(const std::string& plugin_key); + +private: + // Equality only over what a Yes would grant, plus the plugin it is granted to. Distinct + // categories, plugins, targets, or event grants are never considered equivalent. + static bool same_request(const AuditPromptRequest& a, const AuditPromptRequest& b); + + bool contains_locked(const AuditPromptRequest& request) const; + + // Drops queued requests matching `matches` and cancels the active request when it matches and + // its commit has not begun. Returns the blocked workers' completions in FIFO order. The caller + // resolves them after this returns, never under m_mutex: the wake-up can re-enter the queue. + std::vector> + discard_matching(const std::function& matches); + + mutable std::mutex m_mutex; + std::deque m_pending; + std::optional m_active; + bool m_active_cancelled = false; + bool m_active_committing = false; +}; + +// The process-wide queue the drain and the explicit discard calls use. Exposed so a test can put +// a request behind an active prompt and then exercise PluginManager's unload/cancel wiring +// against the real queue. Production reaches it only through PluginAuditManager. +AuditPromptQueue& runtime_prompt_queue_for_testing(); + } // namespace Slic3r #endif // slic3r_PluginAuditManager_hpp_ diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index 7425f2d255..90813794af 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -142,7 +142,13 @@ bool PluginManager::initialize() return true; } -void PluginManager::set_shutting_down() { m_shutting_down.store(true, std::memory_order_release); } +void PluginManager::set_shutting_down() +{ + m_shutting_down.store(true, std::memory_order_release); + // The GUI may already be closing: drop audit prompts that have not been shown yet rather than + // letting a queued dialog open after shutdown has begun. + PluginAuditManager::discard_pending_permission_prompts(); +} void PluginManager::shutdown() { @@ -154,6 +160,11 @@ void PluginManager::shutdown() return; } + // Set the shutdown flag before releasing any blocked permission prompt: a worker that fails + // because of that release must see the cancellation and not record a spurious load error or + // disable the package. + set_shutting_down(); + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": PluginManager shutdown enter"; // Detach the libslic3r hooks first so nothing dispatches into Python while (or after) plugins @@ -161,9 +172,6 @@ void PluginManager::shutdown() // the remaining hook seams retain their existing shutdown requirements. plugin_hooks::uninstall(); - // Reject new plugin loads before we drain. - set_shutting_down(); - std::string wait_error; if (!wait_for_discovery(std::chrono::milliseconds::max(), wait_error) && !wait_error.empty()) BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Plugin discovery did not finish cleanly during shutdown: " << wait_error; @@ -431,6 +439,12 @@ void PluginManager::unload_and_erase_if(const std::function if (loaded_entry_found) continue; + // A removed package can no longer retry the load a queued prompt was waiting for. + // Loaded entries were unloaded above; not-loaded ones are erased here. + for (const Plugin& plugin : m_plugins) + if (should_remove(plugin)) + m_failed_loads.erase(plugin.descriptor.plugin_key); + m_plugins.erase(std::remove_if(m_plugins.begin(), m_plugins.end(), should_remove), m_plugins.end()); if (after_erase_locked) after_erase_locked(); @@ -703,6 +717,12 @@ bool PluginManager::is_plugin_load_in_progress(const std::string& plugin_key) co return m_load_in_progress.count(plugin_key) > 0; } +bool PluginManager::is_plugin_load_cancelled(const std::string& plugin_key) const +{ + std::lock_guard lock(m_mutex); + return is_plugin_load_cancelled_locked(plugin_key); +} + void PluginManager::wait_for_all_plugin_loads() const { std::unique_lock lock(m_mutex); @@ -744,6 +764,12 @@ std::string PluginManager::get_plugin_load_error(const std::string& plugin_key) return it == m_load_errors.end() ? std::string{} : it->second; } +bool PluginManager::is_plugin_load_failed(const std::string& plugin_key) const +{ + std::lock_guard lock(m_mutex); + return find_plugin_locked(plugin_key) != nullptr && m_failed_loads.count(plugin_key) > 0; +} + bool PluginManager::cancel_plugin_load(const std::string& plugin_key) { bool cancelled = false; @@ -752,6 +778,13 @@ bool PluginManager::cancel_plugin_load(const std::string& plugin_key) cancelled = cancel_plugin_load_locked(plugin_key); } + // A queued or active audit prompt for this load would keep its worker blocked on an answer + // that can no longer authorize anything. Mark the load cancelled first, then discard outside + // m_mutex, matching unload_plugin(): a prompt whose answer has not begun committing loses to + // the cancellation, while an in-progress commit stays atomic. + if (cancelled) + PluginAuditManager::discard_pending_permission_prompts_for(plugin_key); + notify_plugin_load_state_changed(cancelled); return cancelled; } @@ -763,6 +796,7 @@ bool PluginManager::cancel_plugin_load_locked(const std::string& plugin_key) m_cancelled.insert(plugin_key); m_load_errors.erase(plugin_key); + m_failed_loads.erase(plugin_key); return true; } @@ -780,7 +814,17 @@ void PluginManager::release_load_slot(const std::string& plugin_key) { std::lock_guard lock(m_mutex); changed = m_load_in_progress.erase(plugin_key) > 0; - m_cancelled.erase(plugin_key); + + const bool cancelled = m_cancelled.erase(plugin_key) > 0; + const Plugin* plugin = find_plugin_locked(plugin_key); + const bool loaded = plugin != nullptr && plugin->is_loaded(); + // Record an ordinary failure, but never a cancelled or successful load, and never one for + // a package that was removed while the worker unwound. Only the ordinary failure leaves + // its queued runtime prompts actionable for approval and retry. + if (cancelled || loaded || plugin == nullptr || m_load_errors.count(plugin_key) == 0) + m_failed_loads.erase(plugin_key); + else + m_failed_loads.insert(plugin_key); } notify_plugin_load_state_changed(changed); } @@ -887,6 +931,7 @@ void PluginManager::load_plugin(const std::string& plugin_key, bool skip_deps, s if (exists && !invalid && !already_loaded && !load_in_progress && !shutting_down) { m_load_in_progress.insert(plugin_id); m_load_errors.erase(plugin_id); + m_failed_loads.erase(plugin_id); load_slot_claimed = true; } } @@ -1001,8 +1046,18 @@ void PluginManager::load_plugin_impl(const std::string& plugin_key, bool skip_de std::string error; bool registration_failed = false; if (!plugin_loader::load(descriptor, skip_deps, capabilities_to_enable, registry_precheck, plugin, error, ®istration_failed)) { - if (error == LOAD_CANCELLED) + // A permission prompt denied because the load was cancelled (unload or shutdown) surfaces + // here as an ordinary registration/permission failure. Do not disable the package or record + // an error for that: a genuine denial still follows the normal failure path below. + bool load_cancelled = m_shutting_down.load(std::memory_order_acquire); + if (!load_cancelled) { + std::lock_guard lock(m_mutex); + load_cancelled = is_plugin_load_cancelled_locked(plugin_key); + } + if (error == LOAD_CANCELLED || load_cancelled) { + BOOST_LOG_TRIVIAL(info) << "[load_plugin_impl] CANCELLED plugin=" << plugin_key; return; // cancelled: nothing materialized survives, and no error is recorded + } if (registration_failed) mark_plugin_install_state_disabled(plugin_key); fail(std::move(error)); @@ -1085,6 +1140,9 @@ bool PluginManager::unload_plugin(const std::string& plugin_key) // Cancel any in-progress load for this plugin so its worker discards the result. cancelled = cancel_plugin_load_locked(plugin_key); + // An explicit unload also revokes the "ordinary failure" state, so a prompt admitted + // after the queue discard below can never be shown for the unloaded plugin. + m_failed_loads.erase(plugin_key); Plugin* plugin = find_plugin_locked(plugin_key); if (plugin != nullptr && plugin->is_loaded()) { @@ -1100,6 +1158,11 @@ bool PluginManager::unload_plugin(const std::string& plugin_key) } } + // Queued audit prompts belong to a plugin that is going away: cancel any blocked load worker + // and keep a late answer from persisting. Do this after marking the load cancelled so a worker + // released by the cancellation cannot take it as approval. + PluginAuditManager::discard_pending_permission_prompts_for(plugin_key); + if (!found) { notify_plugin_load_state_changed(cancelled); return true; @@ -1147,8 +1210,10 @@ void PluginManager::unload_all_plugins() // Bulk shutdown intentionally skips the normal unload notification path, but resources owned // by GUI subscribers still need to be torn down before the interpreter is finalized. - for (const std::string& key : removed_keys) + for (const std::string& key : removed_keys) { + PluginAuditManager::discard_pending_permission_prompts_for(key); run_on_unload_callbacks(key); + } // Broadcast cancellation to every plugin before waiting. This keeps bulk unload from // starving a later plugin while an earlier plugin uses the full cancellation grace period. @@ -1573,9 +1638,15 @@ bool PluginManager::install_plugin(const boost::filesystem::path& filepath, Plug // Every successful install may have replaced executable plugin code. Revoke any permissions // associated with the previous package so the newly installed version must request them again. - if (!plugin_descriptor.plugin_key.empty()) + if (!plugin_descriptor.plugin_key.empty()) { revoke_plugin_permissions(plugin_descriptor.plugin_key); + // A prompt queued by the replaced code must not grant a permission the new code never + // requested: an installed package starts its lifecycle from a clean failure state. + std::lock_guard lock(m_mutex); + m_failed_loads.erase(plugin_descriptor.plugin_key); + } + if (!plugin_descriptor.plugin_key.empty()) clear_plugin_error(plugin_descriptor.plugin_key); @@ -2124,6 +2195,9 @@ bool PluginManager::keep_installed_plugin_as_local(const PluginDescriptor& plugi entry->descriptor.plugin_key = new_key; entry->descriptor.cloud.reset(); entry->descriptor.clear_error(); + // The package identity changed, so neither key may keep an old failure's prompt alive. + m_failed_loads.erase(old_key); + m_failed_loads.erase(new_key); for (const auto& capability : entry->capabilities) { if (capability) @@ -2168,6 +2242,7 @@ bool PluginManager::finalize_cloud_plugin_removal(const PluginDescriptor& plugin { std::lock_guard lock(m_mutex); + m_failed_loads.erase(plugin.plugin_key); m_plugins.erase(std::remove_if(m_plugins.begin(), m_plugins.end(), [&plugin](const Plugin& entry) { return entry.descriptor.plugin_key == plugin.plugin_key; }), m_plugins.end()); diff --git a/src/slic3r/plugin/PluginManager.hpp b/src/slic3r/plugin/PluginManager.hpp index 58db6a996d..d0c62e38a3 100644 --- a/src/slic3r/plugin/PluginManager.hpp +++ b/src/slic3r/plugin/PluginManager.hpp @@ -233,11 +233,22 @@ public: void unload_cloud_plugins(); bool is_plugin_loaded(const std::string& plugin_key) const; bool is_plugin_load_in_progress(const std::string& plugin_key) const; + // True when an in-flight load has been cancelled but its worker has not released the slot yet. + // Such a load stays "in progress" for wait_for_all_plugin_loads(), but it is no longer treated + // as a live plugin when cancellation is observed. A dialog racing with cancellation may still + // appear or remain open, but its answer is discarded unless the commit already won. + bool is_plugin_load_cancelled(const std::string& plugin_key) const; void wait_for_all_plugin_loads() const; bool wait_for_all_plugin_loads(std::chrono::milliseconds timeout) const; // false on timeout bool wait_for_plugin_load(const std::string& plugin_key, std::chrono::milliseconds timeout, std::string& error) const; bool cancel_plugin_load(const std::string& plugin_key); std::string get_plugin_load_error(const std::string& plugin_key) const; + // True when a discovered plugin's most recent load attempt failed for an ordinary reason. + // Cancelling the load, starting another one, unloading the plugin, installing it again, or + // removing its package clears it. A discovery rescan leaves it alone, because a rescan does + // not prove the executable package changed. A queued runtime prompt stays actionable in this + // state, because approving it saves the grant that lets the retry load succeed. + bool is_plugin_load_failed(const std::string& plugin_key) const; void set_capability_enabled(const PluginCapabilityId& id, bool enabled); @@ -372,6 +383,9 @@ private: // wait_for_all_plugin_loads() return early, after which shutdown() unloads everything and // GUI_App finalizes the interpreter — leaving the live worker to run Python against it. std::unordered_set m_cancelled; + // Keys whose most recent load attempt failed without being cancelled. Kept separately from + // m_load_errors so clearing it never changes the error a load waiter reads. + std::unordered_set m_failed_loads; std::map m_load_errors; mutable std::condition_variable m_load_cv; diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 70d03389d2..634c20f444 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -33,13 +33,16 @@ #include #include +#include #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -80,6 +83,544 @@ std::string read_text_file(const fs::path& path) } // namespace +namespace { + +AuditPromptRequest prompt_request(const std::string& plugin_key, AuditEventCategory category, + std::vector targets) +{ + AuditPromptRequest request; + request.category = category; + request.plugin_key = plugin_key; + request.plugin_name = plugin_key; + request.event_name = "open"; + request.keys = std::move(targets); + request.shown = request.keys; + return request; +} + +AuditPromptBucket bucket(AuditEventCategory category, std::vector targets) +{ + return {category, std::move(targets)}; +} + +// A load-time declaration: one combined prompt over the buckets no earlier grant covers. A load +// worker may be blocked on its answer. +AuditPromptRequest declared_request(const std::string& plugin_key, std::vector buckets) +{ + AuditPromptRequest request; + request.kind = AuditPromptKind::DeclaredPermissions; + request.plugin_key = plugin_key; + request.plugin_name = plugin_key; + request.buckets = std::move(buckets); + return request; +} + +// The informational denial shown for a create/delete event raised off the GUI thread. Production +// builds it by copying the runtime request it denies and changing only the kind, so it carries the +// same keys; it has no Yes/No choice and no worker waiting on it. +AuditPromptRequest denied_request(const std::string& plugin_key, AuditEventCategory category, + std::vector targets) +{ + AuditPromptRequest request = prompt_request(plugin_key, category, std::move(targets)); + request.event_name = category == AuditEventCategory::FsDelete ? "os.remove" : "open"; + request.kind = AuditPromptKind::DeniedOperation; + return request; +} + +// A request plus the completion a blocked load worker waits on, and the future that worker holds. +struct WaitingRequest +{ + AuditPromptRequest request; + std::shared_ptr completion; + std::future future; +}; + +WaitingRequest waiting(AuditPromptRequest request) +{ + auto completion = std::make_shared(); + std::future future = completion->get_future(); + request.completion = completion; + return {std::move(request), std::move(completion), std::move(future)}; +} + +bool settled(std::future& future) +{ + return future.wait_for(std::chrono::milliseconds(0)) == std::future_status::ready; +} + +// The drain and the unload/cancel wiring use a process-wide queue. A test that enqueues into it +// directly must leave it empty even when an assertion aborts the case. +struct ScopedRuntimePromptQueue +{ + AuditPromptQueue& queue = runtime_prompt_queue_for_testing(); + + ScopedRuntimePromptQueue() { queue.discard_all(); } + ~ScopedRuntimePromptQueue() { queue.discard_all(); } +}; + +// The same snapshot drain_runtime_prompts() builds for the availability check. +AuditPromptPluginState prompt_plugin_state(const std::string& plugin_key) +{ + PluginManager& manager = PluginManager::instance(); + AuditPromptPluginState state; + state.loaded = manager.is_plugin_loaded(plugin_key); + state.load_in_progress = manager.is_plugin_load_in_progress(plugin_key); + state.load_cancelled = manager.is_plugin_load_cancelled(plugin_key); + state.load_failed = manager.is_plugin_load_failed(plugin_key); + state.shutting_down = manager.is_shutting_down(); + return state; +} + +} // namespace + +TEST_CASE("A runtime audit prompt is queued while another one is active", "[audit][Python]") +{ + AuditPromptQueue queue; + + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::ShowNow); + // Still inside the first dialog's modal loop: a GUI-thread event must queue, not nest. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/b"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::Queued); + // The request already on screen is not queued a second time. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::Duplicate); + CHECK(queue.pending_count() == 1); + CHECK_FALSE(queue.take_next().has_value()); + + queue.complete(); + std::optional next = queue.take_next(); + REQUIRE(next.has_value()); + CHECK(next->keys == std::vector{"/b"}); + CHECK_FALSE(queue.take_next().has_value()); + CHECK_FALSE(queue.idle()); + + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("Only exactly equivalent pending audit prompts are coalesced", "[audit][Python]") +{ + AuditPromptQueue queue; + + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Duplicate); + // A different category, plugin, or target is a distinct grant and never merges. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsReadWrite, {"/a"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(prompt_request("other_plugin", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/b"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.pending_count() == 4); +} + +TEST_CASE("Queued audit prompts are handed out in arrival order", "[audit][Python]") +{ + AuditPromptQueue queue; + + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/b"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + + std::optional first = queue.take_next(); + REQUIRE(first.has_value()); + CHECK(first->keys == std::vector{"/a"}); + queue.complete(); + + std::optional second = queue.take_next(); + REQUIRE(second.has_value()); + CHECK(second->keys == std::vector{"/b"}); + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("Discarding drops queued audit prompts but leaves the active one", "[audit][Python]") +{ + AuditPromptQueue queue; + + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::ShowNow); + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/b"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + + queue.discard_all(); + CHECK_FALSE(queue.has_pending()); + queue.complete(); + CHECK_FALSE(queue.take_next().has_value()); + CHECK(queue.idle()); +} + +TEST_CASE("Unloading a plugin drops only that plugin's queued audit prompts", "[audit][Python]") +{ + AuditPromptQueue queue; + + CHECK(queue.admit(prompt_request("unloaded", AuditEventCategory::FsRead, {"/a"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(prompt_request("kept", AuditEventCategory::FsRead, {"/b"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(prompt_request("unloaded", AuditEventCategory::FsRead, {"/c"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + + queue.discard_plugin("unloaded"); + + std::optional next = queue.take_next(); + REQUIRE(next.has_value()); + CHECK(next->plugin_key == "kept"); + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("Runtime, declared, and informational audit prompts are serialized in arrival order", "[audit][Python]") +{ + AuditPromptQueue queue; + + // A GUI-thread event arrives first and is on screen; the declaration and the informational + // denial that follow both have to wait for it, whatever their kind. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/runtime"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::ShowNow); + CHECK(queue.admit(declared_request("plugin", {bucket(AuditEventCategory::Http, {"https://api.example.com"})}), + /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); + // A create/delete event falls back to its informational denial while a dialog is up. + CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsDelete, {"/deleted"}), + denied_request("plugin", AuditEventCategory::FsDelete, {"/deleted"}), + /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); + CHECK(queue.pending_count() == 2); + + // At most one prompt is on screen: nothing is handed out until the active dialog returns. + CHECK_FALSE(queue.take_next().has_value()); + + queue.complete(); + std::optional declared = queue.take_next(); + REQUIRE(declared.has_value()); + CHECK(declared->kind == AuditPromptKind::DeclaredPermissions); + REQUIRE(declared->buckets.size() == 1); + CHECK(declared->buckets.front().category == AuditEventCategory::Http); + const std::vector declared_targets{"https://api.example.com"}; + CHECK(declared->buckets.front().targets == declared_targets); + // The declaration's dialog is up now: the informational prompt still waits behind it. + CHECK_FALSE(queue.take_next().has_value()); + CHECK(queue.pending_count() == 1); + queue.complete(); + + std::optional denied = queue.take_next(); + REQUIRE(denied.has_value()); + CHECK(denied->kind == AuditPromptKind::DeniedOperation); + CHECK(denied->category == AuditEventCategory::FsDelete); + const std::vector denied_targets{"/deleted"}; + CHECK(denied->shown == denied_targets); + // A denial copies the runtime request it denies, so its keys are present even though the + // category grants nothing via a denial, and no worker waits on it. + CHECK(denied->keys == denied_targets); + CHECK(denied->completion == nullptr); + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("Only exactly equivalent declared permission prompts are coalesced", "[audit][Python]") +{ + AuditPromptQueue queue; + + const AuditPromptRequest declaration = declared_request("plugin", {bucket(AuditEventCategory::FsRead, {"/a"})}); + CHECK(queue.admit(declaration, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(declaration, /*may_show_now=*/false) == AuditPromptQueue::Admission::Duplicate); + // Same targets for another plugin is a different grant. + CHECK(queue.admit(declared_request("other_plugin", {bucket(AuditEventCategory::FsRead, {"/a"})}), + /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + // The same plugin asking for another category or another target is a different grant. + CHECK(queue.admit(declared_request("plugin", {bucket(AuditEventCategory::FsReadWrite, {"/a"})}), + /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(declared_request("plugin", {bucket(AuditEventCategory::FsRead, {"/b"})}), + /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(queue.pending_count() == 4); + + // The declaration already on screen is not queued a second time either. + AuditPromptQueue shown; + CHECK(shown.admit(declaration, /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + CHECK(shown.admit(declaration, /*may_show_now=*/true) == AuditPromptQueue::Admission::Duplicate); + CHECK(shown.pending_count() == 0); + CHECK_FALSE(shown.idle()); +} + +TEST_CASE("An informational denial never coalesces with a runtime prompt for the same operation", "[audit][Python]") +{ + AuditPromptQueue queue; + + // A GUI-thread create is a real Yes/No prompt; the informational denial of a worker create + // must not be mistaken for a duplicate of it and dropped unseen. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::ShowNow); + CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.pending_count() == 1); + + // Two informational denials of the same operation show nothing new the second time. + CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Duplicate); + // Another target, another category, or another plugin is a separate denial to show. + CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsCreate, {"/other"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsDelete, {"/new"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(denied_request("other_plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.pending_count() == 4); +} + +TEST_CASE("A create/delete prompt falls back to an informational denial when another prompt is up", "[audit][Python]") +{ + AuditPromptQueue queue; + + // Idle GUI thread: the immediate Yes/No prompt is shown, so a create can really be approved. + CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), + denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), + /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + CHECK(queue.pending_count() == 0); + + // Its dialog is up, so the same create cannot be shown as a second Yes/No prompt; it queues as + // the informational denial that matches what the user can actually do. + CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), + denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), + /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); + // The queued denial is not a duplicate of the active Yes/No prompt, and is not queued twice. + CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), + denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), + /*may_show_now=*/true) == AuditPromptQueue::Admission::Duplicate); + CHECK(queue.pending_count() == 1); + + queue.complete(); + std::optional queued = queue.take_next(); + REQUIRE(queued.has_value()); + CHECK(queued->kind == AuditPromptKind::DeniedOperation); + CHECK(queued->category == AuditEventCategory::FsCreate); + const std::vector expected{"/new"}; + CHECK(queued->shown == expected); + CHECK(queued->keys == expected); + CHECK(queued->completion == nullptr); + queue.complete(); + CHECK(queue.idle()); + + // A worker create also gets the informational denial while the queue is idle: it cannot + // authorize the operation, so showing a Yes/No prompt would promise a grant it cannot keep. + AuditPromptQueue worker; + CHECK(worker.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsDelete, {"/gone"}), + denied_request("plugin", AuditEventCategory::FsDelete, {"/gone"}), + /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + std::optional denial = worker.take_next(); + REQUIRE(denial.has_value()); + CHECK(denial->kind == AuditPromptKind::DeniedOperation); + worker.complete(); + CHECK(worker.idle()); +} + +TEST_CASE("A synchronous audit prompt is shown only while the queue is idle", "[audit][Python]") +{ + AuditPromptQueue queue; + + // Idle: the prompt is shown now, and nothing is left for a later GUI callback. + CHECK(queue.admit_synchronous(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"})) == + AuditPromptQueue::Admission::ShowNow); + CHECK(queue.pending_count() == 0); + CHECK_FALSE(queue.take_next().has_value()); + queue.complete(); + CHECK(queue.idle()); + + // Another prompt is on screen: the synchronous caller is rejected, whether its request is + // equivalent to the active one or not, and no deferred copy is stored. + CHECK(queue.admit_synchronous(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"})) == + AuditPromptQueue::Admission::ShowNow); + CHECK(queue.admit_synchronous(prompt_request("plugin", AuditEventCategory::FsRead, {"/a"})) == + AuditPromptQueue::Admission::Rejected); + CHECK(queue.admit_synchronous(prompt_request("plugin", AuditEventCategory::FsRead, {"/b"})) == + AuditPromptQueue::Admission::Rejected); + CHECK(queue.pending_count() == 0); + CHECK_FALSE(queue.take_next().has_value()); + // The rejection did not cancel or otherwise disturb the active prompt. + CHECK_FALSE(queue.complete()); + CHECK(queue.idle()); + + // A prompt already waiting counts as busy too: the rejection leaves the pending count and the + // queued request untouched, and nothing is deferred behind it. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/queued"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.admit_synchronous(prompt_request("plugin", AuditEventCategory::FsRead, {"/rejected"})) == + AuditPromptQueue::Admission::Rejected); + CHECK(queue.pending_count() == 1); + + std::optional queued = queue.take_next(); + REQUIRE(queued.has_value()); + const std::vector expected{"/queued"}; + CHECK(queued->keys == expected); + queue.complete(); + CHECK(queue.idle()); + CHECK_FALSE(queue.take_next().has_value()); +} + +TEST_CASE("Discarding all audit prompts denies every blocked waiter", "[audit][Python]") +{ + AuditPromptQueue queue; + + WaitingRequest active = waiting(prompt_request("plugin", AuditEventCategory::FsRead, {"/active"})); + CHECK(queue.admit(active.request, /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + + WaitingRequest queued_runtime = waiting(prompt_request("plugin", AuditEventCategory::FsRead, {"/queued"})); + WaitingRequest queued_load = + waiting(declared_request("plugin", {bucket(AuditEventCategory::Http, {"https://api.example.com"})})); + CHECK(queue.admit(queued_runtime.request, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(queued_load.request, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + + queue.discard_all(); + // A late Yes from the dialog that was still up at shutdown never becomes an approval. + active.completion->resolve(true); + + REQUIRE(settled(active.future)); + REQUIRE(settled(queued_runtime.future)); + REQUIRE(settled(queued_load.future)); + CHECK(active.future.get() == false); + CHECK(queued_runtime.future.get() == false); + CHECK(queued_load.future.get() == false); + CHECK_FALSE(queue.has_pending()); + + // The cancelled dialog stays on screen, so a new prompt queues instead of nesting under it. + CHECK_FALSE(queue.take_next().has_value()); + CHECK(queue.admit(prompt_request("other", AuditEventCategory::FsRead, {"/new"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::Queued); + CHECK(queue.complete()); + CHECK_FALSE(queue.complete()); + CHECK_FALSE(queue.idle()); + + std::optional next = queue.take_next(); + REQUIRE(next.has_value()); + const std::vector expected{"/new"}; + CHECK(next->keys == expected); + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("Unloading a plugin denies its blocked waiters and keeps other plugins' prompts", "[audit][Python]") +{ + AuditPromptQueue queue; + + WaitingRequest unloaded = waiting(prompt_request("unloaded", AuditEventCategory::FsRead, {"/a"})); + WaitingRequest kept = waiting(declared_request("kept", {bucket(AuditEventCategory::FsRead, {"/b"})})); + CHECK(queue.admit(unloaded.request, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(kept.request, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + + queue.discard_plugin("absent"); + CHECK(queue.pending_count() == 2); + + queue.discard_plugin("unloaded"); + + REQUIRE(settled(unloaded.future)); + CHECK(unloaded.future.get() == false); + // The surviving load waiter is not released by another plugin's unload. + CHECK_FALSE(settled(kept.future)); + CHECK(queue.pending_count() == 1); + + std::optional next = queue.take_next(); + REQUIRE(next.has_value()); + CHECK(next->plugin_key == "kept"); + CHECK(next->kind == AuditPromptKind::DeclaredPermissions); + CHECK(next->completion == kept.completion); + queue.complete(); + kept.completion->resolve(true); + REQUIRE(settled(kept.future)); + CHECK(kept.future.get() == true); + CHECK(queue.idle()); +} + +TEST_CASE("A committed answer is not cancelled by a discard that races it", "[audit][Python]") +{ + AuditPromptQueue queue; + CHECK_FALSE(queue.begin_commit()); // nothing active to commit + + WaitingRequest active = waiting(declared_request("plugin", {bucket(AuditEventCategory::FsRead, {"/a"})})); + CHECK(queue.admit(active.request, /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + + // The user answered and the GUI thread is about to write the sidecar. An unload racing that + // write must neither deny the worker nor forbid the grant it approved. + CHECK(queue.begin_commit()); + queue.discard_plugin("plugin"); + CHECK_FALSE(settled(active.future)); + CHECK_FALSE(queue.complete()); + + // A shutdown that wins the race before the commit does deny the waiter and forbids the write. + WaitingRequest late = waiting(declared_request("other", {bucket(AuditEventCategory::FsRead, {"/b"})})); + CHECK(queue.admit(late.request, /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + queue.discard_all(); + CHECK_FALSE(queue.begin_commit()); + REQUIRE(settled(late.future)); + CHECK(late.future.get() == false); + CHECK(queue.complete()); + CHECK(queue.idle()); +} + +TEST_CASE("Unloading a plugin cancels its active prompt but leaves it on screen", "[audit][Python]") +{ + AuditPromptQueue queue; + + WaitingRequest unloaded = waiting(prompt_request("unloaded", AuditEventCategory::FsRead, {"/a"})); + WaitingRequest kept = waiting(declared_request("kept", {bucket(AuditEventCategory::FsRead, {"/b"})})); + CHECK(queue.admit(unloaded.request, /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + CHECK(queue.admit(kept.request, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + + queue.discard_plugin("unloaded"); + // The dialog returns after the unload; the late answer must not approve the load worker. + unloaded.completion->resolve(true); + + REQUIRE(settled(unloaded.future)); + CHECK(unloaded.future.get() == false); + CHECK_FALSE(queue.take_next().has_value()); + // complete() reports the cancellation, so the caller must not persist the accepted grant. + CHECK(queue.complete()); + CHECK_FALSE(settled(kept.future)); + + std::optional next = queue.take_next(); + REQUIRE(next.has_value()); + CHECK(next->plugin_key == "kept"); + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("A queued runtime prompt survives an ordinary load failure", "[audit]") +{ + // The load failed after its plugin code raised the event: the event's denial may be why it + // failed, and approving the saved grant is what lets the user retry the load. + AuditPromptPluginState failed; + failed.load_failed = true; + CHECK(prompt_plugin_is_available(failed, AuditPromptKind::RuntimeEvent)); + + // A declaration is answered by the load worker that is loading; once no load is in progress, + // nothing waits on it. An informational denial was never an approval request. + CHECK_FALSE(prompt_plugin_is_available(failed, AuditPromptKind::DeclaredPermissions)); + CHECK_FALSE(prompt_plugin_is_available(failed, AuditPromptKind::DeniedOperation)); + + // Explicit cancellation and unload discard the prompt instead: the queue removes its entry + // and a request admitted after that discard must not become a stale dialog. + AuditPromptPluginState cancelled = failed; + cancelled.load_cancelled = true; + CHECK_FALSE(prompt_plugin_is_available(cancelled, AuditPromptKind::RuntimeEvent)); + + AuditPromptPluginState unloaded = failed; + unloaded.load_failed = false; + CHECK_FALSE(prompt_plugin_is_available(unloaded, AuditPromptKind::RuntimeEvent)); + + AuditPromptPluginState shutting_down = failed; + shutting_down.shutting_down = true; + CHECK_FALSE(prompt_plugin_is_available(shutting_down, AuditPromptKind::RuntimeEvent)); + + // The normal paths still decide prompts for a live plugin. + AuditPromptPluginState loaded; + loaded.loaded = true; + CHECK(prompt_plugin_is_available(loaded, AuditPromptKind::DeclaredPermissions)); + AuditPromptPluginState loading; + loading.load_in_progress = true; + CHECK(prompt_plugin_is_available(loading, AuditPromptKind::RuntimeEvent)); +} + TEST_CASE("Plugin audit denies host-managed filenames anywhere", "[audit]") { seed_denied_names(); @@ -656,6 +1197,26 @@ const char* const AUDIT_PLUGIN_SOURCE = R"PY(# /// script # /// )PY"; +// A plugin whose registration fails after the module has imported. Its queued runtime prompt is +// the one an ordinary load failure must keep actionable for approval and retry. +const char* const BROKEN_AUDIT_PLUGIN_SOURCE = R"PY(# /// script +# requires-python = ">=3.12" +# +# [tool.orcaslicer.plugin] +# name = "Broken Audit Plugin" +# description = "Plugin audit load-failure fixture" +# author = "OrcaSlicer" +# version = "1.0" +# type = "script" +# /// +import orca + +@orca.plugin +class BrokenAuditPackage(orca.base): + def register_capabilities(self): + raise RuntimeError("registration failed") +)PY"; + // A third-party library, installed outside the stdlib and outside the plugin. const char* const LIBRARY_SOURCE = R"PY( import socket @@ -837,11 +1398,11 @@ struct AuditHarness } // Call before taking the GIL: discovery is not Python work. - void add_plugin(const std::string& key) + void add_plugin(const std::string& key, const char* source = AUDIT_PLUGIN_SOURCE) { const fs::path root = data.plugins_dir() / key; fs::create_directories(root); - std::ofstream((root / (key + ".py")).string(), std::ios::binary) << AUDIT_PLUGIN_SOURCE; + std::ofstream((root / (key + ".py")).string(), std::ios::binary) << source; save_permissions(key, {}); PluginManager::instance().discover_plugins(/*async=*/false, /*clear=*/true); } @@ -928,6 +1489,48 @@ const char* const PLUGIN = "AuditPlugin"; } // namespace +TEST_CASE("A queued runtime prompt survives its plugin's failed load until unload", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedRuntimePromptQueue runtime_queue; + harness.add_plugin("Broken_Plugin", BROKEN_AUDIT_PLUGIN_SOURCE); + + // A prompt for another plugin is on screen when the failing plugin raises its event. + CHECK(runtime_queue.queue.admit(prompt_request("active", AuditEventCategory::FsRead, {"/active"}), + /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + CHECK(runtime_queue.queue.admit(prompt_request("Broken_Plugin", AuditEventCategory::FsRead, {"/queued"}), + /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(runtime_queue.queue.pending_count() == 1); + + PluginManager& manager = PluginManager::instance(); + manager.load_plugin("Broken_Plugin", /*skip_deps=*/true); + std::string error; + CHECK_FALSE(manager.wait_for_plugin_load("Broken_Plugin", std::chrono::seconds(120), error)); + INFO("load error: " << error); + CHECK(manager.is_plugin_load_failed("Broken_Plugin")); + CHECK(runtime_queue.queue.pending_count() == 1); + + // The active prompt closes; the queued runtime prompt is next and still actionable even + // though its load has already failed and released the slot. + runtime_queue.queue.complete(); + std::optional next = runtime_queue.queue.take_next(); + REQUIRE(next.has_value()); + CHECK(next->plugin_key == "Broken_Plugin"); + CHECK(prompt_plugin_is_available(prompt_plugin_state(next->plugin_key), next->kind)); + runtime_queue.queue.complete(); + + // Unloading the plugin runs the production discard against this same queue. + CHECK(runtime_queue.queue.admit(prompt_request("Broken_Plugin", AuditEventCategory::FsRead, {"/queued"}), + /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + REQUIRE(manager.unload_plugin("Broken_Plugin")); + CHECK(runtime_queue.queue.pending_count() == 0); + CHECK(runtime_queue.queue.idle()); + CHECK_FALSE(prompt_plugin_is_available(prompt_plugin_state("Broken_Plugin"), AuditPromptKind::RuntimeEvent)); +} + TEST_CASE("A saved request grant covers the request's own connection in a later session", "[audit][Python]") { AuditHarness harness; diff --git a/tests/slic3rutils/test_plugin_lifecycle.cpp b/tests/slic3rutils/test_plugin_lifecycle.cpp index 7cb1008031..86636f21a5 100644 --- a/tests/slic3rutils/test_plugin_lifecycle.cpp +++ b/tests/slic3rutils/test_plugin_lifecycle.cpp @@ -94,6 +94,26 @@ class EchoPackage(orca.base): orca.register_capability(Echo) )PY"; +// A plugin whose registration always fails after the module imported. The failure is ordinary: +// neither cancellation nor unload, so its queued runtime prompts stay actionable for a retry. +const char* const BROKEN_PLUGIN_SOURCE = R"PY(# /// script +# requires-python = ">=3.12" +# +# [tool.orcaslicer.plugin] +# name = "Broken Plugin" +# description = "Plugin whose registration always fails." +# author = "tests" +# version = "1.0" +# type = "script" +# /// +import orca + +@orca.plugin +class BrokenPackage(orca.base): + def register_capabilities(self): + raise RuntimeError("registration failed") +)PY"; + // A minimal printer-agent plugin exposing exactly one PrinterConnection capability. const char* const PRINTER_AGENT_PLUGIN_SOURCE = R"PY(# /// script # requires-python = ">=3.12" @@ -1003,6 +1023,7 @@ class SlowPackage(orca.base): // The key is registered before the worker is spawned, so this is not a race. REQUIRE(manager.is_plugin_load_in_progress("Slow_Load_Plugin")); REQUIRE(manager.cancel_plugin_load("Slow_Load_Plugin")); + CHECK(manager.is_plugin_load_cancelled("Slow_Load_Plugin")); // Cancelling must not release the worker's slot. shutdown() unloads everything and GUI_App // finalizes the interpreter as soon as this wait returns, so reporting "no loads in progress" @@ -1013,7 +1034,10 @@ class SlowPackage(orca.base): // The worker releases the slot itself, once it has unwound. CHECK(manager.wait_for_all_plugin_loads(std::chrono::seconds(60))); CHECK_FALSE(manager.is_plugin_load_in_progress("Slow_Load_Plugin")); + CHECK_FALSE(manager.is_plugin_load_cancelled("Slow_Load_Plugin")); CHECK_FALSE(manager.is_plugin_loaded("Slow_Load_Plugin")); + // A cancellation is not an ordinary failure, so no prompt is kept actionable for a retry. + CHECK_FALSE(manager.is_plugin_load_failed("Slow_Load_Plugin")); } TEST_CASE("Loading an unknown plugin key records an error instead of crashing", "[PluginLifecycle][Python]") @@ -1037,6 +1061,62 @@ TEST_CASE("Loading an unknown plugin key records an error instead of crashing", CHECK(manager.get_plugin_capabilities("No_Such_Plugin").empty()); } +TEST_CASE("An ordinary load failure stays recorded until the plugin is unloaded", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // Registration raises after the module imported, which is an ordinary failure: the user can + // approve a queued runtime prompt and retry. Cancelling or unloading is different. + ScopedDataDir data_dir_guard("lifecycle-load-failed"); + write_plugin(data_dir_guard, "Broken_Plugin", BROKEN_PLUGIN_SOURCE); + + PluginManager& manager = PluginManager::instance(); + manager.discover_plugins(/*async=*/false, /*clear=*/true); + + std::string error; + CHECK_FALSE(load_and_wait(manager, "Broken_Plugin", error)); + INFO("load error: " << error); + CHECK_FALSE(error.empty()); + CHECK_FALSE(manager.is_plugin_loaded("Broken_Plugin")); + CHECK_FALSE(manager.is_plugin_load_in_progress("Broken_Plugin")); + CHECK_FALSE(manager.is_plugin_load_cancelled("Broken_Plugin")); + CHECK(manager.is_plugin_load_failed("Broken_Plugin")); + + // An explicit unload clears the state a queued prompt would otherwise rely on. + REQUIRE(manager.unload_plugin("Broken_Plugin")); + CHECK_FALSE(manager.is_plugin_load_failed("Broken_Plugin")); +} + +TEST_CASE("Rediscovering a removed failed plugin does not revive its failure state", "[PluginLifecycle][Python]") +{ + ScopedPluginManager plugin_system; + if (!plugin_system.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + ScopedDataDir data_dir_guard("lifecycle-failed-removed"); + const fs::path plugin_dir = write_plugin(data_dir_guard, "Removed_Plugin", BROKEN_PLUGIN_SOURCE); + + PluginManager& manager = PluginManager::instance(); + manager.discover_plugins(/*async=*/false, /*clear=*/true); + + std::string error; + REQUIRE_FALSE(load_and_wait(manager, "Removed_Plugin", error)); + REQUIRE(manager.is_plugin_load_failed("Removed_Plugin")); + + // Removing the missing package must drop the state, not leave it keyed by the old package. + fs::remove_all(plugin_dir); + manager.discover_plugins(/*async=*/false, /*clear=*/true); + manager.remove_missing_plugins({"Removed_Plugin"}); + CHECK_FALSE(manager.is_plugin_load_failed("Removed_Plugin")); + + // Rediscovery starts from a clean failure state even when the key is reused. + write_plugin(data_dir_guard, "Removed_Plugin", BROKEN_PLUGIN_SOURCE); + manager.discover_plugins(/*async=*/false, /*clear=*/true); + CHECK_FALSE(manager.is_plugin_load_failed("Removed_Plugin")); +} + TEST_CASE("The startup auto-load list only contains packages whose sidecar enables them", "[PluginLifecycle][Python]") { ScopedPluginManager plugin_system;