Compare commits

...

12 Commits

Author SHA1 Message Date
Ian Chua fc2a88ba72 fix: isolate browser sessions in plugin ui callbacks 2026-11-19 14:26:05 +08:00
Ian Chua 113b42da33 Merge branch 'main' into fix/isolate-plugin-browser-session 2026-11-18 18:14:21 +08:00
Ian Chua 3838002bc8 feat: serialize permission grant for create and delete files (#17478)
* feat: serialize permission grant for create and delete files

* test: expect saved copytree permissions in hardlink audit test

* refactor: simplify plugin filesystem and permission handling

* fix: show triggering paths in plugin permission prompts

* fix: require subtree consent for recursive plugin deletes

* fix: tests

* fix: Windows short-path aliases in plugin audit checks

* fix: correct plugin folder permission display and consent text
2026-11-18 17:50:29 +08:00
HanifKoh 0c80c412a1 Put Prusa CORE One Overhang Speeds in the Right Slots (#17605)
PrusaSlicer's overhang_speed_0..3 count from the steepest overhang
(0% overlap) up, while Orca's overhang_1_4..4_4_speed count from the
mildest. The MK4S base preset maps them that way (_3 -> 1_4, _2 -> 2_4,
_1 -> 3_4, _0 -> 4_4), but the CORE One process presets put
PrusaSlicer's _2 and _3 overrides in the 50% and 75% slots, and the
CORE One L presets put _3 in the 50% slot. As a result steeper
overhangs could print faster than milder ones, e.g. 0.20mm STRUCTURAL
@CORE One 0.4 ran 25% overhangs at 30 mm/s and 50% overhangs at
45 mm/s.

Rename the keys to the slots the mapping gives, without changing any
value. Five CORE One MMU3 presets also wrote their own overhang speeds
in a mixed-up order, including 0 (no slowdown) for the mildest
overhangs; drop those keys so they inherit their corrected CORE One
parents. PrusaSlicer has no separate MMU3 print presets.
2026-11-18 16:40:58 +08:00
Ian Chua e740246f7e Merge branch 'main' into fix/isolate-plugin-browser-session 2026-11-04 14:42:59 +08:00
Ian Chua 20c01cfc7e Merge branch 'main' into fix/isolate-plugin-browser-session 2026-10-23 18:28:35 +08:00
Ian Chua 3ba5ddfe19 fix: Share isolated WebView sessions per plugin profile 2026-10-23 16:34:44 +08:00
Ian Chua 83de33416e Merge branch 'main' into fix/isolate-plugin-browser-session 2026-10-23 16:17:08 +08:00
Ian Chua 15030ef560 Merge branch 'main' into fix/isolate-plugin-browser-session 2026-10-16 22:23:03 +08:00
Ian Chua b29f06a0ab fix: clang-tidy 2026-10-12 18:49:28 +08:00
Ian Chua 9ec0d39592 Merge branch 'main' into fix/isolate-plugin-browser-session 2026-10-12 18:35:44 +08:00
Ian Chua 0b9b05ed85 fix: Isolate plugin's webview browser sessions 2026-10-12 16:44:24 +08:00
85 changed files with 5074 additions and 478 deletions
+103 -33
View File
@@ -24,7 +24,9 @@ Permissions are stored per plugin key. A plugin can hold:
| Field | Kind | Governs |
| --- | --- | --- |
| `fs_read` | target list | Read-shaped filesystem events. Targets are exact paths or `<dir>/*` trees. |
| `fs_readwrite` | target list | Write-shaped and read/write filesystem events mapped to `FsReadWrite`: a write-mode `open`, rename, chmod, utime, copy, move, archive extraction, and similar. Same target matching as `fs_read`. A write-mode `open` can create a file, but this grant does not cover events mapped to `FsCreate` or `FsDelete`, which have no persistent grant list. |
| `fs_readwrite` | target list | Write-shaped and read/write filesystem events mapped to `FsReadWrite`: a write-mode `open`, rename, chmod, utime, copy, move, archive extraction, and similar. Same target matching as `fs_read`. A write-mode `open` can create a file, but this grant does not cover events mapped to `FsCreate` or `FsDelete`. |
| `fs_create` | folder list | Filesystem create events such as `os.mkdir` and `os.symlink`. |
| `fs_delete` | folder list | Filesystem delete events such as `os.remove` and `shutil.rmtree`. |
| `network_http` | target list | Network targets, consulted together with `network_socket` for both HTTP and socket events. A canonical `scheme://host` entry is host-wide and covers both layers; a URL with a path, port, query or trailing slash is exact; a bare host or legacy address tuple covers raw sockets. |
| `network_socket` | target list | The same network matching, kept as a separate list so a plugin can declare socket access without an HTTP URL. |
| `process` | target list | Process creation and process replacement: `os.system`, `subprocess.Popen`, `os.spawn*`, `os.exec*`, `pty.spawn`, `_winapi.CreateProcess`, and similar. Targets match the audited value verbatim. |
@@ -32,19 +34,24 @@ Permissions are stored per plugin key. A plugin can hold:
| `events` | target list | Audited events that expose no target, keyed as `<Category>:<event>`, for example `Socket:socket.__new__`. Matched verbatim. |
| `full_access` | boolean | Turns off the permission decision for the plugin. See "Full access". |
Filesystem create and delete events (`os.mkdir`, `os.symlink`, `tempfile.mkstemp`,
`os.remove`, `shutil.rmtree`, and similar) are audited, but they have no persistent grant
list. A `fs_read` or `fs_readwrite` grant does not cover these events, although a write grant
can create a file through `open()`. Without full access, each such
event outside an allowed root is prompted only when it can be answered inline. On the wx
main thread a Yes applies only to the operation that raised it and is not saved. Off the
main thread the event is denied immediately and an informational denial is shown instead;
there is no Yes/No prompt, no saved grant, and no promise that a later attempt will be
approved.
Create and delete grants are independent of read and read/write grants. An empty list grants
no folders; an absolute folder path grants operations directly inside that folder, while a path
ending in `/*` also covers its subfolders; a list containing only `*` grants all folders. Runtime approval stores
the parent folder of the audited target, except for a recursive delete, whose consent is
transient and is never stored. A delete grant covers existing entries in that folder,
not just entries created by the plugin. The unconditional denied paths still apply.
A recursive delete (`shutil.rmtree`) is a subtree operation: a plain folder grant is
insufficient even when it names the target folder or its parent. It requires either a saved
delete tree grant whose root covers the target, or explicit one-time consent for that canonical
subtree. A tree grant rooted exactly at the target covers the entries inside it but not the
final removal of the target folder itself, which is an entry in the parent; the operation asks
for consent unless the parent is granted separately. The consent applies only to the operation
that requested it and the nested deletes it performs inside that subtree.
### Target matching
- Exact filesystem entries match the audited path verbatim. An absolute exact entry also
- Read and read/write exact filesystem entries match the audited path verbatim. An absolute exact entry also
matches an equivalent canonical path, including a symlink alias or a relative target resolved
against the current working directory. Relative exact entries match only verbatim, so their
equivalence scope cannot move with the working directory. Canonical equivalence fails closed
@@ -56,6 +63,23 @@ approved.
root must be absolute on the current platform: a relative root never matches, even when a
target is spelled exactly like the entry, so the scope cannot float with the process
working directory.
- Create and delete folder grants compare canonical parent directories; a final symlink is
governed by the folder containing the link. Link creation checks the destination folder;
a hardlink also requires write access to its source because writes through either name
affect the same file. Both source and destination remain
subject to the denied-path check. An unresolved parent
does not match a folder grant. Recursive deletion is checked as a subtree operation: an
exact folder grant does not cover it, but a delete tree grant does, and a one-time consent
covers the target subtree for that operation only. A target-rooted tree grant covers the
entries inside the target but not removing the target folder itself; that final removal needs
a grant for the containing folder or one-time consent. Nested delete entries inside an
approved subtree are allowed while the operation runs, provided they stay inside the canonical
subtree and are reached through standard-library frames. Scope is decided by the entry's
containing folder: deleting a symlink acts on the link entry, never on its destination.
Intermediate `..` components are resolved after symlinks, never lexically folded before
them, and a final `..` fails closed. A
symlink or `..` that would leave the subtree is judged on its own, and denied paths stay
blocked.
- Network entries can be an HTTP URL, a canonical `scheme://host`, a bare host, a
`host:port` pair, or a legacy persisted address tuple such as `('host', 443)`.
`normalize_network_url` reduces a URL to lowercase `scheme://host`; path, query,
@@ -101,10 +125,12 @@ order:
before allowed roots, before a granted operation and before full access, so no grant
can make a denied path reachable.
2. **Covered by a granted operation.** When a granted root operation is still running,
nested events raised through its standard-library frames are allowed without another
prompt. The coverage is bounded to the operation frame and does not extend to plugin
or third-party frames it calls back into. A nested `urllib.Request` is judged on its
own URL, including when it follows a redirect.
nested events raised through its standard-library frames are generally allowed without
another prompt. Delete operations still check nested delete events against their
own grants, or against the canonical subtree recorded by a one-time recursive-delete
consent started by this operation. The coverage is bounded to the operation frame and does
not extend to plugin or third-party frames it calls back into. A nested `urllib.Request`
is judged on its own URL, including when it follows a redirect.
3. **Implicit allowed root or standard-library read.** A filesystem target inside an
allowed root is allowed; a read of the interpreter's standard library is also allowed.
See "Implicit access".
@@ -143,18 +169,17 @@ An event that is not covered by a saved grant or an implicit rule is either put
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,
`AuditPromptQueue` serializes runtime prompts, one-time recursive-delete consent, 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:
attempt can succeed without another prompt. Create and delete approvals save the target's
parent folder, so a worker can retry after the queued Yes. Recursive delete instead uses
one-time consent, as described below. 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
@@ -164,10 +189,27 @@ screen, but its answer is ignored unless committing won the race. An ordinary lo
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
Runtime approvals store the target observed by the audit hook, except that create and delete
approvals store its parent folder. A URL with a path, port or
query is therefore an exact grant; a bare host remains usable for raw sockets. The
declared form and the runtime form are not normalized by the same code path.
A recursive delete is different: a Yes grants consent for the canonical target subtree for
that operation only. The prompt shows the subtree root and states that the consent is not
saved; a filesystem, drive, or network share root gets an explicit warning that its whole
filesystem, drive, or network share is covered. Nested deletes inside that subtree proceed
during the same operation; after it ends, the same target asks again. Denied paths stay blocked
throughout. When the prompt cannot run inline, the current attempt is denied and a Yes from the
posted dialog is kept as a short-lived, single-use approval bound to the plugin key and
canonical target. The posted prompt says it applies to the next matching attempt within one
minute after approval; the next matching attempt consumes it. A different plugin, a different
target, a reused or an expired approval does not. A prompt already open for the same plugin and
target is not posted again, so a retry loop cannot queue duplicate dialogs. The pending-prompt
set is bounded; at capacity, new prompts are denied rather than evicting a dialog that is
already queued. A permission edit, revocation, or reinstall invalidates the plugin's transient
approvals and pending prompt keys; a dialog callback already queued becomes a no-op instead of
recreating a stale approval.
## Implicit access
Some access needs no grant because it is part of the plugin system's normal operation:
@@ -180,6 +222,12 @@ Some access needs no grant because it is part of the plugin system's normal oper
- A per-call scoped root can be added. The G-code post-process hook grants the folder
containing the exported G-code file so the plugin can edit it; the root is scoped to
that call.
- A delete inside a writable allowed root is scoped by the entry's containing folder. Deleting
a symlink that lives in the root is therefore implicit even when the link points outside,
because the operation removes the link entry; an outside link that points into the root is
not implicit. A recursive delete inside a writable root records its target subtree as the
running operation, so its fd-based reads do not trigger a separate prompt and its nested
deletes cannot leave that subtree.
### Denied paths
@@ -198,8 +246,10 @@ The following are denied before any allowed root or full-access check:
## Persistence and editing
Grants and install state live in `.install_state.json` in the plugin root. The
`permissions` object stores `fs_read`, `fs_readwrite`, `network_http`,
`network_socket`, `process`, `threading`, `events`, and `full_access`. The file is
`permissions` object stores `fs_read`, `fs_readwrite`, `fs_create`, `fs_delete`, `network_http`,
`network_socket`, `process`, `threading`, `events`, and `full_access`. It never stores a
recursive-delete consent: that approval and any retry approval are in memory only, so accepting
one does not widen the plugin's saved delete scope. The file is
written by `write_install_state`, the single writer for the sidecar schema. In-process
reads and read-modify-write operations are synchronized. Writes prepare a complete
replacement in the plugin directory and replace the sidecar only after the write succeeds.
@@ -253,7 +303,8 @@ targets; unchanged entries, including grants written by an older release, are ca
byte-for-byte. New filesystem targets must be absolute on the current
platform: a POSIX path starts at `/`, and a Windows path names a drive plus root or a UNC
share. A `*` is accepted only as the final `/*` of a folder tree, and `..` components are
refused. The matcher also refuses to widen a relative tree root, so a relative tree entry
refused for filesystem grants. Create and delete use absolute folder paths, optional final `/*`
tree grants, or the all-folders mode. The matcher also refuses to widen a relative tree root, so a relative tree entry
saved by hand or carried over from an older release never authorizes. New network targets
must be a full `http://` or `https://` URL; the writer stores `normalize_network_url`'s canonical
lowercase `scheme://host`, dropping port, path, query and fragment. Bare hosts, other
@@ -265,6 +316,11 @@ while full access is on are inert and apply again when full access is off. Turni
on does not delete the stored lists. A permission change affects subsequent audit decisions,
not operations already authorized.
The dialog also asks for confirmation before granting create or delete access to all folders.
On Linux and macOS, create and delete operations using a directory file descriptor are checked
against its resolved path. If that path cannot be resolved, the operation is denied, even with
full access.
## Full access
Full access is a per-plugin boolean that turns off the permission decision. It does not
@@ -312,6 +368,17 @@ never treated as an opt-out.
- **Denied paths are a direct-access block.** Path laundering through a symlink,
hardlink, subprocess, or Windows 8.3 short name is outside the model. A tree grant is
canonicalized for matching, but the deny check itself is base-name and component based.
- **A recursive delete stops at a denied path.** Consent for the subtree does not override the
deny registry. A protected entry inside the tree makes `shutil.rmtree` fail with
`PermissionError` (or be skipped by `ignore_errors`), leaving that entry and any unvisited
entries in place. This is deliberate: protected paths stay protected.
- **fd-based recursive deletes expose only partial paths.** `shutil.rmtree` reads with
`os.scandir(fd)` and opens entries with `dir_fd`; those audit events carry an integer
descriptor or a relative name rather than the full path. The running operation frame covers
them normally, and each relative entry name is still checked, so denied entries stay blocked.
A relative `os.open` target is canonicalized against the process working directory, so a
working directory containing a denied keyword can over-block nested opens. That fails closed
and does not widen access.
- **`data_dir()` is shared and writable.** Every plugin can write anywhere in the
application data directory, including other plugin package files. Only the
install-state sidecar and the denied names and keywords are blocked there.
@@ -325,18 +392,21 @@ never treated as an opt-out.
be re-entered as an absolute path to take effect.
- **An off-main-thread prompt denies the current event.** A persistable grant is saved
only if the user later accepts, so the first attempt from a worker fails with
`PermissionError`. Create and delete have no persistable grant and no retryable approval:
off the main thread they are denied and only an informational denial is shown, while the
inline main-thread prompt covers only the operation that raised it.
- **A running root operation is not re-evaluated.** Revoking full access or changing a
grant affects later top-level operations, not an operation whose root frame already
recorded coverage.
`PermissionError`; a later attempt can succeed after approval. A recursive-delete consent is
instead kept as a short-lived, single-use retry approval bound to the plugin and canonical
target, valid for the next matching attempt within one minute after approval, and is never
persisted. Duplicate prompts for the same plugin and target are not posted.
- **A running root operation is generally not re-evaluated.** Revoking full access or changing a
grant affects later top-level operations, not an operation whose root frame already recorded
coverage. Nested delete events within a delete operation are checked separately, or covered
by the one-time subtree consent recorded on that operation.
## File and symbol map
- `src/slic3r/plugin/PluginAuditManager.hpp` / `.cpp` - `PluginAuditManager`,
`install_hook`, `audit_plugin_event`, `decide_audited_event`, `request_permissions`,
`request_permission`, `AuditPromptQueue`, `check_path_access`,
`request_permission`, `request_recursive_delete_consent`, `delete_target_inside_approved_subtree`,
`delete_target_inside_writable_allowed_root`, `AuditPromptQueue`, `check_path_access`,
`network_permission_matches`, `default_denied_filenames`, `default_denied_path_keywords`,
`ScopedPluginAuditContext`.
- `src/slic3r/plugin/PluginFsUtils.hpp` / `.cpp` - `PluginPermissions`,
+5 -4
View File
@@ -144,11 +144,12 @@ A consequence of running Script on a non-main thread: the audit permission promp
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.
succeed on a later one. Create and delete approvals save the target's parent folder in the same way.
Recursive-delete consent is instead a one-time approval for the next matching attempt within one
minute, bound to the plugin and canonical target. It is never saved. The plugin-load worker and the
slicing worker follow the same behavior.
`AuditPromptQueue` serializes runtime prompts, informational denials and load-time declared-permission
`AuditPromptQueue` serializes runtime prompts, recursive-delete consent 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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "Prusa",
"version": "02.04.00.19",
"version": "02.04.00.20",
"force_update": "0",
"description": "Prusa configurations",
"machine_model_list": [
@@ -17,9 +17,6 @@
"infill_wall_overlap": "25%",
"reduce_infill_retraction": "1",
"filename_format": "{input_filename_base}_{layer_height}mm_{filament_type[0]}-{filament_type[1]}-{filament_type[2]}-{filament_type[3]}-{filament_type[4]}_COREONE_MMU3_{print_time}.gcode",
"overhang_1_4_speed": "0",
"overhang_2_4_speed": "25",
"overhang_4_4_speed": "80%",
"support_line_width": "0.4",
"minimum_sparse_infill_area": "15",
"support_bottom_z_distance": "0.17",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "VzCIZcLeFkrR4e3N",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "Ajm1BOji7RhOH8vj",
"instantiation": "true",
"overhang_1_4_speed": "50",
"overhang_3_4_speed": "60%",
"overhang_2_4_speed": "50",
"overhang_1_4_speed": "60%",
"sparse_infill_speed": "300",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -6,7 +6,7 @@
"setting_id": "wATWoU2pvkCugSEj",
"instantiation": "true",
"overhang_2_4_speed": "50",
"overhang_3_4_speed": "60%",
"overhang_1_4_speed": "60%",
"sparse_infill_speed": "300",
"travel_speed": "500",
"travel_acceleration": "6000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "Er7s41kb6bBDjBVP",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"sparse_infill_speed": "120",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "Ri9JPCMN8YgbT9pp",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -6,8 +6,8 @@
"setting_id": "M8WdIdQWUxYohSoe",
"instantiation": "true",
"inner_wall_speed": "70",
"overhang_3_4_speed": "30",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "30",
"overhang_1_4_speed": "70%",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -7,7 +7,7 @@
"instantiation": "true",
"inner_wall_speed": "80",
"overhang_2_4_speed": "30",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"travel_speed": "500",
"travel_acceleration": "6000",
"default_acceleration": "3000",
@@ -17,9 +17,6 @@
"infill_wall_overlap": "25%",
"reduce_infill_retraction": "1",
"filename_format": "{input_filename_base}_{layer_height}mm_{filament_type[0]}-{filament_type[1]}-{filament_type[2]}-{filament_type[3]}-{filament_type[4]}_COREONE_MMU3_{print_time}.gcode",
"overhang_1_4_speed": "0",
"overhang_2_4_speed": "25",
"overhang_4_4_speed": "80%",
"support_line_width": "0.4",
"minimum_sparse_infill_area": "15",
"support_base_pattern": "default",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "o828K3OgfkY099HE",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"compatible_printers_condition": "printer_notes=~/.*PRINTER_MODEL_COREONE[^_a-zA-Z0-9].*/ and nozzle_diameter[0]==0.4 and printer_notes!~/.*HF_NOZZLE.*/",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "hC9F5dv2WJ4pJMJx",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"compatible_printers_condition": "printer_notes=~/.*PRINTER_MODEL_COREONE[^_a-zA-Z0-9].*/ and nozzle_diameter[0]==0.4 and printer_notes!~/.*HF_NOZZLE.*/",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "TcOnRh8cZfyZcQzx",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "0XpimvIotRzkG5C0",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "wfltF3Wq4BExv5nn",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "30",
"overhang_1_4_speed": "70%",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "JiBYOvJXa3KIsWlk",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "50",
"overhang_1_4_speed": "70%",
"sparse_infill_speed": "300",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "8FVn4dELsu1VoEFn",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "kzKpZiJ0ni4ry97j",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "30",
"overhang_1_4_speed": "70%",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -6,7 +6,7 @@
"setting_id": "Xge3hbQO7LYu708A",
"instantiation": "true",
"overhang_2_4_speed": "30",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"travel_speed": "500",
"travel_acceleration": "6000",
"default_acceleration": "3000",
@@ -6,7 +6,7 @@
"setting_id": "VfD1ailcNZG4715m",
"instantiation": "true",
"overhang_2_4_speed": "50",
"overhang_3_4_speed": "60%",
"overhang_1_4_speed": "60%",
"sparse_infill_speed": "300",
"travel_speed": "500",
"travel_acceleration": "6000",
@@ -6,7 +6,7 @@
"setting_id": "NlEh0boG6G8cm7er",
"instantiation": "true",
"overhang_2_4_speed": "30",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"travel_speed": "500",
"travel_acceleration": "6000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "MJI3kUwsJ3adqKx7",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "4dkMphdZvBhDyRH3",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "SJgbNC9RPNJ5pETW",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_2_4_speed": "30",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -17,9 +17,6 @@
"infill_wall_overlap": "25%",
"reduce_infill_retraction": "1",
"filename_format": "{input_filename_base}_{layer_height}mm_{filament_type[0]}-{filament_type[1]}-{filament_type[2]}-{filament_type[3]}-{filament_type[4]}_COREONE_MMU3_{print_time}.gcode",
"overhang_1_4_speed": "0",
"overhang_2_4_speed": "15",
"overhang_3_4_speed": "25",
"inner_wall_line_width": "0.45",
"outer_wall_line_width": "0.45",
"sparse_infill_line_width": "0.45",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "j18VMrjkn0nNcqF0",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "UbyRKcnbmQtxSOGo",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "30",
"overhang_1_4_speed": "70%",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "HmzxDcsh7N8XFbcZ",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "50",
"overhang_1_4_speed": "70%",
"sparse_infill_speed": "300",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "HvtMtivKFekmwpqp",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "L5p4CoVhGtFA8NUk",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "30",
"overhang_1_4_speed": "70%",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -6,7 +6,7 @@
"setting_id": "mMMK2jmzahWruFjK",
"instantiation": "true",
"overhang_2_4_speed": "30",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"travel_speed": "500",
"travel_acceleration": "6000",
"default_acceleration": "3000",
@@ -6,7 +6,7 @@
"setting_id": "MOYF1incx6aCPT3i",
"instantiation": "true",
"overhang_2_4_speed": "50",
"overhang_3_4_speed": "60%",
"overhang_1_4_speed": "60%",
"sparse_infill_speed": "300",
"travel_speed": "500",
"travel_acceleration": "6000",
@@ -6,7 +6,7 @@
"setting_id": "71l9zfjgGKBk7P4O",
"instantiation": "true",
"overhang_2_4_speed": "30",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"travel_speed": "500",
"travel_acceleration": "6000",
"default_acceleration": "3000",
@@ -15,9 +15,6 @@
"infill_wall_overlap": "25%",
"reduce_infill_retraction": "1",
"filename_format": "{input_filename_base}_{layer_height}mm_{filament_type[0]}-{filament_type[1]}-{filament_type[2]}-{filament_type[3]}-{filament_type[4]}_COREONE_MMU3_{print_time}.gcode",
"overhang_1_4_speed": "0",
"overhang_2_4_speed": "15",
"overhang_3_4_speed": "25",
"inner_wall_line_width": "0.45",
"outer_wall_line_width": "0.45",
"sparse_infill_line_width": "0.45",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "Xwzu2GvZfskVw39Z",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "2Az8F1vPrNXgKK1V",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_2_4_speed": "30",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "zBWdXWEuyUFu88Pg",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -15,9 +15,6 @@
"infill_wall_overlap": "25%",
"reduce_infill_retraction": "1",
"filename_format": "{input_filename_base}_{layer_height}mm_{filament_type[0]}-{filament_type[1]}-{filament_type[2]}-{filament_type[3]}-{filament_type[4]}_COREONE_MMU3_{print_time}.gcode",
"overhang_1_4_speed": "50%",
"overhang_2_4_speed": "15",
"overhang_4_4_speed": "90%",
"inner_wall_line_width": "0.45",
"outer_wall_line_width": "0.45",
"sparse_infill_line_width": "0.45",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "CbQCA65dMMEkK134",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"support_threshold_angle": "35",
"outer_wall_acceleration": "3000",
"inner_wall_acceleration": "6000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "m23j7wSoEJdezJgy",
"instantiation": "true",
"overhang_3_4_speed": "35",
"overhang_2_4_speed": "35",
"top_surface_acceleration": "2000",
"inner_wall_acceleration": "2500",
"internal_solid_infill_acceleration": "5000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "wV3jMl7YWJ8dwdE8",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"top_surface_acceleration": "2000",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "uzCEBmbNEQVjR8i8",
"instantiation": "true",
"overhang_3_4_speed": "40",
"overhang_2_4_speed": "40",
"top_surface_acceleration": "2000",
"support_speed": "100",
"support_interface_speed": "55%",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "ggWI2g8z3wNfnFG3",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "30",
"overhang_1_4_speed": "70%",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "gDKE0bH5qPyNewzu",
"instantiation": "true",
"overhang_3_4_speed": "50",
"overhang_2_4_speed": "50",
"support_interface_speed": "50%",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "h1nfJq2NJquQhuRt",
"instantiation": "true",
"overhang_3_4_speed": "35",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "35",
"overhang_1_4_speed": "70%",
"top_surface_acceleration": "2000",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -6,7 +6,7 @@
"setting_id": "T7OokZGHzzb08zU1",
"instantiation": "true",
"overhang_2_4_speed": "30",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"travel_speed": "500",
"travel_acceleration": "6000",
"default_acceleration": "3000",
@@ -6,7 +6,7 @@
"setting_id": "cK8T3bqisPivC2MG",
"instantiation": "true",
"overhang_2_4_speed": "35",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"top_surface_speed": "2000",
"travel_speed": "500",
"travel_acceleration": "6000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "xwwhZvsBxulQ1x0L",
"instantiation": "true",
"overhang_3_4_speed": "30",
"overhang_2_4_speed": "30",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "RISdNOnVSnA7v3yH",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"support_speed": "120",
"support_interface_speed": "50%",
"travel_speed": "350",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "VeYx8eYxSM2B7X2d",
"instantiation": "true",
"overhang_3_4_speed": "35",
"overhang_2_4_speed": "35",
"support_speed": "110",
"support_interface_speed": "50%",
"travel_speed": "350",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "2XzTOQAtbbUhXKeX",
"instantiation": "true",
"overhang_3_4_speed": "35",
"overhang_2_4_speed": "35",
"top_surface_acceleration": "2000",
"inner_wall_acceleration": "2500",
"internal_solid_infill_acceleration": "5000",
@@ -5,8 +5,8 @@
"from": "system",
"setting_id": "ecyfUzv5L2MJ74lQ",
"instantiation": "true",
"overhang_3_4_speed": "35",
"overhang_4_4_speed": "70%",
"overhang_2_4_speed": "35",
"overhang_1_4_speed": "70%",
"top_surface_acceleration": "2000",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "md2z7xPjOLeOWx25",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"top_surface_acceleration": "2000",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -6,7 +6,7 @@
"setting_id": "Qz6UOajHaO5Zctcf",
"instantiation": "true",
"overhang_2_4_speed": "35",
"overhang_3_4_speed": "70%",
"overhang_1_4_speed": "70%",
"top_surface_speed": "2000",
"travel_speed": "500",
"travel_acceleration": "6000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "6oVNX62VOpdaRmbI",
"instantiation": "true",
"overhang_3_4_speed": "35",
"overhang_2_4_speed": "35",
"travel_speed": "350",
"travel_acceleration": "7000",
"default_acceleration": "3000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "oGmCrMvVMo9eXPlo",
"instantiation": "true",
"overhang_3_4_speed": "40",
"overhang_2_4_speed": "40",
"top_surface_acceleration": "2000",
"travel_speed": "350",
"travel_acceleration": "7000",
@@ -5,7 +5,7 @@
"from": "system",
"setting_id": "zBotlr9rsKLjriaN",
"instantiation": "true",
"overhang_3_4_speed": "45",
"overhang_2_4_speed": "45",
"top_surface_acceleration": "2000",
"travel_speed": "350",
"travel_acceleration": "7000",
+105 -4
View File
@@ -369,8 +369,12 @@ function HandleStudio(value) {
delete draft.additions[request.category];
if (payload.success === true && draft && (request.operation === "replace" || request.operation === "remove"))
delete draft.edits[request.category]?.[request.old_value];
// The host sends the updated list before this result. Re-read it instead of dropping the
// draft: edits the user made while this request was in flight must survive the reply.
if (payload.success === true && draft && (request.category === "fs_create" || request.category === "fs_delete")) {
if (request.operation === "set_mode")
(draft.partialModes ||= {})[request.category] = request.value === "partial";
else if (request.operation === "remove")
(draft.partialModes ||= {})[request.category] = true;
}
if (draft)
ApplyLatestPermissionSource(request.pluginKey);
renderedPermissionsSignature = null;
@@ -1107,8 +1111,8 @@ function RenderPermissions(plugin) {
["events", "permissions_events", "Events"]
];
const categoryGuidance = {
fs_read: [T("permissions_filesystem_help", "Enter an absolute path on this computer. Add /* at the end to include the folder and everything below it; no other wildcard is accepted. A read/write grant can create files through open(), but it does not cover create or delete events such as os.mkdir and os.remove. Without Full access, each such event outside allowed folders needs its own approval, which is never saved. When a plugin runs in the background, these events are denied without asking."), T("permissions_filesystem_placeholder", "/path/to/directory/*")],
fs_readwrite: [T("permissions_filesystem_help", "Enter an absolute path on this computer. Add /* at the end to include the folder and everything below it; no other wildcard is accepted. A read/write grant can create files through open(), but it does not cover create or delete events such as os.mkdir and os.remove. Without Full access, each such event outside allowed folders needs its own approval, which is never saved. When a plugin runs in the background, these events are denied without asking."), T("permissions_filesystem_placeholder", "/path/to/directory/*")],
fs_read: [T("permissions_filesystem_help", "Enter an absolute path on this computer. Add /* at the end to include the folder and everything below it; no other wildcard is accepted. A read/write grant can create files through open(), but does not cover create or delete events such as os.mkdir and os.remove."), T("permissions_filesystem_placeholder", "/path/to/directory/*")],
fs_readwrite: [null, ""],
network_http: [null, "https://example.com"],
network_socket: [null, "https://example.com"],
process: [T("permissions_process_help", "Enter the exact value recorded by the audit. It may be a Python representation of the command."), T("permissions_process_placeholder", "Exact audited value")],
@@ -1233,6 +1237,7 @@ function RenderPermissions(plugin) {
for (const [key, translation, fallback] of categories) {
if (key === "fs_read") {
groupBodies.get(key).appendChild(RenderFilesystemSection(plugin, pluginKey, draft, installed, categoryGuidance.fs_read));
groupBodies.get(key).appendChild(RenderFolderModes(plugin, pluginKey, draft, installed));
continue;
}
if (key === "fs_readwrite")
@@ -1331,6 +1336,102 @@ function RenderPermissions(plugin) {
}
}
function RenderFolderModes(plugin, pluginKey, draft, editable) {
const section = document.createElement("section");
section.className = "permission-section permission-filesystem";
const description = document.createElement("div");
description.className = "permission-description";
const guidance = document.createElement("p");
guidance.className = "permission-guidance";
guidance.id = "permission-guidance-folder-modes";
guidance.textContent = T("permissions_folder_modes_help", "Choose none, selected folders, or all folders. Enter an absolute folder path to allow operations directly inside it, or add /* to include all nested folders. No other wildcard is accepted. Delete access allows deleting files and folders inside the granted scope; deleting the granted folder itself requires access to its parent. Some folders are allowed automatically, while protected paths remain blocked. Other operations may require approval. A background operation needing approval is denied first; after approval, a retry may succeed.");
description.appendChild(guidance);
const controls = document.createElement("div");
controls.className = "permission-controls";
section.append(description, controls);
const types = [
{ key: "fs_create", label: T("permissions_create", "Create"), name: T("permissions_create_name", "File system: Create") },
{ key: "fs_delete", label: T("permissions_delete", "Delete"), name: T("permissions_delete_name", "File system: Delete") }
];
for (const type of types) {
const bucket = document.createElement("section");
bucket.className = "permission-filesystem-bucket";
const entries = draft.values[type.key];
if (!Array.isArray(entries) || !Array.isArray(plugin.permissions?.[type.key])) {
const notice = document.createElement("p");
notice.className = "permission-notice";
notice.textContent = T("permissions_unavailable", "Permissions are unavailable.");
bucket.appendChild(notice);
controls.appendChild(bucket);
continue;
}
const savedEntries = plugin.permissions[type.key];
const mode = savedEntries.length === 1 && savedEntries[0] === "*" ? "full"
: savedEntries.length || draft.partialModes?.[type.key] ? "partial" : "none";
const fieldset = document.createElement("fieldset");
fieldset.className = "permission-mode";
fieldset.setAttribute("aria-describedby", guidance.id);
const legend = document.createElement("legend");
legend.className = "permission-heading";
legend.textContent = type.label;
fieldset.appendChild(legend);
for (const [value, label] of [["none", T("permissions_mode_none", "None")], ["partial", T("permissions_mode_partial", "Selected folders")], ["full", T("permissions_mode_full", "All folders")]]) {
const wrapper = document.createElement("label");
const radio = document.createElement("input");
radio.type = "radio";
radio.id = `permission-mode-${type.key}-${value}`;
radio.name = `permission-mode-${type.key}`;
radio.value = value;
radio.checked = mode === value;
radio.disabled = !editable;
radio.addEventListener("change", () => {
if (savedEntries.length === 0 && value !== "full") {
(draft.partialModes ||= {})[type.key] = value === "partial";
renderedPermissionsSignature = null;
RenderDetails();
document.getElementById(radio.id)?.focus();
} else {
CommitPermission(pluginKey, { operation: "set_mode", category: type.key, value });
}
});
wrapper.append(radio, document.createTextNode(label));
fieldset.appendChild(wrapper);
}
bucket.appendChild(fieldset);
if (mode !== "partial" && (draft.additions[type.key] || Object.keys(draft.edits[type.key] || {}).length)) {
const notice = document.createElement("p");
notice.className = "permission-notice";
notice.textContent = T("permissions_folder_drafts_retained", "Unsaved folder changes are kept. Choose Selected folders to review or discard them.");
bucket.appendChild(notice);
}
if (mode === "partial") {
if (savedEntries.includes("*")) {
const notice = document.createElement("p");
notice.className = "permission-notice";
notice.textContent = T("permissions_folder_invalid_wildcard", "The wildcard is ignored when combined with folder paths. Remove it or choose all folders.");
bucket.appendChild(notice);
}
if (savedEntries.length === 0) {
const notice = document.createElement("p");
notice.className = "permission-notice";
notice.textContent = T("permissions_folder_empty", "Add a folder to save selected-folder access. No selected folders are saved until you add one.");
bucket.appendChild(notice);
}
const list = document.createElement("ul");
list.className = "permission-list";
const placeholder = T("permissions_folder_placeholder", "Absolute folder path");
entries.forEach((entry, index) => {
const item = document.createElement("li");
item.appendChild(PermissionForm(pluginKey, type.key, type.name, index, editable, placeholder, guidance.id, draft));
list.appendChild(item);
});
bucket.append(list, PermissionForm(pluginKey, type.key, type.name, null, editable, placeholder, guidance.id, draft));
}
controls.appendChild(bucket);
}
return section;
}
function RenderFilesystemSection(plugin, pluginKey, draft, editable, guidanceText) {
const section = document.createElement("section");
section.className = "permission-section permission-filesystem";
@@ -1465,6 +1465,24 @@ body.pane-resizing {
.permission-filesystem-bucket + .permission-filesystem-bucket { margin-top: 17px; }
.permission-mode {
min-width: 0;
margin: 0 0 10px;
padding: 0;
border: 0;
}
.permissions-content .permission-mode label {
display: inline-flex;
align-items: center;
gap: 5px;
margin: 4px 16px 4px 0;
color: var(--text);
}
.permission-mode input { accent-color: var(--main-color); }
.permission-mode input:focus-visible { outline: 2px solid var(--main-color); outline-offset: 2px; }
.permissions-content label.permission-thread-toggle {
display: inline-flex;
align-items: center;
+3 -2
View File
@@ -26,8 +26,9 @@ DockPanel::DockPanel(wxWindow* parent,
const std::string& html,
MessageHandler on_message,
CloseHandler on_close,
CloseHandler on_destroyed)
: WebPanel(parent, web_hosting::orca_bridge_script())
CloseHandler on_destroyed,
const wxString& profile)
: WebPanel(parent, web_hosting::orca_bridge_script(), profile)
, m_html(html)
, m_on_message(std::move(on_message))
, m_on_close(std::move(on_close))
+4 -1
View File
@@ -6,6 +6,8 @@
#include <optional>
#include <string>
#include <wx/string.h>
class wxWindow;
namespace Slic3r { namespace GUI {
@@ -27,7 +29,8 @@ public:
const std::string& html,
MessageHandler on_message,
CloseHandler on_close,
CloseHandler on_destroyed);
CloseHandler on_destroyed,
const wxString& profile = wxEmptyString);
~DockPanel() override;
// Main thread only.
+99 -2
View File
@@ -32,6 +32,7 @@
#include <boost/filesystem.hpp>
#include <boost/log/trivial.hpp>
#include <boost/system/error_code.hpp>
#include <algorithm>
#include <memory>
@@ -61,6 +62,22 @@ const wxString kUnsubscribeTitle = _L("Unsubscribe");
const wxString kOverwritePluginTitle = _L("Overwrite Plugin");
std::string s_selected_plugin_install_action = "explore";
// The permission validator has already checked the path and its final wildcard. Compare both
// its spelling and its resolved location, since a symlink can also point to a filesystem root.
bool is_root_tree_permission(const std::string& permission)
{
if (permission.empty() || permission.back() != '*')
return false;
const std::string folder = permission.substr(0, permission.size() - 1);
if (is_filesystem_root(boost::filesystem::path(folder)))
return true;
boost::system::error_code ec;
const boost::filesystem::path resolved = boost::filesystem::weakly_canonical(boost::filesystem::path(folder), ec);
return !ec && is_filesystem_root(resolved);
}
struct PluginContextAction
{
std::string id;
@@ -172,6 +189,8 @@ nlohmann::json build_permissions_payload(const PluginPermissions& permissions)
nlohmann::json payload;
payload["fs_read"] = permissions.fs_read;
payload["fs_readwrite"] = permissions.fs_readwrite;
payload["fs_create"] = permissions.fs_create;
payload["fs_delete"] = permissions.fs_delete;
payload["network_http"] = permissions.network_http;
payload["network_socket"] = permissions.network_socket;
payload["process"] = permissions.process;
@@ -725,7 +744,18 @@ nlohmann::json PluginsDialog::localized_strings() const
{"permissions_process", _u8L_CONTEXT("Processes", "Permission category")},
{"permissions_threading", _u8L("Threading")},
{"permissions_events", _u8L_CONTEXT("Events", "Permission category")},
{"permissions_filesystem_help", _u8L("Enter an absolute path on this computer. Add /* at the end to include the folder and everything below it; no other wildcard is accepted. A read/write grant can create files through open(), but it does not cover create or delete events such as os.mkdir and os.remove. Without Full access, each such event outside allowed folders needs its own approval, which is never saved. When a plugin runs in the background, these events are denied without asking.")},
{"permissions_filesystem_help", _u8L("Enter an absolute path on this computer. Add /* at the end to include the folder and everything below it; no other wildcard is accepted. A read/write grant can create files through open(), but does not cover create or delete events such as os.mkdir and os.remove.")},
{"permissions_create", _u8L_CONTEXT("Create", "Permission access")},
{"permissions_delete", _u8L_CONTEXT("Delete", "Permission access")},
{"permissions_create_name", _u8L("File system: Create")},
{"permissions_delete_name", _u8L("File system: Delete")},
{"permissions_folder_modes_help", _u8L("Choose none, selected folders, or all folders. Enter an absolute folder path to allow operations directly inside it, or add /* to include all nested folders. No other wildcard is accepted. Delete access allows deleting files and folders inside the granted scope; deleting the granted folder itself requires access to its parent. Some folders are allowed automatically, while protected paths remain blocked. Other operations may require approval. A background operation needing approval is denied first; after approval, a retry may succeed.")},
{"permissions_mode_none", _u8L_CONTEXT("None", "Permission access")},
{"permissions_mode_partial", _u8L("Selected folders")},
{"permissions_mode_full", _u8L("All folders")},
{"permissions_folder_placeholder", _u8L("Absolute folder path")},
{"permissions_folder_empty", _u8L("Add a folder to save selected-folder access. No selected folders are saved until you add one.")},
{"permissions_folder_invalid_wildcard", _u8L("The wildcard is ignored when combined with folder paths. Remove it or choose all folders.")},
#ifdef _WIN32
{"permissions_filesystem_placeholder", _u8L("C:\\path\\to\\directory\\*")},
#else
@@ -1053,6 +1083,10 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload)
bucket = PluginPermissionCategory::FsRead; entries = &stored.permissions.fs_read;
} else if (category == "fs_readwrite") {
bucket = PluginPermissionCategory::FsReadWrite; entries = &stored.permissions.fs_readwrite;
} else if (category == "fs_create") {
bucket = PluginPermissionCategory::FsCreate; entries = &stored.permissions.fs_create;
} else if (category == "fs_delete") {
bucket = PluginPermissionCategory::FsDelete; entries = &stored.permissions.fs_delete;
} else if (category == "network_http") {
bucket = PluginPermissionCategory::NetworkHttp; entries = &stored.permissions.network_http;
} else if (category == "network_socket") {
@@ -1078,6 +1112,39 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload)
} else {
mutation.threading = enabled;
}
} else if ((category == "fs_create" || category == "fs_delete") && operation == "set_mode") {
const std::string mode = string_field("value");
if (mode != "none" && mode != "partial" && mode != "full") {
invalid();
return;
}
if (mode == "full" && !(entries->size() == 1 && entries->front() == "*")) {
const wxString message = category == "fs_delete" ?
wxString::Format(_L("Allow \"%s\" to delete entries in all folders?\n\n"
"This includes deleting existing files and folders accessible to your account. "
"Protected paths remain blocked. Only allow this for a plugin you trust."), plugin_name) :
wxString::Format(_L("Allow \"%s\" to create entries in all folders?\n\n"
"This includes creating files and folders accessible to your account. "
"Protected paths remain blocked. Only allow this for a plugin you trust."), plugin_name);
MessageDialog dialog(this, message, _L("All folders"), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING);
dialog.SetButtonLabel(wxID_NO, _L("No"), /*set_focus=*/true);
const int result = dialog.ShowModal();
restore_z_order();
if (result != wxID_YES) {
finish(false);
return;
}
// A permission prompt may have saved another grant while this dialog was open.
if (!PluginManager::instance().get_install_state(plugin_key, stored)) {
show_status(_L("Failed to save permissions."), "error");
finish(false);
return;
}
}
for (const std::string& entry : *entries)
mutation.remove.push_back({bucket, entry});
if (mode == "full")
mutation.add.push_back({bucket, "*"});
} else {
if (!entries || (operation != "add" && operation != "remove" && operation != "replace") ||
(operation != "add" && (!payload.contains("old_value") || !payload.at("old_value").is_string())) ||
@@ -1092,6 +1159,12 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload)
return;
}
mutation.remove.push_back({bucket, old_value});
// A mixed list does not grant full access, but removing its last folder would turn
// the remaining wildcard into a full grant. Remove the wildcard as well.
if (operation == "remove" && (category == "fs_create" || category == "fs_delete") &&
entries->size() == 2 && old_value != "*" &&
std::find(entries->begin(), entries->end(), "*") != entries->end())
mutation.remove.push_back({bucket, "*"});
}
if (operation != "remove") {
const std::string raw = string_field("value");
@@ -1101,7 +1174,11 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload)
bool valid = !value.empty() && value.find('\0') == std::string::npos;
if (valid && (category == "fs_read" || category == "fs_readwrite"))
valid = normalize_filesystem_permission(value, normalized, reason);
else if (valid && category == "network_http")
else if (valid && (category == "fs_create" || category == "fs_delete")) {
valid = normalize_filesystem_permission(value, normalized, reason);
if (entries->size() == 1 && entries->front() == "*")
valid = false;
} else if (valid && category == "network_http")
valid = normalize_network_permission(value, normalized, reason);
else if (valid && category == "network_socket")
valid = normalize_socket_permission(value, normalized, reason);
@@ -1113,6 +1190,26 @@ void PluginsDialog::mutate_plugin_permission(const nlohmann::json& payload)
finish(false);
return;
}
if ((category == "fs_create" || category == "fs_delete") && is_root_tree_permission(normalized)) {
// TRN %1% is the plugin name; %2% is the folder tree path being granted.
const wxString message = category == "fs_delete" ?
format_wxstr(_L("Allow \"%1%\" to delete entries throughout \"%2%\"?\n\n"
"This covers the entire filesystem, drive, or network share named by this path, "
"including existing files and folders in nested folders. Protected paths remain blocked. "
"Only allow this for a plugin you trust."), plugin_name, from_u8(normalized)) :
format_wxstr(_L("Allow \"%1%\" to create entries throughout \"%2%\"?\n\n"
"This covers the entire filesystem, drive, or network share named by this path, "
"including nested folders. Protected paths remain blocked. "
"Only allow this for a plugin you trust."), plugin_name, from_u8(normalized));
MessageDialog dialog(this, message, _L("All folders"), wxYES_NO | wxNO_DEFAULT | wxICON_WARNING);
dialog.SetButtonLabel(wxID_NO, _L("No"), /*set_focus=*/true);
const int result = dialog.ShowModal();
restore_z_order();
if (result != wxID_YES) {
finish(false);
return;
}
}
mutation.add.push_back({bucket, normalized});
}
}
+3 -2
View File
@@ -28,7 +28,8 @@ WebDialog::WebDialog(wxWindow* parent,
SubmitHandler on_submit,
CloseHandler on_close,
CloseHandler on_destroyed,
long wx_style)
long wx_style,
const wxString& profile)
: WebViewHostDialog(parent, wxID_ANY, title, wxDefaultPosition, size, wx_style)
, m_html(html)
, m_on_message(std::move(on_message))
@@ -38,7 +39,7 @@ WebDialog::WebDialog(wxWindow* parent,
{
// A tiny bundled bootstrap page brings the webview up; the real plugin HTML
// is swapped in via SetPage once the bootstrap finishes loading.
create_webview(web_hosting::BOOTSTRAP_PAGE, title, size, wxSize(320, 240));
create_webview(web_hosting::BOOTSTRAP_PAGE, title, size, wxSize(320, 240), profile);
// Paint the window/webview in the themed background so there is no white
// flash before the (transparent) bootstrap page and plugin HTML render.
+2 -1
View File
@@ -49,7 +49,8 @@ public:
SubmitHandler on_submit,
CloseHandler on_close,
CloseHandler on_destroyed,
long wx_style = wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxMAXIMIZE_BOX | wxRESIZE_BORDER);
long wx_style = wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxMAXIMIZE_BOX | wxRESIZE_BORDER,
const wxString& profile = wxEmptyString);
~WebDialog() override;
static void post_message(WebDialog* dialog, const nlohmann::json& data);
+2 -2
View File
@@ -18,7 +18,7 @@
namespace Slic3r { namespace GUI {
WebPanel::WebPanel(wxWindow* parent, const char* bridge_script)
WebPanel::WebPanel(wxWindow* parent, const char* bridge_script, const wxString& profile)
: wxPanel(parent, wxID_ANY)
{
SetBackgroundColour(wxGetApp().get_window_default_clr());
@@ -26,7 +26,7 @@ WebPanel::WebPanel(wxWindow* parent, const char* bridge_script)
SetSizer(sizer);
// Never null: WebView::CreateWebView substitutes a placeholder view when no backend is available.
m_browser = WebView::CreateWebView(this, web_hosting::bootstrap_url());
m_browser = WebView::CreateWebView(this, web_hosting::bootstrap_url(), profile);
m_browser->SetBackgroundColour(GetBackgroundColour());
m_browser->AddUserScript(wxString::FromUTF8(WebViewHostDialog::theme_user_script()));
m_browser->AddUserScript(wxString::FromUTF8(WebViewHostDialog::element_defaults_user_script()));
+2 -1
View File
@@ -4,6 +4,7 @@
#include <wx/event.h>
#include <wx/panel.h>
#include <wx/string.h>
#include <wx/webview.h>
#include <optional>
@@ -22,7 +23,7 @@ namespace Slic3r { namespace GUI {
class WebPanel : public wxPanel
{
public:
WebPanel(wxWindow* parent, const char* bridge_script);
WebPanel(wxWindow* parent, const char* bridge_script, const wxString& profile = wxEmptyString);
protected:
wxWebView* browser() const { return m_browser; }
+99 -6
View File
@@ -3,6 +3,8 @@
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/Utils/MacDarkMode.hpp"
#include <libslic3r/Utils.hpp>
#include <algorithm>
#include <boost/log/trivial.hpp>
@@ -10,8 +12,10 @@
#include <chrono>
#include <cstddef>
#include <exception>
#include <map>
#include <thread>
#include <wx/chartype.h>
#include <wx/setup.h>
#include <wx/webview.h>
#include <wx/string.h>
@@ -81,6 +85,50 @@ webkit_get_minor_version (void);
}
#endif
// Private storage root for an isolated (plugin) profile. Plugin pages must not reach the shared
// default store's cookies/session (e.g. the OrcaCloud login), so each profile gets its own dir,
// shared by every view of that profile. macOS isolates with an in-memory store instead (see
// CreateWebView), so this is unused there.
#if !defined(__WXOSX__)
static wxString isolated_profile_path(const wxString& profile)
{
wxString safe;
safe.reserve(profile.size());
for (wxString::const_iterator it = profile.begin(); it != profile.end(); ++it) {
const wxChar c = *it;
const bool keep = (c >= wxT('a') && c <= wxT('z')) || (c >= wxT('A') && c <= wxT('Z')) ||
(c >= wxT('0') && c <= wxT('9')) || c == wxT('.') || c == wxT('-') || c == wxT('_');
safe += keep ? c : wxT('_');
}
if (safe.empty())
safe = wxT("default");
return wxString::FromUTF8((boost::filesystem::path(Slic3r::data_dir()) / "web_profiles" / safe.ToStdString()).string());
}
// A profile's backend state - the cookie jar, storage and the live session - belongs to the object
// wx builds from a wxWebViewConfiguration: the WebView2 environment on Windows, the
// WebKitWebContext on Linux. One configuration per profile is therefore what lets two views of the
// same plugin see each other's login; a configuration per view would share only the directory on
// disk, not the session in memory.
static const wxWebViewConfiguration& profile_configuration(const wxString& profile)
{
static std::map<wxString, wxWebViewConfiguration> configs;
const auto existing = configs.find(profile);
if (existing != configs.end())
return existing->second;
#if defined(__WIN32__)
wxWebViewConfiguration config = wxWebView::NewConfiguration(wxWebViewBackendEdge);
#else
wxWebViewConfiguration config = wxWebView::NewConfiguration(wxWebViewBackendWebKit);
#endif
// Has to precede the first view, i.e. the environment/context built from the configuration.
config.SetDataPath(isolated_profile_path(profile));
return configs.emplace(profile, config).first->second;
}
#endif // !__WXOSX__
#ifdef __WIN32__
// Run Download and Install in another thread so we don't block the UI thread
DWORD DownloadAndInstallWV2RT() {
@@ -144,6 +192,9 @@ DWORD DownloadAndInstallWV2RT() {
class WebViewEdge : public wxWebViewEdge
{
public:
WebViewEdge() = default;
explicit WebViewEdge(const wxWebViewConfiguration& config) : wxWebViewEdge(config) {}
bool SetUserAgent(const wxString &userAgent) override
{
bool dark = userAgent.Contains("dark");
@@ -222,6 +273,11 @@ public:
{
}
explicit WebViewWebKit(const wxWebViewConfiguration& config)
: wxWebViewWebKit(config)
{
}
~WebViewWebKit() override
{
RemoveScriptMessageHandler("wx");
@@ -310,7 +366,7 @@ static wxString linux_user_agent()
}
#endif
wxWebView* WebView::CreateWebView(wxWindow * parent, wxString const & url)
wxWebView* WebView::CreateWebView(wxWindow * parent, wxString const & url, wxString const & profile)
{
#if wxUSE_WEBVIEW_EDGE
// Check if a fixed version of edge is present in
@@ -330,12 +386,38 @@ wxWebView* WebView::CreateWebView(wxWindow * parent, wxString const & url)
if (!url2.empty()) { url2 = wxURI(url2).BuildURI(); }
BOOST_LOG_TRIVIAL(trace) << __FUNCTION__ << ": " << url2.ToUTF8();
const bool isolated = !profile.IsEmpty();
#ifdef __WIN32__
wxWebView* webView = new WebViewEdge;
wxWebView* webView = nullptr;
if (isolated) {
// Reusing the configuration reuses its WebView2 environment, so every view of a profile
// belongs to the same browser profile and a login in one view is visible in another.
webView = new WebViewEdge(profile_configuration(profile));
} else {
webView = new WebViewEdge;
}
#elif defined(__WXOSX__)
wxWebView* webView = new WebViewWebKit;
wxWebView* webView = nullptr;
if (isolated) {
// wx has no SetDataPath on macOS, and WKWebView copies the configuration for each view
// (wx's "wx" script message handler lives on that per-view copy), so the views keep one
// configuration each and share a session through the profile's in-memory data store.
wxWebViewConfiguration config = wxWebView::NewConfiguration(wxWebViewBackendWebKit);
Slic3r::GUI::WKWebViewConfiguration_setSharedNonPersistentDataStore(config.GetNativeConfiguration(), profile);
webView = new WebViewWebKit(config);
} else {
webView = new WebViewWebKit;
}
#else
auto webView = wxWebView::New();
wxWebView* webView = nullptr;
if (isolated) {
// Reusing the configuration reuses its WebKitWebContext, so every view of a profile shares
// the same cookies, storage and live session.
webView = wxWebView::New(profile_configuration(profile));
} else {
webView = wxWebView::New();
}
#endif
if (webView) {
webView->SetBackgroundColour(StateColor::darkModeColorFor(*wxWHITE));
@@ -353,14 +435,25 @@ wxWebView* WebView::CreateWebView(wxWindow * parent, wxString const & url)
webView->RegisterHandler(wxSharedPtr<wxWebViewHandler>(new wxWebViewFSHandler("memory")));
#else
// With WKWebView handlers need to be registered before creation.
// On Linux (WebKit2GTK), URI schemes are registered globally and can only
// be registered once, so guard against multiple registrations.
#ifdef __linux__
// WebKitGTK registers a URI scheme on a WebKitWebContext, once per context, and wx answers
// a request through the view whose RegisterHandler() registered it. A view of the shared
// store has a context of its own, so it registers here. The views of a profile share one
// context, but registering from one of them would make every other view depend on that
// view's lifetime and would give untrusted plugin pages the local-file access of "wxfs";
// plugin pages load their own document only, so their context registers no scheme.
if (!isolated) {
webView->RegisterHandler(wxSharedPtr<wxWebViewHandler>(new wxWebViewArchiveHandler("wxfs")));
webView->RegisterHandler(wxSharedPtr<wxWebViewHandler>(new wxWebViewFSHandler("memory")));
}
#else
static bool s_schemes_registered = false;
if (!s_schemes_registered) {
webView->RegisterHandler(wxSharedPtr<wxWebViewHandler>(new wxWebViewArchiveHandler("wxfs")));
webView->RegisterHandler(wxSharedPtr<wxWebViewHandler>(new wxWebViewFSHandler("memory")));
s_schemes_registered = true;
}
#endif
webView->Create(parent, wxID_ANY, url2, wxDefaultPosition, wxDefaultSize, wxBORDER_NONE);
#ifdef __linux__
webView->SetUserAgent(linux_user_agent());
+6 -1
View File
@@ -14,7 +14,12 @@ wxDECLARE_EVENT(EVT_WEBVIEW_RECREATED, wxCommandEvent);
class WebView
{
public:
static wxWebView *CreateWebView(wxWindow *parent, wxString const &url);
// `profile` empty -> the shared default backend store used by all trusted UI.
// `profile` non-empty -> a private store keyed by `profile`, so this view shares no
// cookies/storage/session with the shared store or any other profile. Views created
// with the same `profile` share one store, and therefore one live session. Used for
// plugin-supplied (untrusted) content.
static wxWebView *CreateWebView(wxWindow *parent, wxString const &url, wxString const &profile = wxEmptyString);
#if wxUSE_WEBVIEW_EDGE
static bool CheckWebViewRuntime();
static bool DownloadAndInstallWebViewRuntime();
+3 -2
View File
@@ -172,7 +172,8 @@ WebViewHostDialog::WebViewHostDialog(wxWindow* parent,
bool WebViewHostDialog::create_webview(const std::string& resource_path,
const wxString& title,
const wxSize& dialog_size,
const wxSize& min_size)
const wxSize& min_size,
const wxString& profile)
{
SetTitle(title);
SetMinSize(FromDIP(min_size));
@@ -181,7 +182,7 @@ bool WebViewHostDialog::create_webview(const std::string& resource_path,
wxBoxSizer* topsizer = new wxBoxSizer(wxVERTICAL);
// Created empty and loaded below, after the user scripts are added, so the first load already has them.
m_browser = WebView::CreateWebView(this, wxEmptyString);
m_browser = WebView::CreateWebView(this, wxEmptyString, profile);
if (m_browser == nullptr) {
wxLogError("Could not init m_browser");
delete topsizer;
+2 -1
View File
@@ -38,7 +38,8 @@ public:
bool create_webview(const std::string& resource_path,
const wxString& title,
const wxSize& dialog_size = wxSize(820, 660),
const wxSize& min_size = wxSize(640, 640));
const wxSize& min_size = wxSize(640, 640),
const wxString& profile = wxEmptyString);
void load_url(const wxString& url);
bool run_script(const wxString& script);
+1
View File
@@ -12,6 +12,7 @@ extern double mac_max_scaling_factor();
extern void set_miniaturizable(void * window);
void WKWebView_evaluateJavaScript(void * web, wxString const & script, void (*callback)(wxString const &));
void WKWebView_setTransparentBackground(void * web);
void WKWebViewConfiguration_setSharedNonPersistentDataStore(void * configuration, const wxString & profile);
void WKWebView_force_display(void * web);
void set_tag_when_enter_full_screen(bool isfullscreen);
void set_title_colour_after_set_title(void * window);
+24
View File
@@ -102,6 +102,30 @@ void WKWebView_setTransparentBackground(void * web)
[webView registerForDraggedTypes: @[NSFilenamesPboardType]];
}
// Give a WKWebViewConfiguration the in-memory website data store of its profile, so the views of
// one profile share that store's cookies and storage without any of it reaching the disk or the
// default store. Views share a session only through a common store, and
// +nonPersistentDataStore makes a new one on every call, so one store is kept per profile for the
// process lifetime. Used to isolate plugin web views.
void WKWebViewConfiguration_setSharedNonPersistentDataStore(void * configuration, const wxString & profile)
{
static NSMutableDictionary<NSString *, WKWebsiteDataStore *> * stores = nil;
if (stores == nil)
stores = [[NSMutableDictionary alloc] init];
wxCFStringRef key_ref(profile);
NSString * key = key_ref.AsNSString();
WKWebsiteDataStore * store = [stores objectForKey:key];
if (store == nil) {
store = [WKWebsiteDataStore nonPersistentDataStore];
[stores setObject:store forKey:key];
}
WKWebViewConfiguration * config = (WKWebViewConfiguration*)configuration;
if (config)
config.websiteDataStore = store;
}
// Force a WKWebView to re-lay-out and repaint. Needed for chrome-less popups: the window is
// transparent, so a WKWebView whose layer has no pending frame leaves the whole window invisible
// until the user generates input (scroll/arrow). setNeedsDisplay alone does not always reach the
File diff suppressed because it is too large Load Diff
+196 -35
View File
@@ -4,7 +4,9 @@
// Via pybind11 so this file requests the same python3xx.lib as everything else.
#include <boost/filesystem/path.hpp>
#include <pybind11/conduit/wrap_include_python_h.h>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <functional>
#include <future>
@@ -60,9 +62,11 @@ enum class AuditEventCategory {
};
// Returns true if candidate resolves to a path inside allowed_root.
// Uses weakly_canonical and component-wise comparison to reject traversal attacks. A candidate
// whose final component is a dangling symlink is never inside: containment fails closed rather
// than authorizing the destination a write through it would create.
// Uses weakly_canonical and component-wise comparison to reject traversal attacks. On Windows both
// sides also have their 8.3 short names expanded, so the same directory spelled either way still
// compares equal. A candidate whose final component is a dangling symlink, or a path that cannot be
// normalized, is never inside: containment fails closed rather than authorizing the destination a
// write through it would create.
bool is_inside_allowed_root(const boost::filesystem::path& candidate,
const boost::filesystem::path& allowed_root);
@@ -148,6 +152,13 @@ public:
AuditDecision check_path_access(const boost::filesystem::path& candidate, bool is_write);
AuditDecision check_open(const std::string& path, const std::string& mode);
// True when deleting `target` is implicitly allowed because the entry lives in a writable
// allowed root, or is the root itself. Scope is decided by the canonical containing folder,
// never by resolving the final component: deleting a symlink acts on the link inside the
// root, and an outside link pointing into the root is not implicit. This is the FsDelete
// form of the allowed-root check; it preserves deny handling done earlier in the hook.
bool delete_target_inside_writable_allowed_root(const std::string& target) const;
// Ask the user to grant the requested permissions. The request may originate on a plugin
// 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
@@ -160,20 +171,42 @@ public:
// 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
// and is only recognized as the final path component; elsewhere it is an ordinary character.
// The wildcard applies to fs_read and fs_readwrite only, never to event grants or the other
// buckets, and a read grant still never authorizes a write (or the reverse). Denied paths
// stay denied regardless of a covering wildcard.
// The wildcard applies to fs_read, fs_readwrite, fs_create and fs_delete; it never applies to
// event grants or the other buckets, and a read grant still never authorizes a write (or the
// reverse). Denied paths stay denied regardless of a covering wildcard.
//
// A relative tree grant is resolved against the working directory when the request is made:
// the prompt shows, and the sidecar stores, the absolute scope it covers. Exact grants and
// the non-filesystem buckets are stored as requested.
// the prompt shows, and the sidecar stores, the absolute scope it covers. Read/read-write
// exact grants and the non-filesystem buckets are stored as requested; create/delete folders
// are always stored as canonical absolute paths (see below).
//
// fs_create and fs_delete name folders, not files. A literal folder entry grants creating or
// deleting the entries directly inside that folder, never inside a subfolder. A tree entry
// "<folder>/*" grants the same for that folder and every folder beneath it, at any depth. A
// request for "*" on its own asks for unrestricted access to that operation; a "*" anywhere
// else, except as the final component of a tree entry, and any other wildcard, makes the
// declaration fail closed. A relative folder or tree root is resolved against the working
// directory and stored in canonical absolute form. A tree rooted at a filesystem, drive, or
// network share root (for example "/*", "C:\*", or a UNC share root) covers that whole
// filesystem, drive, or network share; its prompt says so explicitly. Denied paths stay
// denied. At runtime, approving either operation stores the
// parent folder of the target (a direct grant, not a tree grant), and the prompt shows that
// canonical folder rather than the target. A recursive delete (shutil.rmtree) is the
// exception: a direct folder grant is insufficient, so it needs a saved tree grant covering
// the target or one-time consent for the canonical subtree. That consent is never stored; see
// the recursive-delete consent helpers below. A runtime folder whose own name contains "*" is
// never prompted for or stored, because the sidecar would read it as a tree grant. The GUI
// thread then lets the operation proceed; a worker-thread approval denies the current
// operation, which has to be retried.
//
// Tree grants are matched on canonical paths: a symlink below the granted folder does not
// extend the grant outside it, and a grant whose root is a symlink applies to its target. A
// target whose final component is a dangling symlink is never covered, since a write through
// it would create the link's target rather than the path the grant describes. Exact grants
// match verbatim; absolute exact grants also match canonical-equivalent paths, including
// relative targets resolved against the working directory at the time of the check.
// relative targets resolved against the working directory at the time of the check. For
// create and delete, a tree grant covers every target whose containing folder is its root or
// any folder below it.
bool request_permissions(const std::string& plugin_key, const PluginPermissions& requested);
// Ask the user to grant network access to the given http(s) URLs. Each URL is reduced to its
@@ -190,6 +223,73 @@ public:
// userinfo and port are discarded; scheme and host are lowercased.
static std::string normalize_network_url(const std::string& url);
// True when `target` is a create/delete tree grant: a folder path ending in "/*". "*" on its
// own is the separate full-access form and returns false, as does any wildcard outside the
// final component. The declared root may be relative and may contain "." or "..";
// request_permissions resolves it against the working directory and stores it canonically.
static bool is_create_delete_tree_grant(const std::string& target);
// --- recursive delete consent ---
// A recursive delete (shutil.rmtree) is authorised only by saved delete grants covering the
// whole operation, or by a one-time consent for that subtree. A plain folder grant is
// insufficient even when it names the target folder or its parent: it authorises deleting
// direct entries, not walking and deleting a whole subtree. A tree grant rooted exactly at
// the target covers the entries inside it but not deleting the target folder itself, which
// is an entry in the parent; that final removal needs the parent covered separately or the
// one-time consent. One-time consent is never written to the sidecar.
//
// When the prompt cannot run inline (the event is raised off the wx main thread), the current
// attempt is denied and the dialog is posted. A Yes records a short-lived (one minute),
// single-use approval bound to the plugin key and canonical subtree root. `add_` and
// `consume_` are the in-memory store used by that retry path; the first matching retry
// consumes the approval. They are thread-safe, bound in time, and never authorise a different
// plugin or target. A prompt already pending for the same pair is not posted again.
//
// A permission edit, revocation, or reinstall invalidates the plugin's transient approvals,
// pending prompt keys, and any queued dialog callback: posted callbacks carry the generation
// they were created for and become no-ops after invalidation.
void invalidate_recursive_delete_state(const std::string& plugin_key);
bool consume_recursive_delete_approval(const std::string& plugin_key, const std::string& canonical_root);
void add_recursive_delete_approval(const std::string& plugin_key, const std::string& canonical_root);
// Answers a recursive-delete consent prompt in place of the dialog, for tests.
// `target` is the canonical subtree root the consent covers. Production never sets it.
using RecursiveDeletePrompt = std::function<bool(const std::string& plugin_name, const std::string& target)>;
static void set_recursive_delete_prompt_for_testing(RecursiveDeletePrompt prompt);
// Simulates a prompt that cannot run inline on the wx main thread: with `background` true the
// current attempt is denied, and a Yes from the testing prompt records a retry approval.
static void set_recursive_delete_prompt_background_for_testing(bool background);
// Returns the recursive-delete prompt exactly as the dialog receives it, for tests.
static std::string format_recursive_delete_permission_prompt_for_testing(const std::string& plugin_name,
const std::string& target,
bool root_scope = false,
bool background = false);
// Test-only lifecycle hooks: clear pending retry approvals, shorten their lifetime, or read
// how many are pending. Production never calls them.
static void clear_recursive_delete_approvals_for_testing();
static void set_recursive_delete_approval_lifetime_for_testing(std::chrono::milliseconds lifetime);
static std::size_t pending_recursive_delete_approvals_for_testing();
// Test-only control for the posted-prompt path. With `deferred` true, a background request
// records its deduplication key but leaves it pending instead of treating the testing prompt's
// answer as final; answer_recursive_delete_prompt_for_testing() then completes it, as the real
// dialog callback would. `generation` is the token read when the prompt was posted; answering
// with a stale token does not store an approval.
static void set_recursive_delete_prompt_deferred_for_testing(bool deferred);
static std::uint64_t recursive_delete_generation_for_testing(const std::string& plugin_key);
static void answer_recursive_delete_prompt_for_testing(const std::string& plugin_key,
const std::string& canonical_root, bool granted,
std::uint64_t generation);
static std::size_t pending_recursive_delete_prompts_for_testing();
// Exposes the entry-scope predicate used for nested deletes without requiring a live Python
// frame. The subtree must be canonical and absolute.
static bool delete_target_inside_subtree_for_testing(const std::string& target,
const std::string& canonical_subtree);
// True when a granted scheme://host entry covers `target`. `target` is a URL (urllib.Request),
// a bare host (http.client.connect, socket.getaddrinfo) or an address as exposed by the audit
// event (a hostname, a host:port pair, or a legacy persisted tuple such as "('host', 443)").
@@ -215,18 +315,57 @@ public:
// library code the operation calls back into is judged on its own. A frame is let go once it
// returns, a suspended generator's (os.walk) when the audit scope ends. Letting a frame go may
// run finalizers of objects its locals held; they are judged as the plugin and never prompt.
void record_root_frame();
bool covered_by_root_frame() const;
//
// The root's category is recorded too. A delete root (shutil.rmtree) does not cover nested
// delete events by itself: an exact folder grant covers only its direct entries, so each
// nested delete is judged on its own, while a tree grant covering the target may still allow
// it. One-time recursive-delete consent records its canonical subtree on the frame, which
// covers nested deletes whose target stays inside that subtree. A read/write root (copytree,
// unpack_archive, move) still covers the create/delete events it performs.
// `approved_delete_subtree`, when non-empty, is the canonical subtree a one-time recursive
// delete consent covers.
void record_root_frame(AuditEventCategory category,
const boost::filesystem::path& approved_delete_subtree = {});
// `allow_delete_roots` is false for a delete event: a frame recorded for a delete root then
// does not cover it, while a read/write root still does.
bool covered_by_root_frame(bool allow_delete_roots = true) const;
// True when every delete target is inside the subtree of a delete root frame recorded with a
// subtree scope (one-time consent or an implicit writable root), and the stack between the
// event and that frame is stdlib code only. This keeps the scope to the approved operation
// and its subtree; plugin callbacks the operation invokes are judged on their own. Protected
// paths are denied before this check.
bool delete_target_inside_approved_subtree(const std::vector<std::string>& targets) const;
bool releasing_frames() const;
// True when code from `filename` (a code object's co_filename) is the interpreter's own
// stdlib: the only code a root frame's coverage passes through. Valid after install_hook().
static bool is_stdlib_file(const std::string& filename);
// Answers permission prompts in place of the dialog, for tests. Production never sets it.
using PermissionPrompt = std::function<bool(const std::string& event_name, const std::vector<std::string>& targets)>;
// One target a runtime permission prompt covers: the path that triggered the prompt and, for
// create and delete, the folder a Yes saves as the persistent grant.
struct PermissionPromptEntry {
std::string target;
std::string grant_folder;
bool operator==(const PermissionPromptEntry& other) const
{
return target == other.target && grant_folder == other.grant_folder;
}
};
// Answers permission prompts in place of the dialog, for tests. `targets` are the persisted
// grants; `entries` pairs each runtime create/delete target with the folder a Yes saves.
// Production never sets it.
using PermissionPrompt = std::function<bool(const std::string& event_name, const std::vector<std::string>& targets,
const std::vector<PermissionPromptEntry>& entries)>;
static void set_permission_prompt_for_testing(PermissionPrompt prompt);
// Returns the runtime create/delete prompt exactly as the dialog receives it, for tests.
// `entries` pairs each triggering target with the folder a Yes saves.
static std::string format_create_delete_permission_prompt_for_testing(
AuditEventCategory category, const std::string& plugin_name,
const std::vector<PermissionPromptEntry>& entries);
// Answers the combined permission-request prompt in place of the dialog, receiving the message
// it would show. Tests run without a wxApp, so this seam also stands in for the app check.
// Production never sets it.
@@ -247,6 +386,18 @@ private:
PluginAuditManager() = default;
// A stdlib frame that raised an operation's own root event. The vector that holds these owns
// one strong reference per frame. delete_root marks a frame recorded for a delete root: such
// a frame does not cover a nested delete by itself (see covered_by_root_frame), unless it also
// records the canonical subtree of a one-time recursive-delete consent. The mark is sticky
// once set, even if the same frame later raises another root event.
struct RootFrame
{
PyObject* frame; // strong reference
bool delete_root;
boost::filesystem::path approved_delete_subtree; // empty unless one-time consent
};
static int audit_hook(const char* event, PyObject* args, void* user_data);
// True for paths inside the interpreter's stdlib, excluding site-packages. Unlike
@@ -255,12 +406,12 @@ private:
static bool is_stdlib_path(const boost::filesystem::path& path);
// Drops the references in `frames`, keeping the caller's error and denial state intact.
void release_frames(std::vector<PyObject*>& frames);
void release_frames(std::vector<RootFrame>& frames);
static thread_local std::string m_current_plugin_key;
static thread_local std::string m_current_capability_name;
static thread_local std::vector<AllowedRoot> m_scoped_allowed_roots;
static thread_local std::vector<PyObject*> m_root_frames; // strong references
static thread_local std::vector<RootFrame> m_root_frames;
static thread_local int m_releasing_frames;
static thread_local bool m_audit_denial_pending;
static thread_local bool m_has_last_violation;
@@ -294,20 +445,21 @@ public:
ScopedPluginAuditContext& operator=(const ScopedPluginAuditContext&) = delete;
private:
std::string m_plugin_key;
std::string m_capability;
std::string m_previous_id;
std::string m_previous_capability;
std::vector<AllowedRoot> m_previous_scoped_roots;
std::vector<PyObject*> m_previous_root_frames;
std::string m_plugin_key;
std::string m_capability;
std::string m_previous_id;
std::string m_previous_capability;
std::vector<AllowedRoot> m_previous_scoped_roots;
std::vector<PluginAuditManager::RootFrame> 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.
// What a queued prompt asks the user. A runtime event, a create/delete target and a recursive
// delete consent can all grant what they show; a load-time declaration grants every bucket it
// lists.
enum class AuditPromptKind {
RuntimeEvent,
DeclaredPermissions,
DeniedOperation,
RecursiveDeleteConsent,
};
// The plugin lifecycle facts the prompt drain consults. Plain data so the lifetime decision is
@@ -353,8 +505,10 @@ private:
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).
// One audit decision awaiting a user answer. `keys` is what a Yes persists; `shown` is the target
// list a prompt without entries lists (empty for an event that is granted by name). `entries`
// pairs each runtime create/delete target with the folder a Yes saves, so a queued prompt shows
// the same triggering paths as an inline one.
struct AuditPromptRequest
{
AuditPromptKind kind = AuditPromptKind::RuntimeEvent;
@@ -365,12 +519,18 @@ struct AuditPromptRequest
bool by_event = false;
std::vector<std::string> keys;
std::vector<std::string> shown;
std::vector<PluginAuditManager::PermissionPromptEntry> entries;
// DeclaredPermissions only: the missing buckets the combined dialog lists.
std::vector<AuditPromptBucket> 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;
// RecursiveDeleteConsent only: the canonical subtree root in `shown`, whether it is a
// filesystem/drive/share root, and the permission generation the answer is valid for. The
// consent is one-time and never persisted; a generation change invalidates the answer.
bool root_scope = false;
std::uint64_t recursive_delete_generation = 0;
// Set only when a worker is blocked waiting for the answer.
std::shared_ptr<AuditPromptCompletion> completion;
};
@@ -388,7 +548,8 @@ public:
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
Rejected // a synchronous-only caller found the queue busy, or the bounded
// recursive-delete consent set is at capacity: nothing was stored
};
// Presents a request synchronously only when the queue is idle. Busy callers are rejected
@@ -400,12 +561,6 @@ public:
// 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<AuditPromptRequest> take_next();
@@ -435,9 +590,15 @@ public:
// started. Used when a plugin is unloaded or removed.
void discard_plugin(const std::string& plugin_key);
// Drops queued recursive-delete consents for one plugin when its permission state changes.
// An active consent dialog cannot be withdrawn; the generation it carries makes its late
// answer a no-op.
void discard_recursive_delete_consents(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.
// Equality over what the prompt asks and what a Yes would grant, plus the plugin it is
// granted to. Distinct categories, plugins, targets, triggering paths, or event grants are
// never considered equivalent, so coalescing cannot hide a prompt or widen a grant.
static bool same_request(const AuditPromptRequest& a, const AuditPromptRequest& b);
bool contains_locked(const AuditPromptRequest& request) const;
+38
View File
@@ -11,6 +11,7 @@
#include <boost/system/error_code.hpp>
#include <boost/log/trivial.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/nowide/cstdio.hpp>
#include <boost/nowide/fstream.hpp>
#include <ios>
@@ -82,6 +83,39 @@ boost::filesystem::path resolve_plugin_root_from_descriptor(const PluginDescript
return {};
}
bool is_filesystem_root(const boost::filesystem::path& root)
{
if (!root.is_absolute())
return false;
#ifdef _WIN32
const auto is_separator = [](char c) { return c == '/' || c == '\\'; };
const std::string path = root.string();
std::vector<std::string> components;
for (size_t start = 0; start < path.size();) {
while (start < path.size() && is_separator(path[start]))
++start;
size_t end = start;
while (end < path.size() && !is_separator(path[end]))
++end;
if (end > start && path.compare(start, end - start, ".") != 0)
components.emplace_back(path.substr(start, end - start));
start = end;
}
if (path.size() >= 2 && is_separator(path[0]) && is_separator(path[1])) {
if (components.size() == 4 && components[0] == "?" &&
boost::algorithm::iequals(components[1], std::string("UNC")))
return true; // \\?\UNC\server\share
return components.size() == 2; // \\server\share or an extended drive root \\?\C:
}
return components.size() == 1 && components[0].size() == 2 && components[0][1] == ':';
#else
return root == root.root_path();
#endif
}
bool is_plugin_root_allowed(const boost::filesystem::path& candidate_root, const std::vector<std::string>& allowed_dirs)
{
boost::system::error_code ec;
@@ -935,6 +969,8 @@ InstallStateReadStatus read_install_state_status(const boost::filesystem::path&
};
read_string_list("fs_read", parsed.permissions.fs_read);
read_string_list("fs_readwrite", parsed.permissions.fs_readwrite);
read_string_list("fs_create", parsed.permissions.fs_create);
read_string_list("fs_delete", parsed.permissions.fs_delete);
read_string_list("network_http", parsed.permissions.network_http);
read_string_list("network_socket", parsed.permissions.network_socket);
read_string_list("process", parsed.permissions.process);
@@ -1108,6 +1144,8 @@ bool write_install_state(const boost::filesystem::path& plugin_dir, const Plugin
json["permissions"] = {
{"fs_read", state.permissions.fs_read},
{"fs_readwrite", state.permissions.fs_readwrite},
{"fs_create", state.permissions.fs_create},
{"fs_delete", state.permissions.fs_delete},
{"network_http", state.permissions.network_http},
{"network_socket", state.permissions.network_socket},
{"process", state.permissions.process},
+21
View File
@@ -23,6 +23,20 @@ struct PluginPermissions
// component. Reads and writes stay separate buckets: a wildcard in one never grants the other.
std::vector<std::string> fs_read;
std::vector<std::string> fs_readwrite;
// Create and delete grants name folders rather than individual targets: a literal folder
// entry grants creating or deleting entries directly inside that folder, not inside its
// subfolders. An entry ending in "/*" is a tree grant that also covers every folder below
// that root, at any depth. Empty means no grant. A sole "*" grants the operation anywhere;
// any other entry must be an absolute folder or tree path, and a relative or unreadable
// entry never matches. A "*" beside other entries is treated as an ordinary (non-matching)
// entry, so full access is never implied by accident; permission declarations reject such a
// mixed list together with every other wildcard. Runtime prompts store the canonical parent
// folder of the approved target (an exact grant, not a tree grant); a runtime parent folder
// whose own name contains "*" is refused instead of stored, because the sidecar would read
// it as a broader tree grant. A tree grant at a filesystem, drive, or network share root
// covers that whole filesystem, drive, or network share.
std::vector<std::string> fs_create;
std::vector<std::string> fs_delete;
std::vector<std::string> network_http;
std::vector<std::string> network_socket;
std::vector<std::string> process;
@@ -60,6 +74,13 @@ std::string get_orca_plugins_dir();
boost::filesystem::path resolve_plugin_root_from_descriptor(const PluginDescriptor& descriptor);
// True when `root` is a filesystem root: POSIX "/", a Windows drive root such as "C:\", or a
// UNC/network share root such as "\\server\share\" (including the extended-length forms
// "\\?\C:\" and "\\?\UNC\server\share\"). A tree grant rooted here covers the whole filesystem,
// volume, or network share, not one folder, so the permission prompt must say so instead of
// presenting it as an ordinary nested folder.
bool is_filesystem_root(const boost::filesystem::path& root);
bool is_plugin_root_allowed(const boost::filesystem::path& candidate_root,
const std::vector<std::string>& allowed_dirs);
+8
View File
@@ -65,6 +65,8 @@ std::vector<std::string>* permission_bucket(PluginPermissions& permissions, Plug
switch (category) {
case PluginPermissionCategory::FsRead: return &permissions.fs_read;
case PluginPermissionCategory::FsReadWrite: return &permissions.fs_readwrite;
case PluginPermissionCategory::FsCreate: return &permissions.fs_create;
case PluginPermissionCategory::FsDelete: return &permissions.fs_delete;
case PluginPermissionCategory::NetworkHttp: return &permissions.network_http;
case PluginPermissionCategory::NetworkSocket: return &permissions.network_socket;
case PluginPermissionCategory::Process: return &permissions.process;
@@ -1416,6 +1418,9 @@ bool PluginManager::mutate_plugin_permissions(const std::string& plugin_key, con
if (applied != nullptr)
*applied = state.permissions;
// Pending recursive-delete consents were granted against the previous permission state.
PluginAuditManager::instance().invalidate_recursive_delete_state(plugin_key);
BOOST_LOG_TRIVIAL(info) << "Applied permission changes for plugin " << plugin_key;
return true;
}
@@ -1438,6 +1443,9 @@ void PluginManager::revoke_plugin_permissions(const std::string& plugin_key)
state.permissions = {};
if (!write_install_state(root, state))
BOOST_LOG_TRIVIAL(warning) << __FUNCTION__ << ": Failed to revoke permissions for " << plugin_key;
// A revoke or reinstall invalidates transient recursive-delete consents and queued callbacks.
PluginAuditManager::instance().invalidate_recursive_delete_state(plugin_key);
}
// ── Callbacks ───────────────────────────────────────────────────────────────────────────────
+2
View File
@@ -117,6 +117,8 @@ struct ScriptCompletion
enum class PluginPermissionCategory {
FsRead,
FsReadWrite,
FsCreate,
FsDelete,
NetworkHttp,
NetworkSocket,
Process,
+63 -6
View File
@@ -189,6 +189,7 @@ std::vector<CapturedCapability> PythonPluginBridge::finalize_plugin_capture(cons
}
const bool has_permission_request =
!requested_permissions.fs_read.empty() || !requested_permissions.fs_readwrite.empty() ||
!requested_permissions.fs_create.empty() || !requested_permissions.fs_delete.empty() ||
!requested_permissions.network_http.empty() || !requested_permissions.network_socket.empty() ||
!requested_permissions.process.empty() || requested_permissions.threading;
if (has_permission_request) {
@@ -569,7 +570,9 @@ void bind_python_api(pybind11::module_& m)
const std::vector<std::string>& network_socket,
const std::vector<std::string>& process,
bool threading,
const std::vector<std::string>& network) {
const std::vector<std::string>& network,
const std::vector<std::string>& fs_create,
const std::vector<std::string>& fs_delete) {
if (g_active_plugin_key.empty())
throw py::value_error("request_permissions() called outside plugin discovery context");
@@ -583,10 +586,34 @@ void bind_python_api(pybind11::module_& m)
};
reject_empty("fs_read", fs_read);
reject_empty("fs_readwrite", fs_readwrite);
reject_empty("fs_create", fs_create);
reject_empty("fs_delete", fs_delete);
reject_empty("network_http", network_http);
reject_empty("network_socket", network_socket);
reject_empty("process", process);
// Create/delete declarations name folders. A trailing "/*" is a tree grant covering
// the folder and its subfolders; a sole "*" is the full-access form. Any other
// wildcard is rejected instead of being stored as a literal folder name or widened
// into a grant. request_permissions() resolves and validates the path itself.
const auto validate_folder_entries = [](const char* name, const std::vector<std::string>& folders) {
const bool full_access = folders.size() == 1 && folders.front() == "*";
for (const std::string& folder : folders) {
if (folder == "*") {
if (!full_access)
throw py::value_error(std::string("request_permissions(") + name +
"=...) accepts \"*\" only on its own");
continue;
}
if (folder.find('*') != std::string::npos &&
!PluginAuditManager::is_create_delete_tree_grant(folder))
throw py::value_error(std::string("request_permissions(") + name +
"=...) accepts \"*\" only as the final /* of a folder tree");
}
};
validate_folder_entries("fs_create", fs_create);
validate_folder_entries("fs_delete", fs_delete);
// A network URL is reduced to scheme://host, so one grant covers every path, query
// and port on that host. It is recorded as an HTTP grant; network_permission_matches
// applies that grant to raw socket events for the same host too.
@@ -613,6 +640,8 @@ void bind_python_api(pybind11::module_& m)
add_targets(requested.fs_read, fs_read);
add_targets(requested.fs_readwrite, fs_readwrite);
add_targets(requested.fs_create, fs_create);
add_targets(requested.fs_delete, fs_delete);
add_targets(requested.network_http, network_http);
add_targets(requested.network_http, normalized_network);
add_targets(requested.network_socket, network_socket);
@@ -628,6 +657,8 @@ void bind_python_api(pybind11::module_& m)
py::arg("process") = std::vector<std::string>{},
py::arg("threading") = false,
py::arg("network") = std::vector<std::string>{},
py::arg("fs_create") = std::vector<std::string>{},
py::arg("fs_delete") = std::vector<std::string>{},
R"pbdoc(Request permissions while OrcaSlicer loads your module.
Each bucket takes the target strings the plugin expects the corresponding audit event to
@@ -635,14 +666,40 @@ report: filesystem paths for fs_read and fs_readwrite, URLs for network_http, so
for network_socket, and commands for process. threading=True requests permission to start
threads. Targets already granted to the plugin are not asked for again.
fs_create and fs_delete take folders rather than files. A literal folder entry grants creating
or deleting entries directly inside that folder, not inside its subfolders. An entry ending in
"/*" is a tree grant: it grants the same for that folder and for every folder below it, at any
depth, for example "/path/to/folder/*". A tree rooted at a filesystem, drive, or network share
root, such as "/*", "C:\\*", or a UNC share root, covers that entire filesystem, drive, or
network share. A relative folder or tree root is
resolved against the working directory when the request is made. Pass "*" on its own for
unrestricted create or delete access; a "*" mixed with other entries is rejected, and a "*"
anywhere other than the final /* of a folder tree is rejected. At runtime, approving a create or
delete prompt stores the parent folder of the approved target as a direct grant, and the prompt
lists that canonical folder; a parent folder whose own name contains "*" is refused rather than
stored. On the main thread the operation then proceeds; a request raised on a worker thread
denies the current operation, so the plugin has to retry it after approval.
A recursive delete (shutil.rmtree) is a subtree operation. A literal folder grant is not
enough, even when it names the target folder or its parent. A saved fs_delete tree grant covers
the entries inside its root; deleting the root folder itself is covered only when the folder
containing that root is also granted. Otherwise the user is asked for one-time consent for the
canonical target subtree before the walk starts. That consent is never saved, covers only that
operation, and a prompt that has to be posted to a worker thread applies to one matching retry
within its short lifetime. Nested deletes inside the approved subtree proceed without another
prompt; denied paths stay blocked. A permission edit, revocation, or reinstall discards any
pending recursive-delete consent, so an old prompt cannot grant access to the reinstalled code.
A filesystem target may end in "/*" to grant a whole directory tree, for example
"/path/to/folder/*". That covers the folder itself and every path beneath it, at any depth.
"*" is the only wildcard and is recognized only as the final path component; a "*" anywhere
else in a target is an ordinary character. Wildcards apply to fs_read and fs_readwrite only,
and a grant in one of those buckets never authorizes the other direction. Tree grants are
matched on canonical paths, so a symlink below the granted folder does not extend the grant
outside it. Paths the host denies by name or keyword stay denied even when a wildcard covers
them.
else in a target is an ordinary character. Tree grants apply to fs_read, fs_readwrite,
fs_create and fs_delete, and a grant in one bucket never authorizes another direction. For
fs_delete, the tree covers deleting entries inside the folder and below, not deleting the
folder root itself; that removal needs the parent folder granted. Tree
grants are matched on canonical paths, so a symlink below the granted folder does not extend
the grant outside it. Paths the host denies by name or keyword stay denied even when a
wildcard covers them.
`network` also lists http(s) URLs, but each is reduced to its scheme and host, so one grant covers
every path, query and port on that host and also authorizes raw socket events for it. The host
+54 -25
View File
@@ -89,15 +89,20 @@ CallablePtr make_holder(py::object obj)
// Adapt a Python callable to a GUI message handler that acquires the GIL and
// swallows/logs exceptions (a raising handler must not escape into wx events).
GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message)
//
// The handler runs later, from a wx event with no plugin call on the stack, so it restores the
// plugin's audit context captured at registration. Without that scope, audit events raised by
// the callback would be unattributed and allowed, like host code.
GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message, std::string plugin_key)
{
CallablePtr holder = make_holder(std::move(on_message));
if (!holder)
return nullptr;
return [holder](const json& data) {
return [holder, plugin_key = std::move(plugin_key)](const json& data) {
PythonGILState gil;
if (!gil)
return;
ScopedPluginAuditContext audit(plugin_key);
try {
holder->fn(json_to_py(data));
} catch (py::error_already_set& e) {
@@ -107,15 +112,16 @@ GUI::WebDialog::MessageHandler make_message_adapter(py::object on_message)
};
}
GUI::WebDialog::SubmitHandler make_submit_adapter(py::object on_submit)
GUI::WebDialog::SubmitHandler make_submit_adapter(py::object on_submit, std::string plugin_key)
{
CallablePtr holder = make_holder(std::move(on_submit));
if (!holder)
return nullptr;
return [holder](const json& data) {
return [holder, plugin_key = std::move(plugin_key)](const json& data) {
PythonGILState gil;
if (!gil)
return;
ScopedPluginAuditContext audit(plugin_key);
try {
holder->fn(json_to_py(data));
} catch (py::error_already_set& e) {
@@ -127,14 +133,15 @@ GUI::WebDialog::SubmitHandler make_submit_adapter(py::object on_submit)
// The plugin's on_close: fired only on a user/JS-initiated close (not forced teardown), while the
// window is alive. Empty if the plugin passed None.
std::function<void()> make_close_adapter(const CallablePtr& holder)
std::function<void()> make_close_adapter(const CallablePtr& holder, std::string plugin_key)
{
if (!holder)
return nullptr;
return [holder]() {
return [holder, plugin_key = std::move(plugin_key)]() {
PythonGILState gil;
if (!gil)
return;
ScopedPluginAuditContext audit(plugin_key);
try {
holder->fn();
} catch (py::error_already_set& e) {
@@ -144,6 +151,17 @@ std::function<void()> make_close_adapter(const CallablePtr& holder)
};
}
// A window or panel is untrusted plugin content, isolated by a per-plugin webview profile.
// An empty key would fall back to the shared profile used by trusted host UI, so refuse it
// instead of creating a window that silently shares the host's cookies and session.
std::string plugin_identity_for_ui(const char* api_name)
{
std::string plugin_key = PluginAuditManager::instance().current_plugin();
if (plugin_key.empty())
throw std::runtime_error(std::string(api_name) + " must be called from a plugin callback");
return plugin_key;
}
// --------------------------------------------------------------------------
// Registry of live plugin UI resources. Keyed by an opaque id; tracks the
// owning plugin so all of a plugin's UI can be torn down on unload.
@@ -373,13 +391,6 @@ struct UiProgressHandle
py::object ui_create_window(const std::string& html, const std::string& title, int width, int height,
py::object on_message, py::object on_close, long style, py::object on_submit)
{
auto msg_adapter = make_message_adapter(std::move(on_message));
auto submit_adapter = make_submit_adapter(std::move(on_submit));
CallablePtr close_holder = make_holder(std::move(on_close));
const std::string plugin_key = PluginAuditManager::instance().current_plugin();
const int w = width > 0 ? width : 820;
const int h = height > 0 ? height : 600;
if ((style & ~WINDOW_MODAL) != 0)
throw std::invalid_argument("unsupported orca.host.ui.create_window style flags");
const bool modal = (style & WINDOW_MODAL) != 0;
@@ -387,6 +398,14 @@ py::object ui_create_window(const std::string& html, const std::string& title, i
if (wxTheApp == nullptr)
throw std::runtime_error("OrcaSlicer application is not initialized");
const std::string plugin_key = plugin_identity_for_ui("orca.host.ui.create_window");
const int w = width > 0 ? width : 820;
const int h = height > 0 ? height : 600;
auto msg_adapter = make_message_adapter(std::move(on_message), plugin_key);
auto submit_adapter = make_submit_adapter(std::move(on_submit), plugin_key);
CallablePtr close_holder = make_holder(std::move(on_close));
// The whole wxWindow/webview creation is deferred to a clean main-loop iteration.
// The WebKit backends deliver script messages synchronously from inside the native
// callback (GTK: HandleWindowEvent in wxgtk_webview_webkit_script_message_received,
@@ -415,13 +434,14 @@ py::object ui_create_window(const std::string& html, const std::string& title, i
if (!UiRegistry::instance().is_open(new_id))
return;
GUI::WebDialog::CloseHandler on_close = make_close_adapter(close_holder);
GUI::WebDialog::CloseHandler on_close = make_close_adapter(close_holder, plugin_key);
// Registry cleanup: GIL-free, runs from the dialog destructor on every path.
auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); };
auto* dlg = new GUI::WebDialog(ui_parent(), wxString::FromUTF8(title), html,
wxSize(w, h), std::move(msg_adapter), std::move(submit_adapter),
std::move(on_close), std::move(on_destroyed), PLUGIN_WX_STYLE);
std::move(on_close), std::move(on_destroyed), PLUGIN_WX_STYLE,
wxString::FromUTF8(plugin_key));
UiRegistry::instance().bind(new_id, dlg, plugin_key);
if (modal) {
dlg->ShowModal();
@@ -492,15 +512,16 @@ py::object ui_create_dock_panel(const std::string& html, const std::string& titl
if (std::find(std::begin(DOCK_POSITIONS), std::end(DOCK_POSITIONS), dock) == std::end(DOCK_POSITIONS))
throw std::invalid_argument("orca.host.ui.create_dock_panel dock must be \"left\", \"right\", \"bottom\" or \"float\"");
auto msg_adapter = make_message_adapter(std::move(on_message));
CallablePtr close_holder = make_holder(std::move(on_close));
const std::string plugin_key = PluginAuditManager::instance().current_plugin();
const int w = width > 0 ? width : 320;
const int h = height > 0 ? height : 480;
if (wxTheApp == nullptr)
throw std::runtime_error("OrcaSlicer application is not initialized");
const std::string plugin_key = plugin_identity_for_ui("orca.host.ui.create_dock_panel");
const int w = width > 0 ? width : 320;
const int h = height > 0 ? height : 480;
auto msg_adapter = make_message_adapter(std::move(on_message), plugin_key);
CallablePtr close_holder = make_holder(std::move(on_close));
// Deferred and pre-bound for the same reasons as create_window().
const int new_id = UiRegistry::instance().reserve_id();
UiRegistry::instance().bind(new_id, nullptr, plugin_key);
@@ -517,8 +538,8 @@ py::object ui_create_dock_panel(const std::string& html, const std::string& titl
}
auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); };
auto* panel = new GUI::DockPanel(plater, html, std::move(msg_adapter), make_close_adapter(close_holder),
std::move(on_destroyed));
auto* panel = new GUI::DockPanel(plater, html, std::move(msg_adapter), make_close_adapter(close_holder, plugin_key),
std::move(on_destroyed), wxString::FromUTF8(plugin_key));
UiRegistry::instance().bind(new_id, panel, plugin_key);
plater->add_dock_pane(panel, GUI::plugin_pane_name(plugin_key, title), wxString::FromUTF8(title), dock,
wxSize(w, h), [panel]() { panel->fire_close(); });
@@ -640,18 +661,26 @@ void plater_notification(GUI::NotificationManager::NotificationLevel notificatio
{
const std::string plugin_key = PluginAuditManager::instance().current_plugin();
CallablePtr holder = make_holder(std::move(on_click));
if (holder)
if (holder) {
// The click runs later, from a wx event with no plugin call on the stack. Without an
// identity there is no audit context to restore, so refuse the callback rather than run
// plugin code unattributed and allowed like host code. A notification with no callback
// keeps its previous behavior.
if (plugin_key.empty())
throw std::runtime_error("orca.host.ui.push_notification on_click must be called from a plugin callback");
UiRegistry::instance().bind_callback(holder, plugin_key);
}
std::function<bool(wxEvtHandler*)> callback;
if (holder) {
callback = [holder](wxEvtHandler*) -> bool {
callback = [holder, plugin_key](wxEvtHandler*) -> bool {
if (!holder->active.load(std::memory_order_acquire))
return false;
PythonGILState gil;
if (!gil)
return false;
ScopedPluginAuditContext audit(plugin_key);
try {
py::object result = holder->fn();
return result.is_none() || result.cast<bool>();
+2 -1
View File
@@ -78,7 +78,8 @@ constexpr char PLUGIN_PAGE_BRIDGE_JS[] = R"JS(
} // namespace
PluginPage::PluginPage(wxWindow* parent, std::shared_ptr<PagesPluginCapability> capability)
: GUI::WebPanel(parent, PLUGIN_PAGE_BRIDGE_JS)
: GUI::WebPanel(parent, PLUGIN_PAGE_BRIDGE_JS,
wxString::FromUTF8(capability ? capability->identity().plugin_key : std::string()))
, m_cap(std::move(capability))
, m_lifetime(std::make_shared<std::atomic<PluginPage*>>(this))
{
File diff suppressed because it is too large Load Diff
+87 -3
View File
@@ -242,9 +242,11 @@ TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's ins
REQUIRE(read_install_state(plugin_dir, state));
CHECK(state.installed_version == "1.2.0");
state.permissions.fs_read = {"/path/to/read"};
state.permissions.fs_readwrite = {"/path/to/readwrite"};
state.permissions.network_http = {"https://api.example.com"};
state.permissions.fs_read = {"/path/to/read"};
state.permissions.fs_readwrite = {"/path/to/readwrite"};
state.permissions.fs_create = {"/path/to/create-folder"};
state.permissions.fs_delete = {"*"};
state.permissions.network_http = {"https://api.example.com"};
state.permissions.network_socket = {"192.168.45.6:443"};
state.permissions.process = {"/usr/bin/curl"};
state.permissions.threading = true;
@@ -255,6 +257,8 @@ TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's ins
REQUIRE(read_install_state(plugin_dir, persisted));
CHECK(persisted.permissions.fs_read == state.permissions.fs_read);
CHECK(persisted.permissions.fs_readwrite == state.permissions.fs_readwrite);
CHECK(persisted.permissions.fs_create == state.permissions.fs_create);
CHECK(persisted.permissions.fs_delete == state.permissions.fs_delete);
CHECK(persisted.permissions.network_http == state.permissions.network_http);
CHECK(persisted.permissions.network_socket == state.permissions.network_socket);
CHECK(persisted.permissions.process == state.permissions.process);
@@ -270,6 +274,86 @@ TEST_CASE("install-state sidecar is the source of truth for a cloud plugin's ins
CHECK(scanned.installed_version == "1.2.0");
}
TEST_CASE("install-state reads create and delete grants and defaults missing keys to none", "[PluginInstall][PluginFsUtils]")
{
ScopedDataDir data_dir_guard("create-delete-permission-read");
const fs::path plugin_dir = data_dir_guard.dir / "plugin";
const auto read_permissions = [&plugin_dir]() {
PluginInstallState state;
REQUIRE(read_install_state(plugin_dir, state));
return state.permissions;
};
SECTION("missing keys grant nothing")
{
write_raw_install_state(plugin_dir, {{"permissions", nlohmann::json::object()}});
// Fail closed: an older sidecar has no create/delete buckets, so neither operation is
// allowed without a prompt.
const PluginPermissions permissions = read_permissions();
CHECK(permissions.fs_create.empty());
CHECK(permissions.fs_delete.empty());
// The same holds when the sidecar has no permissions object at all.
write_raw_install_state(plugin_dir, nlohmann::json::object());
const PluginPermissions no_permissions = read_permissions();
CHECK(no_permissions.fs_create.empty());
CHECK(no_permissions.fs_delete.empty());
}
SECTION("saved folders and the all-folders marker are read back")
{
write_raw_install_state(plugin_dir,
{{"permissions",
{{"fs_create", nlohmann::json::array({"/allowed/create", "/allowed/tree/*"})},
{"fs_delete", nlohmann::json::array({"*"})}}}});
const PluginPermissions permissions = read_permissions();
CHECK(permissions.fs_create == std::vector<std::string>{"/allowed/create", "/allowed/tree/*"});
CHECK(permissions.fs_delete == std::vector<std::string>{"*"});
}
SECTION("a non-array or non-string value grants nothing")
{
write_raw_install_state(plugin_dir,
{{"permissions",
{{"fs_create", "/allowed/create"},
{"fs_delete", nlohmann::json::array({1, true})}}}});
const PluginPermissions permissions = read_permissions();
CHECK(permissions.fs_create.empty());
CHECK(permissions.fs_delete.empty());
}
}
TEST_CASE("install-state writes create and delete grants as arrays", "[PluginInstall][PluginFsUtils]")
{
ScopedDataDir data_dir_guard("create-delete-permission-write");
const fs::path plugin_dir = data_dir_guard.dir / "plugin";
fs::create_directories(plugin_dir);
PluginInstallState state;
state.permissions.fs_create = {"/allowed/create", "/other/tree/*"};
state.permissions.fs_delete = {"*"};
REQUIRE(write_install_state(plugin_dir, state));
std::ifstream in((plugin_dir / ".install_state.json").string(), std::ios::binary);
const nlohmann::json written = nlohmann::json::parse(in);
REQUIRE(written["permissions"].contains("fs_create"));
REQUIRE(written["permissions"].contains("fs_delete"));
CHECK(written["permissions"]["fs_create"].is_array());
CHECK(written["permissions"]["fs_delete"].is_array());
CHECK(written["permissions"]["fs_create"] == nlohmann::json::array({"/allowed/create", "/other/tree/*"}));
CHECK(written["permissions"]["fs_delete"] == nlohmann::json::array({"*"}));
in.close();
PluginInstallState read_back;
REQUIRE(read_install_state(plugin_dir, read_back));
CHECK(read_back.permissions.fs_create == state.permissions.fs_create);
CHECK(read_back.permissions.fs_delete == state.permissions.fs_delete);
}
TEST_CASE("install-state metadata read-modify-write leaves an unreadable sidecar untouched", "[PluginInstall][PluginFsUtils]")
{
ScopedDataDir data_dir_guard("unreadable-install-state");