From 3838002bc8ba58f4f460749af40fa6fd8a89ffc7 Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Wed, 18 Nov 2026 17:50:29 +0800 Subject: [PATCH] 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 --- docs/HLSD/plugin-permissions.md | 136 +- docs/HLSD/python-plugin-async-bridge.md | 9 +- resources/web/dialog/PluginsDialog/index.js | 109 +- resources/web/dialog/PluginsDialog/styles.css | 18 + src/slic3r/GUI/PluginsDialog.cpp | 101 +- src/slic3r/plugin/PluginAuditManager.cpp | 1910 +++++++++++-- src/slic3r/plugin/PluginAuditManager.hpp | 231 +- src/slic3r/plugin/PluginFsUtils.cpp | 38 + src/slic3r/plugin/PluginFsUtils.hpp | 21 + src/slic3r/plugin/PluginManager.cpp | 8 + src/slic3r/plugin/PluginManager.hpp | 2 + src/slic3r/plugin/PythonPluginBridge.cpp | 69 +- tests/slic3rutils/test_plugin_audit.cpp | 2395 ++++++++++++++++- tests/slic3rutils/test_plugin_install.cpp | 90 +- 14 files changed, 4784 insertions(+), 353 deletions(-) diff --git a/docs/HLSD/plugin-permissions.md b/docs/HLSD/plugin-permissions.md index b1a42a0d16..8c14679fbf 100644 --- a/docs/HLSD/plugin-permissions.md +++ b/docs/HLSD/plugin-permissions.md @@ -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 `/*` 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 `:`, 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`, diff --git a/docs/HLSD/python-plugin-async-bridge.md b/docs/HLSD/python-plugin-async-bridge.md index 791e3ba63f..0de7b9678f 100644 --- a/docs/HLSD/python-plugin-async-bridge.md +++ b/docs/HLSD/python-plugin-async-bridge.md @@ -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 diff --git a/resources/web/dialog/PluginsDialog/index.js b/resources/web/dialog/PluginsDialog/index.js index 7e5abfc30c..27adc0c8eb 100644 --- a/resources/web/dialog/PluginsDialog/index.js +++ b/resources/web/dialog/PluginsDialog/index.js @@ -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"; diff --git a/resources/web/dialog/PluginsDialog/styles.css b/resources/web/dialog/PluginsDialog/styles.css index 8e64111461..7c2b209290 100644 --- a/resources/web/dialog/PluginsDialog/styles.css +++ b/resources/web/dialog/PluginsDialog/styles.css @@ -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; diff --git a/src/slic3r/GUI/PluginsDialog.cpp b/src/slic3r/GUI/PluginsDialog.cpp index 2e86019c15..9f023df0b4 100644 --- a/src/slic3r/GUI/PluginsDialog.cpp +++ b/src/slic3r/GUI/PluginsDialog.cpp @@ -32,6 +32,7 @@ #include #include +#include #include #include @@ -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}); } } diff --git a/src/slic3r/plugin/PluginAuditManager.cpp b/src/slic3r/plugin/PluginAuditManager.cpp index c853d07aa2..d04c0f2aaa 100644 --- a/src/slic3r/plugin/PluginAuditManager.cpp +++ b/src/slic3r/plugin/PluginAuditManager.cpp @@ -15,9 +15,18 @@ #include #include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + #include #include +#include #include +#include #include #include #include @@ -25,10 +34,15 @@ #include #include #include +#ifdef __APPLE__ +#include +#include +#endif #include #include #include #include +#include #include #include #include @@ -186,8 +200,10 @@ static bool is_network_category(AuditEventCategory category) return category == AuditEventCategory::Http || category == AuditEventCategory::Socket; } -// Create and delete have no persistent grant list. Off the main thread they are denied outright and -// reported with an informational dialog rather than a Yes/No prompt that could not grant anything. +// Create and delete grants name the folder that directly contains the target: an approval stores +// that parent folder rather than the target, and a saved exact grant allows later operations in +// the same folder. A tree grant "/*" also allows operations in every folder below it. +// Empty means no grant and a sole "*" means any location; see create_delete_grant_covers. static bool is_create_delete_category(AuditEventCategory category) { return category == AuditEventCategory::FsCreate || category == AuditEventCategory::FsDelete; @@ -479,10 +495,93 @@ private: wxSize m_content_dip; }; +#ifdef _WIN32 +// True when a status error only says the path does not exist. Boost clears `ec` for that case on +// POSIX, but its Windows status path (process_status_failure()) always stores the Win32 error, so +// ERROR_FILE_NOT_FOUND and ERROR_PATH_NOT_FOUND mean "just missing" there too. Anything else +// (access denied, sharing violation, invalid name) is a real failure. +bool missing_path_error(const boost::system::error_code& ec) +{ + return !ec || ec.value() == ERROR_FILE_NOT_FOUND || ec.value() == ERROR_PATH_NOT_FOUND; +} + +// Windows can spell one directory with either its long name or its 8.3 short name, and both name +// the same location. Python reports long names (os.path.realpath() and os.scandir()), while an +// allowed root is registered with whatever spelling the process was given, so the two spellings +// must compare equal. weakly_canonical() does not unify them: boost resolves symlinks and "."/".." +// but keeps every component as written, so link resolution stays exactly Boost's and this helper +// only re-spells the path it produced. +// +// GetLongPathNameW is a name-conversion API: it requires an existing path, can fail (for example +// when a parent cannot be read), and its documentation makes no promise about symbolic links. A +// caller that must keep a final link entry therefore must not hand a link to it (see +// delete_entry_names_subtree_root). Components below the longest existing prefix do not exist yet +// and have no short name, so they are appended as written. On failure `out` keeps the unexpanded +// canonical path and the caller decides whether to fail closed. +bool expand_short_name_prefix(const boost::filesystem::path& canonical, boost::filesystem::path& out) +{ + namespace fs = boost::filesystem; + + out = canonical; + if (canonical.empty() || !canonical.is_absolute()) + return false; + + // No cheap test says whether a spelling is short: Windows does not guarantee that an 8.3 alias + // contains '~' (or matches any other shape), so every comparison has to ask the file system. + // Split off the components that do not exist yet; only an existing prefix has a long form. + fs::path existing = canonical; + fs::path tail; + boost::system::error_code ec; + for (;;) { + if (fs::exists(existing, ec) && !ec) + break; + // A missing component is exactly the tail this function appends as written; any other + // status error (access denied, sharing violation, invalid name) fails closed. + if (!missing_path_error(ec) || !existing.has_relative_path()) + return false; + const fs::path component = existing.filename(); + if (component.empty()) + return false; + tail = tail.empty() ? component : component / tail; + existing = existing.parent_path(); + } + + std::wstring buffer(static_cast(MAX_PATH) + 1, L'\0'); + for (;;) { + const DWORD length = ::GetLongPathNameW(existing.c_str(), buffer.data(), + static_cast(buffer.size())); + if (length == 0) + return false; + if (length < buffer.size()) { + buffer.resize(length); + break; + } + buffer.resize(static_cast(length) + 1); + } + + const fs::path expanded(buffer); + if (!expanded.is_absolute()) + return false; + + out = tail.empty() ? expanded : expanded / tail; + return true; +} +#else +// 8.3 short names are a Windows-only alias; elsewhere the canonical path is already comparable. +bool expand_short_name_prefix(const boost::filesystem::path& canonical, boost::filesystem::path& out) +{ + out = canonical; + return true; +} +#endif + // Canonicalize a path for containment comparison. weakly_canonical resolves symlinks but does // NOT require the path to exist — it canonicalizes the prefix that exists and appends the -// non-existing tail lexically. -boost::filesystem::path canonical_for_comparison(const boost::filesystem::path& path) +// non-existing tail lexically. The result then has its Windows 8.3 short names expanded, so both +// sides of a comparison are spelled the same way. +// Returns false when the short-name expansion failed; `out` then holds the unexpanded canonical +// path, and a caller that must fail closed instead of comparing two spellings has to check it. +bool canonicalize_for_comparison(const boost::filesystem::path& path, boost::filesystem::path& out) { namespace fs = boost::filesystem; @@ -494,7 +593,16 @@ boost::filesystem::path canonical_for_comparison(const boost::filesystem::path& if (ec) canon = path; } - return canon; + return expand_short_name_prefix(canon, out); +} + +// Best-effort form for checks that need one canonical path only, e.g. the denied-keyword scan: +// when the expansion fails the plain canonical spelling is used, as it was before it existed. +boost::filesystem::path canonical_for_comparison(const boost::filesystem::path& path) +{ + boost::filesystem::path out; + canonicalize_for_comparison(path, out); + return out; } // True when the final component of `path` is a symlink whose target does not exist. @@ -549,7 +657,8 @@ bool same_canonical_path(const boost::filesystem::path& lhs, const boost::filesy // Component-wise containment: the whole of canonical_root must be a prefix of // canonical_candidate, and the remaining components must not traverse upward. Both arguments are -// expected to come from canonical_for_comparison(). On a match, suffix receives the candidate's +// expected to come from canonicalize_for_comparison()/canonical_folder(), i.e. expanded to long +// names where the platform has 8.3 aliases. On a match, suffix receives the candidate's // components below the root (empty when the two paths are equal). bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, const boost::filesystem::path& canonical_root, @@ -587,7 +696,13 @@ bool suffix_inside_root(const boost::filesystem::path& canonical_candidate, bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boost::filesystem::path& allowed_root) { - const boost::filesystem::path canonical_candidate = canonical_for_comparison(candidate); + // Both sides are canonicalized identically, including the expansion of Windows 8.3 short + // names, so a root registered under one spelling still contains a target reported under the + // other. A side that cannot be normalized fails closed: comparing differently spelled paths + // could otherwise report containment that does not hold. + boost::filesystem::path canonical_candidate; + if (!canonicalize_for_comparison(candidate, canonical_candidate)) + return false; // Fail closed on a dangling final symlink instead of comparing the path it is spelled as: the // grant describes the link, not the destination a write through it would create. The test is @@ -596,8 +711,12 @@ bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boos if (ends_in_dangling_symlink(canonical_candidate)) return false; + boost::filesystem::path canonical_root; + if (!canonicalize_for_comparison(allowed_root, canonical_root)) + return false; + boost::filesystem::path suffix; - return suffix_inside_root(canonical_candidate, canonical_for_comparison(allowed_root), suffix); + return suffix_inside_root(canonical_candidate, canonical_root, suffix); } // --------------------------------------------------------------------------- @@ -607,7 +726,7 @@ bool is_inside_allowed_root(const boost::filesystem::path& candidate, const boos thread_local std::string PluginAuditManager::m_current_plugin_key = ""; thread_local std::string PluginAuditManager::m_current_capability_name = ""; thread_local std::vector PluginAuditManager::m_scoped_allowed_roots; -thread_local std::vector PluginAuditManager::m_root_frames; +thread_local std::vector PluginAuditManager::m_root_frames; thread_local int PluginAuditManager::m_releasing_frames = 0; thread_local bool PluginAuditManager::m_audit_denial_pending = false; thread_local bool PluginAuditManager::m_has_last_violation = false; @@ -641,7 +760,7 @@ ScopedPluginAuditContext::~ScopedPluginAuditContext() mgr.set_current_plugin(m_plugin_key); mgr.set_current_capability(m_capability); while (!PluginAuditManager::m_root_frames.empty()) { - std::vector frames = std::move(PluginAuditManager::m_root_frames); + std::vector frames = std::move(PluginAuditManager::m_root_frames); PluginAuditManager::m_root_frames.clear(); mgr.release_frames(frames); } @@ -1028,6 +1147,216 @@ bool PluginAuditManager::last_violation(AuditViolation& violation) const namespace PluginAuditDetail { +// Defined below: the process-wide serialized prompt queue. Declared here because invalidating a +// plugin's recursive-delete state also drops its queued consents. +AuditPromptQueue& runtime_audit_prompts(); + +// A one-time consent for a recursive delete whose prompt could not run inline. It is deliberately +// in-memory only: no sidecar grant is written, so the approval cannot widen future delete access. +// The plugin key and canonical subtree root bind it to exactly one retry, and the short lifetime +// plus bounded count keep abandoned prompts from accumulating. +struct RecursiveDeleteApproval +{ + std::string plugin_key; + std::string canonical_root; + std::chrono::steady_clock::time_point expires_at; +}; + +using RecursiveDeleteClock = std::chrono::steady_clock; + +constexpr int kRecursiveDeleteApprovalLifetimeSeconds = 60; +std::mutex s_recursive_delete_approval_mutex; +std::vector s_recursive_delete_approvals; +std::chrono::milliseconds s_recursive_delete_approval_lifetime{kRecursiveDeleteApprovalLifetimeSeconds * 1000}; +constexpr std::size_t kMaxRecursiveDeleteApprovals = 16; + +// Prompts that have been posted but not yet answered. The key is the same plugin/target pair an +// approval would use, so a plugin retry loop cannot queue a second modal while the first is still +// open. The entry is cleared when the dialog is answered, or when posting is abandoned. +struct RecursiveDeletePromptKey +{ + std::string plugin_key; + std::string canonical_root; + std::uint64_t generation; +}; + +std::vector s_pending_recursive_delete_prompts; +// Bounds the recursive-delete consents that may be waiting for an answer at once, for both the +// test seam's pending set and the serialized production queue. A plugin retry loop can name many +// distinct targets; at capacity the new consent is rejected rather than queued. +constexpr std::size_t kMaxRecursiveDeletePrompts = 16; + +// Incremented whenever a plugin's permission state is edited, revoked, or reinstalled. Posted +// dialog callbacks capture this value and must not store an approval after it changes. +std::unordered_map s_recursive_delete_generations; + +PluginAuditManager::RecursiveDeletePrompt s_recursive_delete_prompt_for_testing; +bool s_recursive_delete_prompt_background_for_testing = false; +bool s_recursive_delete_prompt_deferred_for_testing = false; + +std::uint64_t recursive_delete_generation(const std::string& plugin_key) +{ + std::lock_guard lock(s_recursive_delete_approval_mutex); + const auto it = s_recursive_delete_generations.find(plugin_key); + return it == s_recursive_delete_generations.end() ? 0 : it->second; +} + +void invalidate_recursive_delete_state(const std::string& plugin_key) +{ + if (plugin_key.empty()) + return; + + { + std::lock_guard lock(s_recursive_delete_approval_mutex); + ++s_recursive_delete_generations[plugin_key]; + + // Any approval or dedup key was granted for the previous permission state. Erase both so + // a later retry starts from the current state. A dialog already posted cannot be + // withdrawn; its callback becomes a no-op through the generation token it captured. + s_recursive_delete_approvals.erase( + std::remove_if(s_recursive_delete_approvals.begin(), s_recursive_delete_approvals.end(), + [&plugin_key](const RecursiveDeleteApproval& approval) { + return approval.plugin_key == plugin_key; + }), + s_recursive_delete_approvals.end()); + s_pending_recursive_delete_prompts.erase( + std::remove_if(s_pending_recursive_delete_prompts.begin(), s_pending_recursive_delete_prompts.end(), + [&plugin_key](const RecursiveDeletePromptKey& prompt) { + return prompt.plugin_key == plugin_key; + }), + s_pending_recursive_delete_prompts.end()); + } + + // Queued production consents for the old permission state are dropped too. An active dialog + // cannot be withdrawn; the generation it captured makes its late answer a no-op. + runtime_audit_prompts().discard_recursive_delete_consents(plugin_key); +} + +// Caller holds s_recursive_delete_approval_mutex. +void prune_recursive_delete_approvals(const RecursiveDeleteClock::time_point& now) +{ + s_recursive_delete_approvals.erase( + std::remove_if(s_recursive_delete_approvals.begin(), s_recursive_delete_approvals.end(), + [now](const RecursiveDeleteApproval& approval) { return approval.expires_at <= now; }), + s_recursive_delete_approvals.end()); +} + +// True when no prompt for this plugin and target is already posted. The caller must pair a true +// result with finish_recursive_delete_prompt() after the dialog is answered. +bool begin_recursive_delete_prompt(const std::string& plugin_key, const std::string& canonical_root, + std::uint64_t generation) +{ + std::lock_guard lock(s_recursive_delete_approval_mutex); + const auto same = [&plugin_key, &canonical_root](const RecursiveDeletePromptKey& prompt) { + return prompt.plugin_key == plugin_key && prompt.canonical_root == canonical_root; + }; + if (std::find_if(s_pending_recursive_delete_prompts.begin(), s_pending_recursive_delete_prompts.end(), same) != + s_pending_recursive_delete_prompts.end()) + return false; + + // At capacity, reject the new prompt instead of evicting an existing key: the evicted + // dialog is already queued and cannot be withdrawn, so eviction would let repeated distinct + // targets queue unlimited dialogs while losing the ability to deduplicate them. + if (s_pending_recursive_delete_prompts.size() >= kMaxRecursiveDeletePrompts) + return false; + + s_pending_recursive_delete_prompts.push_back({plugin_key, canonical_root, generation}); + return true; +} + +void finish_recursive_delete_prompt(const std::string& plugin_key, const std::string& canonical_root, + std::uint64_t generation) +{ + std::lock_guard lock(s_recursive_delete_approval_mutex); + s_pending_recursive_delete_prompts.erase( + std::remove_if(s_pending_recursive_delete_prompts.begin(), s_pending_recursive_delete_prompts.end(), + [&plugin_key, &canonical_root, generation](const RecursiveDeletePromptKey& prompt) { + return prompt.plugin_key == plugin_key && prompt.canonical_root == canonical_root && + prompt.generation == generation; + }), + s_pending_recursive_delete_prompts.end()); +} + +std::size_t pending_recursive_delete_prompts() +{ + std::lock_guard lock(s_recursive_delete_approval_mutex); + return s_pending_recursive_delete_prompts.size(); +} + +// Releases a pending-prompt dedup key on every exit path, including an exception thrown by the +// dialog or the test seam. A deferred test answer deliberately keeps the key and calls +// dismiss(); production callbacks just let the guard run. +class RecursiveDeletePromptGuard +{ +public: + RecursiveDeletePromptGuard(std::string plugin_key, std::string canonical_root, std::uint64_t generation) + : m_plugin_key(std::move(plugin_key)) + , m_canonical_root(std::move(canonical_root)) + , m_generation(generation) + {} + ~RecursiveDeletePromptGuard() + { + if (m_active) + finish_recursive_delete_prompt(m_plugin_key, m_canonical_root, m_generation); + } + + void dismiss() { m_active = false; } + + RecursiveDeletePromptGuard(const RecursiveDeletePromptGuard&) = delete; + RecursiveDeletePromptGuard& operator=(const RecursiveDeletePromptGuard&) = delete; + +private: + std::string m_plugin_key; + std::string m_canonical_root; + std::uint64_t m_generation; + bool m_active = true; +}; + +void store_recursive_delete_approval(const std::string& plugin_key, const std::string& canonical_root) +{ + if (plugin_key.empty() || canonical_root.empty()) + return; + + std::lock_guard lock(s_recursive_delete_approval_mutex); + const RecursiveDeleteClock::time_point now = RecursiveDeleteClock::now(); + prune_recursive_delete_approvals(now); + + // Bound the store even when a user answers many prompts: the oldest pending consent is no + // more useful than an expired one. + if (s_recursive_delete_approvals.size() >= kMaxRecursiveDeleteApprovals) + s_recursive_delete_approvals.erase(s_recursive_delete_approvals.begin()); + + s_recursive_delete_approvals.push_back({plugin_key, canonical_root, now + s_recursive_delete_approval_lifetime}); +} + +bool take_recursive_delete_approval(const std::string& plugin_key, const std::string& canonical_root) +{ + if (plugin_key.empty() || canonical_root.empty()) + return false; + + std::lock_guard lock(s_recursive_delete_approval_mutex); + prune_recursive_delete_approvals(RecursiveDeleteClock::now()); + + const auto found = std::find_if(s_recursive_delete_approvals.begin(), s_recursive_delete_approvals.end(), + [&plugin_key, &canonical_root](const RecursiveDeleteApproval& approval) { + return approval.plugin_key == plugin_key && + approval.canonical_root == canonical_root; + }); + if (found == s_recursive_delete_approvals.end()) + return false; + + // Single use: the retry this consent authorised is the only one it can start. + s_recursive_delete_approvals.erase(found); + return true; +} + +std::size_t pending_recursive_delete_approvals() +{ + std::lock_guard lock(s_recursive_delete_approval_mutex); + prune_recursive_delete_approvals(RecursiveDeleteClock::now()); + return s_recursive_delete_approvals.size(); +} + PyObject* tuple_item(PyObject* args, Py_ssize_t index) { if (!args || !PyTuple_Check(args) || index < 0 || index >= PyTuple_GET_SIZE(args)) @@ -1165,13 +1494,15 @@ std::vector stack_frames() // Moves the held root frames whose operation has returned from `held` to `dropped`. A suspended // generator's frame (os.walk between two items) is off the stack, but its operation resumes, so // it stays held until the scope ends. -void take_returned_frames(std::vector& held, std::vector& dropped) +template +void take_returned_frames(std::vector& held, std::vector& dropped) { if (held.empty()) return; const std::vector stack = stack_frames(); - const auto running = [&stack](PyObject* frame) { + const auto running = [&stack](const Record& record) { + PyObject* frame = record.frame; if (std::find(stack.begin(), stack.end(), frame) != stack.end()) return true; // NULL once the generator has finished or been deleted: its frame then owns its own data. @@ -1191,6 +1522,119 @@ static const std::unordered_set two_path_fs_events{ "shutil.unpack_archive", "_winapi.CreateJunction", }; +// Audit events whose path arguments are resolved against a directory file descriptor. CPython's +// tuple layouts (verified against 3.12): +// os.mkdir(path, mode, dir_fd) +// os.remove(path, dir_fd) / os.rmdir(path, dir_fd) +// os.symlink(src, dst, dir_fd) -- dir_fd applies to the destination only +// os.link(src, dst, src_dir_fd, dst_dir_fd) +// shutil.rmtree(path, dir_fd) -- newer Python releases expose dir_fd here too +// +// A relative path must be resolved against the descriptor's folder, not the process working +// directory. Returns the dir_fd argument index for the given path argument, or -1 when the path +// argument is not resolved through a descriptor. +static int create_delete_dir_fd_index(const std::string& event_name, Py_ssize_t path_index) +{ + if (event_name == "os.mkdir") + return path_index == 0 ? 2 : -1; + if (event_name == "os.remove" || event_name == "os.rmdir") + return path_index == 0 ? 1 : -1; + if (event_name == "os.symlink") + return path_index == 1 ? 2 : -1; + if (event_name == "os.link") + return path_index == 0 ? 2 : (path_index == 1 ? 3 : -1); + if (event_name == "shutil.rmtree") + return path_index == 0 ? 1 : -1; + return -1; +} + +// Resolves an open directory descriptor to its folder. Linux uses the /proc/self/fd link and +// macOS uses F_GETPATH. Returns false when the platform or the running environment cannot name +// the folder; the caller then fails closed instead of checking a path inside the working +// directory that the operation does not use. +static bool resolve_dir_fd_folder(int fd, boost::filesystem::path& out) +{ + namespace fs = boost::filesystem; + +#if defined(__linux__) + boost::system::error_code ec; + const fs::path target = fs::read_symlink(fs::path("/proc/self/fd") / std::to_string(fd), ec); + if (ec || target.empty() || !target.is_absolute()) + return false; + out = target; + return true; +#elif defined(__APPLE__) + char buffer[PATH_MAX] = {}; + if (fcntl(fd, F_GETPATH, buffer) == -1) + return false; + const fs::path target(buffer); + if (target.empty() || !target.is_absolute()) + return false; + out = target; + return true; +#else + (void) fd; + (void) out; + return false; +#endif +} + +// Replaces create/delete target paths that were resolved against a non-default dir_fd with paths +// under the folder that descriptor names. An absolute path ignores dir_fd (POSIX semantics), so it +// keeps its spelling. Returns false when a descriptor cannot be resolved or is not an integer; +// the caller then denies the operation. +static bool resolve_create_delete_targets(const std::string& event_name, PyObject* args, + std::vector& targets) +{ + const Py_ssize_t path_count = two_path_fs_events.count(event_name) ? 2 : 1; + std::vector resolved; + resolved.reserve(targets.size()); + + for (Py_ssize_t path_index = 0; path_index < path_count; ++path_index) { + const std::string path = python_path(tuple_item(args, path_index)); + if (path.empty()) + continue; + + const int fd_index = create_delete_dir_fd_index(event_name, path_index); + PyObject* const fd_item = fd_index >= 0 ? tuple_item(args, fd_index) : nullptr; + if (fd_item != nullptr && fd_item != Py_None) { + if (!PyLong_Check(fd_item)) + return false; + const long fd_value = PyLong_AsLong(fd_item); + if (PyErr_Occurred()) { + PyErr_Clear(); + return false; + } + // CPython passes AT_FDCWD (negative) for an omitted dir_fd. + if (fd_value >= 0 && !boost::filesystem::path(path).is_absolute()) { + boost::filesystem::path base; + if (!resolve_dir_fd_folder(static_cast(fd_value), base)) + return false; + resolved.push_back((base / boost::filesystem::path(path)).string()); + continue; + } + } + + resolved.push_back(path); + } + + targets = std::move(resolved); + return true; +} + +// A link creation reports its existing source and its new destination, but only the destination +// is created. The create grant covers the destination's parent folder; the source is not treated +// as created (a hardlink source is separately required to be writable). Both paths stay subject +// to the deny registry, and an unreadable destination fails closed rather than falling back to +// the source. +static std::vector create_permission_targets(const std::string& event_name, + const std::vector& targets) +{ + if (event_name == "os.link" || event_name == "os.symlink" || event_name == "_winapi.CreateJunction") + return targets.size() == 2 ? std::vector{targets.back()} : std::vector{}; + return targets; +} + static const std::unordered_map> audit_target_arg_indices{ {"http.client.connect", {1}}, {"urllib.Request", {0}}, @@ -1282,6 +1726,8 @@ std::vector* permission_list_for(AuditEventCategory category, bool switch (category) { case AuditEventCategory::FsRead: return &permissions.fs_read; case AuditEventCategory::FsReadWrite: return &permissions.fs_readwrite; + case AuditEventCategory::FsCreate: return &permissions.fs_create; + case AuditEventCategory::FsDelete: return &permissions.fs_delete; case AuditEventCategory::Http: return &permissions.network_http; case AuditEventCategory::Socket: return &permissions.network_socket; case AuditEventCategory::ProcessCreate: return &permissions.process; @@ -1300,11 +1746,11 @@ std::string event_grant_key(AuditEventCategory category, const std::string& even return std::string(category_name(category)) + ":" + event_name; } -// The directory named by a directory-tree grant, i.e. "/*". "*" is the only wildcard, and -// only as the grant's final path component; any other "*" is an ordinary character, so a grant -// can never widen into a pattern the plugin did not spell out. Returns false for a grant that is -// not a tree grant. -bool tree_grant_root(const std::string& grant, boost::filesystem::path& root) +// The folder named by a tree grant, i.e. "/*", exactly as spelled. "*" is the only wildcard, +// and only as the grant's final path component; any other "*" is an ordinary character, so a +// grant can never widen into a pattern the plugin did not spell out. Returns false for a grant +// that is not a tree grant. +bool tree_grant_parent(const std::string& grant, boost::filesystem::path& parent) { if (grant.size() < 2 || grant.back() != '*' || grant.find('*') != grant.size() - 1) return false; @@ -1313,12 +1759,24 @@ bool tree_grant_root(const std::string& grant, boost::filesystem::path& root) if (path.filename() != "*") return false; - const boost::filesystem::path parent = path.parent_path(); - if (parent.empty()) + const boost::filesystem::path root = path.parent_path(); + if (root.empty()) + return false; + + parent = root; + return true; +} + +// The directory named by a directory-tree grant, i.e. "/*". Unlike tree_grant_parent this is +// applied to a stored grant, so ".." is rejected rather than resolved: a grant shown to the user +// as "/a/../*" must not silently become the root or another ancestor. Without a wildcard the +// string still matches verbatim. Returns false for a grant that is not a tree grant. +bool tree_grant_root(const std::string& grant, boost::filesystem::path& root) +{ + boost::filesystem::path parent; + if (!tree_grant_parent(grant, parent)) return false; - // Never resolve ".." here: a grant shown to the user as "/a/../*" must not silently become - // the root or another ancestor. Without a wildcard the string still matches verbatim. for (const boost::filesystem::path& component : parent) { if (component == "..") return false; @@ -1372,8 +1830,8 @@ std::string absolute_tree_grant(const std::string& grant) // could equate different files across unresolved symlinks and "..". A target whose final // component is a dangling symlink is not matched by equivalence, and neither is a grant ending in // one. Windows compares case-insensitively and accepts either separator; POSIX stays -// case-sensitive and treats "\" as an ordinary name character. Hardlinks, 8.3 short names and -// extended-length paths remain distinct paths. +// case-sensitive and treats "\" as an ordinary name character. 8.3 short names of the same file are +// unified on Windows; hardlinks and extended-length spellings remain distinct paths. bool exact_grant_covers(const std::string& grant, const std::string& target) { if (grant == target) @@ -1405,7 +1863,16 @@ bool exact_grant_covers(const std::string& grant, const std::string& target) if (ec || !canonical_target.is_absolute() || ends_in_dangling_symlink(canonical_target)) return false; - return same_canonical_path(canonical_grant, canonical_target); + // Expand 8.3 short names on both sides exactly like the create/delete comparisons, or a grant + // saved under one spelling would not cover the same file named the other way and the user + // would be asked again. Any expansion failure fails closed, as the canonicalization above does. + fs::path expanded_grant; + fs::path expanded_target; + if (!expand_short_name_prefix(canonical_grant, expanded_grant) || + !expand_short_name_prefix(canonical_target, expanded_target)) + return false; + + return same_canonical_path(expanded_grant, expanded_target); } // True when a filesystem grant covers a target: the exact string, an equivalent spelling of the @@ -1443,15 +1910,345 @@ bool fs_grant_covers(const std::string& grant, const std::string& target) return grant == target || is_inside_allowed_root(boost::filesystem::path(target), root); } +// --------------------------------------------------------------------------- +// Create and delete permission identity +// --------------------------------------------------------------------------- + +// A create or delete grant names a folder whose direct entries may be created or deleted, or a +// tree grant "/*" that additionally covers every folder below that root, at any depth. +// An empty list grants nothing, and a sole "*" grants any location. Any other entry must be an +// absolute folder path or an absolute tree grant; a relative or unreadable entry never matches. +// A "*" beside another entry is therefore an ordinary, non-matching entry: full access is only +// ever the explicit one-element form. +bool create_delete_grant_full(const std::vector& granted) +{ + return granted.size() == 1 && granted.front() == "*"; +} + +// Strictly resolves an absolute folder for a grant comparison. Unlike canonical_for_comparison it +// does not fall back to a lexical path: a path that cannot be canonicalized, or whose final +// component is a dangling symlink, never names a folder the grant covers. Relative paths never +// match -- which folder they name depends on the working directory at check time. +bool canonical_folder(const boost::filesystem::path& folder, boost::filesystem::path& out) +{ + namespace fs = boost::filesystem; + + if (folder.empty() || !folder.is_absolute()) + return false; + if (ends_in_dangling_symlink(folder)) + return false; + + boost::system::error_code ec; + const fs::path canonical = fs::weakly_canonical(folder, ec); + if (ec || !canonical.is_absolute() || ends_in_dangling_symlink(canonical)) + return false; + + // Both sides of every grant comparison come through here or through + // is_inside_allowed_root(), so expanding Windows 8.3 short names keeps a stored grant + // spelled one way comparable to a target spelled the other. Failing closed on an expansion + // error keeps an unresolvable spelling from authorizing anything. + if (!expand_short_name_prefix(canonical, out)) + return false; + return true; +} + +// The folder that directly contains the entry a create/delete event targets. The target itself may +// not exist yet (a create), so its parent is canonicalized with weakly_canonical: the existing +// prefix is resolved and the non-existing tail is appended lexically. A final ".." or "." names a +// directory rather than an entry, so that target is resolved first and its parent is used instead. +// The final component itself is deliberately not canonicalized: deleting or creating a symlink +// acts on the link inside its parent folder, not on the link's destination. A trailing separator +// on a symlink is rejected instead of resolving through the link: the path is ambiguous between +// the link and its destination, and must not grant the destination's parent folder. Returns false +// when the folder cannot be resolved, and the operation then fails closed. +bool create_delete_target_folder(const std::string& target, boost::filesystem::path& folder) +{ + namespace fs = boost::filesystem; + + if (target.empty()) + return false; + + const fs::path path(target); + boost::system::error_code ec; + const fs::path absolute = path.is_absolute() ? path : fs::absolute(path, ec); + if (ec || !absolute.is_absolute()) + return false; + + const fs::path filename = path.filename(); + if (filename == "." || filename == "..") { + if (filename == ".") { + // A trailing separator (or a trailing ".") names the directory itself. Strip those + // components to find the entry the path ends at; if it is a symlink, resolve-through + // would name the link destination's folder, so fail closed. + fs::path entry = path; + while (entry.filename() == "." && !entry.parent_path().empty()) + entry = entry.parent_path(); + if (!entry.empty() && entry.filename() != ".") { + boost::system::error_code status_ec; + const fs::file_status status = fs::symlink_status(entry, status_ec); + if (!status_ec && fs::is_symlink(status)) + return false; + } + } + + // The target names a directory: resolve it, then use the directory that contains it. + const fs::path resolved = fs::weakly_canonical(absolute, ec); + if (ec || !resolved.is_absolute()) + return false; + const fs::path parent = resolved.parent_path(); + if (parent.empty()) + return false; + folder = parent; + return true; + } + + const fs::path parent = fs::weakly_canonical(absolute.parent_path(), ec); + if (ec || !parent.is_absolute()) + return false; + + folder = parent; + return true; +} + +// True when `target` names the approved subtree root itself, without resolving the final path +// component through a symlink. Deleting a link acts on the link entry, not on its destination, so +// an outside link pointing into the subtree must not be treated as the subtree root. The parent is +// canonicalized, which resolves intermediate symlinks and ".." with the operating system's +// semantics; the path is never lexically folded first, because "link/.." must follow the link +// before stepping up. The final component is compared by name -- with an 8.3 short name of a +// non-link entry expanded to its long spelling -- and a final ".." fails closed. +bool delete_entry_names_subtree_root(const std::string& target, const boost::filesystem::path& canonical_subtree) +{ + namespace fs = boost::filesystem; + + if (target.empty() || canonical_subtree.empty() || !canonical_subtree.is_absolute()) + return false; + + boost::system::error_code ec; + const fs::path path(target); + const fs::path absolute = path.is_absolute() ? path : fs::absolute(path, ec); + if (ec || !absolute.is_absolute()) + return false; + + // Strip only trailing separators / "." components so a trailing slash still names the entry. + // Do not lexically fold the remaining path: that would turn "/.." into the link's + // lexical parent instead of the parent of the link's destination. + fs::path entry = absolute; + while (!entry.empty() && (entry.filename() == "." || entry.filename().empty()) && + !entry.parent_path().empty()) + entry = entry.parent_path(); + + if (entry.empty() || entry.filename() == "." || entry.filename() == "..") + return false; + + const fs::path parent = fs::weakly_canonical(entry.parent_path(), ec); + if (ec || !parent.is_absolute() || !fs::is_directory(parent, ec) || ec) + return false; + + fs::path expanded_parent; + if (!expand_short_name_prefix(parent, expanded_parent)) + return false; + + // The final component stays compared by name, so the expanded parent alone is enough for a link + // entry: its destination is never followed. Spelling the component long is only safe when it is + // not a link, because GetLongPathNameW's documentation does not promise to leave a link + // unresolved; it is needed when a target names the root through the root's own 8.3 alias. A + // missing entry has no alias and stays as written. + const fs::path entry_path = expanded_parent / entry.filename(); + boost::system::error_code status_ec; + const fs::file_status status = fs::symlink_status(entry_path, status_ec); + if (status_ec || fs::is_symlink(status)) + return same_canonical_path(entry_path, canonical_subtree); + + fs::path expanded_entry; + if (!expand_short_name_prefix(entry_path, expanded_entry)) + return false; + + return same_canonical_path(expanded_entry, canonical_subtree); +} + +// True when deleting `target` acts on an entry inside `canonical_subtree`. The containing folder +// decides scope, so a symlink entry is judged by where it lives, not by what it points at. The one +// exception is the subtree root itself, recognised without following its final component. +bool delete_target_within_subtree(const std::string& target, const boost::filesystem::path& canonical_subtree) +{ + boost::filesystem::path folder; + if (create_delete_target_folder(target, folder) && is_inside_allowed_root(folder, canonical_subtree)) + return true; + + return delete_entry_names_subtree_root(target, canonical_subtree); +} + +// True when a runtime folder path contains '*'. A folder literally named with a wildcard cannot +// be stored as a literal create/delete grant: the sidecar would read the marker as a tree grant +// and cover a broader scope than the approved folder. Runtime callers fail closed before +// prompting for or persisting such a grant. +bool create_delete_folder_has_wildcard(const boost::filesystem::path& folder) +{ + return folder.string().find('*') != std::string::npos; +} + +// True when one saved create/delete grant covers the canonical folder `wanted`. A tree grant +// covers its canonical root and every folder below it, at any depth. An exact grant names exactly +// one folder, so it is consulted only when `allow_exact_grant` is true: a tree request is never +// covered by an exact grant, because that grant authorizes only the entries directly inside its +// folder, not the subtree. +bool create_delete_grant_covers_canonical_folder(const std::vector& granted, + const boost::filesystem::path& wanted, + bool allow_exact_grant) +{ + for (const std::string& grant : granted) { + boost::filesystem::path root; + if (tree_grant_root(grant, root)) { + boost::filesystem::path canonical_root; + if (!canonical_folder(root, canonical_root)) + continue; // relative or unresolvable roots never authorize + boost::filesystem::path suffix; + if (suffix_inside_root(wanted, canonical_root, suffix)) + return true; + continue; + } + if (!allow_exact_grant) + continue; + if (!canonical_folder(boost::filesystem::path(grant), root)) + continue; // relative or unresolvable entries never authorize + if (same_canonical_path(root, wanted)) + return true; + } + return false; +} + +// True when a saved create/delete grant already covers `folder`, the directory directly +// containing a create or delete target. An exact grant names that folder; a tree grant names +// its root and every folder below it. Folders are compared in canonical form so "." / "..", +// repeated separators and symlinked folders do not create a second grant for the same location, +// and a symlink inside a tree cannot escape it. A full grant covers every folder. +bool create_delete_grant_covers_folder(const std::vector& granted, const std::string& folder) +{ + if (create_delete_grant_full(granted)) + return true; + + boost::filesystem::path wanted; + if (!canonical_folder(boost::filesystem::path(folder), wanted)) + return false; + + return create_delete_grant_covers_canonical_folder(granted, wanted, /*allow_exact_grant=*/true); +} + +// True when the saved create/delete grants cover creating or deleting `target`: the folder +// directly containing it is named by an exact grant, or lies inside a tree grant's root. +bool create_delete_grant_covers(const std::vector& granted, const std::string& target) +{ + if (create_delete_grant_full(granted)) + return true; + + boost::filesystem::path folder; + return create_delete_target_folder(target, folder) && create_delete_grant_covers_folder(granted, folder.string()); +} + +// Resolves a folder path to the absolute, canonical location stored in the sidecar. A relative +// path is resolved against the working directory the request is made in, like a relative tree +// grant. Returns false for an empty or unresolvable path; the caller fails closed instead of +// storing a grant with a different scope. The final component must not be a dangling symlink +// (see canonical_folder). +bool resolve_create_delete_folder(const boost::filesystem::path& path, boost::filesystem::path& folder) +{ + if (path.empty()) + return false; + + boost::system::error_code ec; + const boost::filesystem::path absolute = path.is_absolute() ? path : boost::filesystem::absolute(path, ec); + if (ec || !absolute.is_absolute()) + return false; + + return canonical_folder(absolute, folder); +} + +// Resolves a folder requested by a plugin declaration to the absolute, canonical path stored in +// the sidecar. A relative folder is resolved against the working directory the request is made +// in, like a relative tree grant. Returns false for an empty, wildcard-containing, unresolvable or +// dangling entry; the declaration then fails closed instead of storing a grant with a different +// scope. The sole "*" full form is handled before this helper. +bool absolute_create_delete_folder(const std::string& requested, std::string& folder) +{ + if (requested.empty() || requested.find('*') != std::string::npos) + return false; + + boost::filesystem::path canonical; + if (!resolve_create_delete_folder(boost::filesystem::path(requested), canonical)) + return false; + + folder = canonical.string(); + return true; +} + +// Splits a requested create/delete tree grant into its root. Unlike tree_grant_root, this is +// applied to a declaration, not to a stored grant: "." and ".." are allowed because the root is +// canonicalized and shown to the user before it is stored. Returns false for every shape +// tree_grant_parent rejects. +bool requested_tree_grant_root(const std::string& requested, boost::filesystem::path& root) +{ + return tree_grant_parent(requested, root); +} + +// Resolves one entry from a create/delete declaration to the string stored for it. An exact +// folder becomes its canonical absolute path. A tree grant "/*" resolves its root the same +// way and is stored as "/*", so the sidecar records the absolute scope the prompt +// showed. Returns false for an empty entry, a wildcard other than a final tree marker, or an +// entry that cannot be resolved; the declaration then fails closed. The sole "*" full form is +// handled before this helper. +bool absolute_create_delete_grant(const std::string& requested, std::string& grant) +{ + boost::filesystem::path root; + if (!requested_tree_grant_root(requested, root)) + return absolute_create_delete_folder(requested, grant); + + boost::filesystem::path canonical; + if (!resolve_create_delete_folder(root, canonical)) + return false; + + grant = (canonical / "*").string(); + return true; +} + +// True when a saved create/delete grant already covers the whole scope of another grant entry. +// An exact requested folder is covered by an exact grant naming it, or by a tree grant whose root +// contains it. A requested tree grant is covered only by a tree grant whose root contains its +// root (or by full access): an exact grant authorizes direct entries in one folder, not the +// subtree the request asks for. +bool create_delete_grant_covers_grant(const std::vector& granted, const std::string& requested) +{ + if (create_delete_grant_full(granted)) + return true; + + boost::filesystem::path requested_root; + if (!tree_grant_root(requested, requested_root)) + return create_delete_grant_covers_folder(granted, requested); + + boost::filesystem::path wanted_root; + if (!canonical_folder(requested_root, wanted_root)) + return false; + + return create_delete_grant_covers_canonical_folder(granted, wanted_root, /*allow_exact_grant=*/false); +} + // True when `granted` already covers `target`. Only the filesystem buckets accept a tree grant, // and their exact entries may name the target file by an equivalent path spelling: an event // grant ("FsRead:open") and the non-filesystem buckets (URLs, socket addresses, commands) are -// matched verbatim, as before. +// matched verbatim, as before. The create/delete buckets are folder grants: they match the +// folder directly containing the target (an exact folder grant) or any folder inside a tree +// grant's root, not the target's spelling. bool has_permission(AuditEventCategory category, bool by_event, const std::vector& granted, const std::string& target) { const bool fs_bucket = !by_event && (category == AuditEventCategory::FsRead || category == AuditEventCategory::FsReadWrite); + const bool create_delete_bucket = + !by_event && is_create_delete_category(category); + + if (create_delete_bucket) + return create_delete_grant_covers(granted, target); + for (const auto& grant : granted) { // fs_grant_covers also owns the exact match, so that a relative tree entry cannot match // by spelling alone. @@ -1514,8 +2311,19 @@ bool persist_permission(const std::string& plugin_key, AuditEventCategory catego if (!permission_list) return false; - if (!has_permission(category, by_event, *permission_list, target)) + if (is_create_delete_category(category)) { + // A runtime folder whose name contains '*' cannot be stored as a literal create/delete + // grant: the sidecar would read it as a tree grant. Fail closed rather than persist a + // grant whose scope differs from the one the prompt showed. + if (target.find('*') != std::string::npos) + return false; + // The caller passes the target's parent folder for these buckets, so compare it as a + // folder rather than as a target path. + if (!create_delete_grant_covers_folder(*permission_list, target)) + permission_list->push_back(target); + } else if (!has_permission(category, by_event, *permission_list, target)) { permission_list->push_back(target); + } return write_install_state(root, state); } @@ -1560,14 +2368,106 @@ int report_denied(PluginAuditManager& mgr, } wxString audit_message(AuditEventCategory category, const wxString& plugin_name, const wxString& event_name, - const wxString& target_list, size_t target_count) + const wxString& target_list, size_t target_count, bool full_fs_scope = false, + bool tree_scope = false, bool root_tree_scope = false) { + // Create and delete grants name folders, and a declaration may ask for the whole filesystem + // with a sole "*". Describe that scope instead of printing the marker as a folder. + if (full_fs_scope) { + switch (category) { + case AuditEventCategory::FsCreate: + return wxString::Format( + _L("Plugin \"%s\" is requesting to create files anywhere on this computer.\n\n" + "Paths the host denies stay blocked."), + plugin_name); + case AuditEventCategory::FsDelete: + return wxString::Format( + _L("Plugin \"%s\" is requesting to delete files anywhere on this computer.\n\n" + "Paths the host denies stay blocked."), + plugin_name); + default: + break; + } + } + if (target_list.IsEmpty()) return wxString::Format( _L("Plugin \"%s\" is requesting permission for the Python audit event \"%s\".\n\n" "This operation does not expose a target the audit hook can display."), plugin_name, event_name); + if (tree_scope) { + if (root_tree_scope) { + switch (category) { + // A tree grant rooted at a filesystem, drive, or network share root covers everything + // on it. Say so explicitly instead of describing it like an ordinary nested folder. + // A mixed target list may also hold exact folders: only the entries ending in /* or \* + // cover subfolders, so the message cannot say that every listed folder does. + case AuditEventCategory::FsCreate: + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to create files in the following folder:\n%s\n\n" + "Approval covers creating entries directly inside the listed folder. " + "Only a target ending in /* or \\* also includes that folder's subfolders, at any depth. " + "An exact folder target covers the entries directly inside that folder only. " + "A target that is a filesystem, drive, or network share root, such as /*, " + "C:\\*, or \\\\server\\share\\*, covers that entire filesystem, drive, or network share.", + "Plugin \"%s\" is requesting to create files in the following folders:\n%s\n\n" + "Approval covers creating entries directly inside each listed folder. " + "Only targets ending in /* or \\* also include their folder's subfolders, at any depth. " + "Exact folder targets cover the entries directly inside that folder only. " + "A target that is a filesystem, drive, or network share root, such as /*, " + "C:\\*, or \\\\server\\share\\*, covers that entire filesystem, drive, or network share.", + target_count), + plugin_name, target_list); + case AuditEventCategory::FsDelete: + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to delete files in the following folder:\n%s\n\n" + "Approval covers deleting entries directly inside the listed folder. " + "Only a target ending in /* or \\* also includes that folder's subfolders, at any depth. " + "An exact folder target covers the entries directly inside that folder only. " + "A target that is a filesystem, drive, or network share root, such as /*, " + "C:\\*, or \\\\server\\share\\*, covers that entire filesystem, drive, or network share.", + "Plugin \"%s\" is requesting to delete files in the following folders:\n%s\n\n" + "Approval covers deleting entries directly inside each listed folder. " + "Only targets ending in /* or \\* also include their folder's subfolders, at any depth. " + "Exact folder targets cover the entries directly inside that folder only. " + "A target that is a filesystem, drive, or network share root, such as /*, " + "C:\\*, or \\\\server\\share\\*, covers that entire filesystem, drive, or network share.", + target_count), + plugin_name, target_list); + default: + break; + } + } + switch (category) { + // The target list shows a tree grant as "/*". Its approval covers subfolders, + // unlike a literal folder entry, so the prompt says so. The scope sentence is part of + // each msgid rather than appended, so a translator can reorder it. + case AuditEventCategory::FsCreate: + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to create files in the following folder:\n%s\n\n" + "Approval covers creating entries directly inside the listed folder. " + "Only a target ending in /* or \\* also includes that folder's subfolders, at any depth. " + "An exact folder target covers the entries directly inside that folder only.", + "Plugin \"%s\" is requesting to create files in the following folders:\n%s\n\n" + "Approval covers creating entries directly inside each listed folder. " + "Only targets ending in /* or \\* also include their folder's subfolders, at any depth. " + "Exact folder targets cover the entries directly inside that folder only.", + target_count), + plugin_name, target_list); + case AuditEventCategory::FsDelete: + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to delete files in the following folder:\n%s\n\n" + "Approval covers deleting entries directly inside the listed folder. " + "Only a target ending in /* or \\* also includes that folder's subfolders, at any depth. " + "An exact folder target covers the entries directly inside that folder only.", + "Plugin \"%s\" is requesting to delete files in the following folders:\n%s\n\n" + "Approval covers deleting entries directly inside each listed folder. " + "Only targets ending in /* or \\* also include their folder's subfolders, at any depth. " + "Exact folder targets cover the entries directly inside that folder only.", + target_count), + plugin_name, target_list); + default: + break; + } + } + switch (category) { case AuditEventCategory::FsRead: return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to read the following file:\n%s", @@ -1577,21 +2477,24 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name, return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to read/write the following file:\n%s", "Plugin \"%s\" is requesting to read/write the following files:\n%s", target_count), plugin_name, target_list); - // Creating and deleting have no persistent grant list, so the inline prompt says a Yes covers - // this operation only. Off the main thread they use the informational denial instead. The - // sentence is part of each msgid rather than appended: a translator must be able to reorder - // it inside the message. + // These buckets persist a folder grant: a Yes stores the folder shown in the prompt, and + // later operations whose target is directly inside it are allowed. The scope sentence is part + // of each msgid rather than appended, so a translator can reorder it. case AuditEventCategory::FsCreate: - return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to create the following file:\n%s\n\n" - "This approval applies only to this operation and is not remembered.", - "Plugin \"%s\" is requesting to create the following files:\n%s\n\n" - "This approval applies only to this operation and is not remembered.", target_count), + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to create files in the following folder:\n%s\n\n" + "Approval covers creating entries directly inside the listed folder. " + "It does not cover its subfolders.", + "Plugin \"%s\" is requesting to create files in the following folders:\n%s\n\n" + "Approval covers creating entries directly inside each listed folder. " + "It does not cover their subfolders.", target_count), plugin_name, target_list); case AuditEventCategory::FsDelete: - return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to delete the following file:\n%s\n\n" - "This approval applies only to this operation and is not remembered.", - "Plugin \"%s\" is requesting to delete the following files:\n%s\n\n" - "This approval applies only to this operation and is not remembered.", target_count), + return wxString::Format(_L_PLURAL("Plugin \"%s\" is requesting to delete files in the following folder:\n%s\n\n" + "Approval covers deleting entries directly inside the listed folder. " + "It does not cover its subfolders.", + "Plugin \"%s\" is requesting to delete files in the following folders:\n%s\n\n" + "Approval covers deleting entries directly inside each listed folder. " + "It does not cover their subfolders.", target_count), plugin_name, target_list); case AuditEventCategory::Http: return wxString::Format( @@ -1620,15 +2523,19 @@ wxString audit_message(AuditEventCategory category, const wxString& plugin_name, // Format with a placeholder first so translated messages can put the target list anywhere. PermissionMessage formatted_audit_message(AuditEventCategory category, const wxString& plugin_name, - const wxString& event_name, const wxString& targets, size_t count) + const wxString& event_name, const wxString& targets, size_t count, + bool full_fs_scope = false, bool tree_scope = false, + bool root_tree_scope = false) { if (targets.empty()) - return {audit_message(category, plugin_name, event_name, targets, count), {}}; + return {audit_message(category, plugin_name, event_name, targets, count, full_fs_scope, tree_scope, + root_tree_scope), {}}; wxString marker = "__ORCA_PERMISSION_TARGETS__"; while (plugin_name.Contains(marker) || event_name.Contains(marker) || targets.Contains(marker)) marker += "_"; - PermissionMessage message{audit_message(category, plugin_name, event_name, marker, count), {}}; + PermissionMessage message{ + audit_message(category, plugin_name, event_name, marker, count, full_fs_scope, tree_scope, root_tree_scope), {}}; const size_t pos = message.text.find(marker); if (pos != wxString::npos) { message.text.replace(pos, marker.length(), targets); @@ -1637,16 +2544,95 @@ PermissionMessage formatted_audit_message(AuditEventCategory category, const wxS return message; } +// A runtime create/delete prompt shows both the path that triggered it and the folder a Yes +// saves, so the user can see why the plugin was stopped and what the persistent grant covers. +// The declaration prompt keeps showing only the requested folder scope. +PermissionMessage formatted_create_delete_message(AuditEventCategory category, const wxString& plugin_name, + const std::vector& entries) +{ + // TRN %1% is the path the plugin tried to create or delete; %2% is the folder saved as a + // grant if the user approves. + const wxString entry_format = _L("Target: %1%\nSaved folder: %2%"); + wxString target_list; + for (const auto& entry : entries) { + if (!target_list.IsEmpty()) + target_list += "\n"; + target_list += GUI::format_wxstr(entry_format, entry.target, entry.grant_folder); + } + + wxString marker = "__ORCA_PERMISSION_TARGETS__"; + while (plugin_name.Contains(marker) || target_list.Contains(marker)) + marker += "_"; + + wxString text; + switch (category) { + case AuditEventCategory::FsCreate: + // TRN %1% is the plugin name; %2% is the list of targets, each with the folder saved as a + // grant. + text = GUI::format_wxstr( + _L_PLURAL("Plugin \"%1%\" is requesting to create the following entry:\n%2%\n\n" + "If you approve, the folder shown with this target is saved as a grant for future " + "operations. The grant covers creating entries directly inside that folder. It does not " + "cover the subfolders inside that folder.", + "Plugin \"%1%\" is requesting to create the following entries:\n%2%\n\n" + "If you approve, the folder shown with each target is saved as a grant for future " + "operations. Each grant covers creating entries directly inside its folder. It does not " + "cover the subfolders inside that folder.", + entries.size()), + plugin_name, marker); + break; + case AuditEventCategory::FsDelete: + // TRN %1% is the plugin name; %2% is the list of targets, each with the folder saved as a + // grant. + text = GUI::format_wxstr( + _L_PLURAL("Plugin \"%1%\" is requesting to delete the following entry:\n%2%\n\n" + "If you approve, the folder shown with this target is saved as a grant for future " + "operations. The grant covers deleting entries directly inside that folder. It does not " + "cover the subfolders inside that folder.", + "Plugin \"%1%\" is requesting to delete the following entries:\n%2%\n\n" + "If you approve, the folder shown with each target is saved as a grant for future " + "operations. Each grant covers deleting entries directly inside its folder. It does not " + "cover the subfolders inside that folder.", + entries.size()), + plugin_name, marker); + break; + default: + return {}; + } + + PermissionMessage message{text, {}}; + const size_t pos = message.text.find(marker); + if (pos != wxString::npos) { + message.text.replace(pos, marker.length(), target_list); + message.targets.emplace_back(pos, target_list.length()); + } + return message; +} + // Builds and shows the modal permission prompt. Must run on the GUI thread. bool prompt_for_targets(AuditEventCategory category, const std::string& plugin_name, const std::string& event_name, - const std::vector& unresolved) + const std::vector& unresolved, + const std::vector& entries) { + if (is_create_delete_category(category) && !entries.empty()) { + PermissionMessage message = + formatted_create_delete_message(category, wxString::FromUTF8(plugin_name.c_str()), entries); + return show_permission_dialog(message, _L("Plugin permission request")); + } + wxString target_list; for (const auto& target : unresolved) target_list += wxString::FromUTF8(target.c_str()) + "\n"; + const bool tree_scope = std::any_of(unresolved.begin(), unresolved.end(), [](const std::string& target) { + boost::filesystem::path root; + return tree_grant_root(target, root); + }); + PermissionMessage message = formatted_audit_message(category, wxString::FromUTF8(plugin_name.c_str()), - wxString::FromUTF8(event_name.c_str()), target_list, unresolved.size()); + wxString::FromUTF8(event_name.c_str()), target_list, + unresolved.size(), /*full_fs_scope=*/false, tree_scope, + /*root_tree_scope=*/false); return show_permission_dialog(message, _L("Plugin permission request")); } @@ -1657,19 +2643,37 @@ bool prompt_for_permission_message(const PermissionMessage& message) } // Builds the combined body for a load-time declaration. Each bucket keeps its own formatted target -// block, so a translated sentence can place its target list independently. +// block, so a translated sentence can place its target list independently. A create/delete +// bucket keeps the scope disclosure the declaration prompt has always shown: a sole "*" is +// unrestricted scope, and a tree grant ("/*") also covers every subfolder. PermissionMessage build_permission_message(const std::string& plugin_name, const std::vector& buckets) { PermissionMessage message; for (const AuditPromptBucket& bucket : buckets) { + const bool full_fs_scope = is_create_delete_category(bucket.category) && bucket.targets.size() == 1 && + bucket.targets.front() == "*"; + const bool tree_scope = + is_create_delete_category(bucket.category) && + std::any_of(bucket.targets.begin(), bucket.targets.end(), [](const std::string& target) { + boost::filesystem::path root; + return tree_grant_root(target, root); + }); + const bool root_tree_scope = + tree_scope && std::any_of(bucket.targets.begin(), bucket.targets.end(), [](const std::string& target) { + boost::filesystem::path root; + return tree_grant_root(target, root) && is_filesystem_root(root); + }); + wxString targets; - for (const std::string& target : bucket.targets) - targets += wxString::FromUTF8(target.c_str()) + "\n"; + if (!full_fs_scope) + for (const std::string& target : bucket.targets) + targets += wxString::FromUTF8(target.c_str()) + "\n"; if (!message.text.IsEmpty()) message.text += "\n\n"; PermissionMessage part = formatted_audit_message(bucket.category, wxString::FromUTF8(plugin_name.c_str()), - wxEmptyString, targets, bucket.targets.size()); + wxEmptyString, targets, bucket.targets.size(), + full_fs_scope, tree_scope, root_tree_scope); for (const auto& range : part.targets) message.targets.emplace_back(message.text.length() + range.first, range.second); message.text += part.text; @@ -1677,50 +2681,146 @@ PermissionMessage build_permission_message(const std::string& plugin_name, const return message; } -// Builds the informational message shown when an off-main-thread create/delete event is denied. -// There is no Yes/No choice: that path cannot grant create/delete permission, so the dialog must -// not imply that approving it would make a later attempt succeed. -wxString permission_denied_message(AuditEventCategory category, const wxString& plugin_name, - const wxString& target_list, size_t target_count) +// A recursive delete consent shows the canonical subtree root and states that the approval lasts +// only for this operation (or, when posted asynchronously, for one next matching attempt). That +// scope cannot be expressed by the persistent create/delete grant prompt, so it has its own +// complete message rather than a fragment appended to the folder prompt. A filesystem, drive, or +// network share root gets an additional sentence: deleting it covers everything on that root. +PermissionMessage formatted_recursive_delete_message(const wxString& plugin_name, const wxString& target, + bool root_scope, bool background) { - if (target_list.IsEmpty()) - return wxString::Format( - _L("Plugin \"%s\" tried to perform a file operation that requires permission.\n\n" - "The operation was denied. Use an allowed location or enable Full access for this plugin if you trust it."), - plugin_name); + wxString marker = "__ORCA_RECURSIVE_DELETE_TARGET__"; + while (plugin_name.Contains(marker) || target.Contains(marker)) + marker += "_"; - switch (category) { - case AuditEventCategory::FsCreate: - return wxString::Format(_L_PLURAL("Plugin \"%s\" tried to create the following file:\n%s\n\n" - "The operation was denied. Use an allowed location or enable Full access for this plugin if you trust it.", - "Plugin \"%s\" tried to create the following files:\n%s\n\n" - "The operation was denied. Use an allowed location or enable Full access for this plugin if you trust it.", target_count), - plugin_name, target_list); - case AuditEventCategory::FsDelete: - return wxString::Format(_L_PLURAL("Plugin \"%s\" tried to delete the following file:\n%s\n\n" - "The operation was denied. Use an allowed location or enable Full access for this plugin if you trust it.", - "Plugin \"%s\" tried to delete the following files:\n%s\n\n" - "The operation was denied. Use an allowed location or enable Full access for this plugin if you trust it.", target_count), - plugin_name, target_list); - default: - return wxString::Format(_L("Plugin \"%s\" tried to perform a file operation that requires permission.\n\n" - "The operation was denied. Use an allowed location or enable Full access for this plugin if you trust it."), - plugin_name); + // TRN %1% is the plugin name; %2% is the canonical folder whose subtree may be deleted. + wxString format; + if (root_scope) { + format = background + ? _L("Plugin \"%1%\" is requesting to recursively delete the following folder:\n%2%\n\n" + "This target is a filesystem, drive, or network share root. Approval covers that entire " + "filesystem, drive, or network share, and applies to the next matching attempt within one " + "minute after you approve. The current attempt has already been denied. It is not saved as " + "a permission and cannot be reused for another operation. Protected paths stay blocked.") + : _L("Plugin \"%1%\" is requesting to recursively delete the following folder:\n%2%\n\n" + "This target is a filesystem, drive, or network share root. Approval covers that entire " + "filesystem, drive, or network share while this operation runs. It is not saved as a " + "permission and cannot be reused for another operation. Protected paths stay blocked."); + } else { + format = background + ? _L("Plugin \"%1%\" is requesting to recursively delete the following folder:\n%2%\n\n" + "Approval covers deleting the entries in this folder and everything inside it, and applies " + "to the next matching attempt within one minute after you approve. The current attempt has " + "already been denied. It is not saved as a permission and cannot be reused for another " + "operation. Protected paths stay blocked.") + : _L("Plugin \"%1%\" is requesting to recursively delete the following folder:\n%2%\n\n" + "Approval covers deleting the entries in this folder and everything inside it while this " + "operation runs. It is not saved as a permission and cannot be reused for another operation. " + "Protected paths stay blocked."); } + wxString text = GUI::format_wxstr(format, plugin_name, marker); + + PermissionMessage message{text, {}}; + const size_t pos = message.text.find(marker); + if (pos != wxString::npos) { + message.text.replace(pos, marker.length(), target); + message.targets.emplace_back(pos, target.length()); + } + return message; } -// Shows the informational denial for a create/delete event whose prompt had to be handled off the -// main thread. Must run on the GUI thread. -void show_permission_denied_dialog(AuditEventCategory category, const std::string& plugin_name, - const std::vector& targets) +// Builds and shows the modal recursive-delete prompt. Must run on the GUI thread. +bool prompt_for_recursive_delete(const std::string& plugin_name, const std::string& target, bool root_scope, + bool background) { - wxString target_list; - for (const auto& target : targets) - target_list += wxString::FromUTF8(target.c_str()) + "\n"; + return show_permission_dialog( + formatted_recursive_delete_message(wxString::FromUTF8(plugin_name.c_str()), wxString::FromUTF8(target.c_str()), + root_scope, background), + _L("Plugin permission request")); +} - const wxString message = permission_denied_message(category, wxString::FromUTF8(plugin_name.c_str()), - target_list, targets.size()); - GUI::MessageDialog(audit_prompt_parent(), message, _L("Plugin operation denied"), wxOK | wxICON_WARNING).ShowModal(); +// Defined below: the drain scheduler and the completion helper. A recursive-delete consent joins +// the same serialization as every other audit prompt. +bool schedule_runtime_prompt_drain_checked(); +bool finish_audit_prompt(const std::shared_ptr& completion, bool satisfied); + +// Asks for one-time consent to delete the canonical `target` subtree. On the wx main thread the +// answer is available before the operation returns, so a Yes lets this attempt proceed. Off that +// thread, or while another audit prompt is active, the modal is serialized through +// AuditPromptQueue and the current attempt is denied; a Yes records a short-lived single-use +// approval that only the same plugin and target can consume on a retry. A pending prompt for the +// same plugin/target is not queued again, so a plugin retry loop cannot flood the user with +// duplicate modals. +bool request_recursive_delete_consent(const std::string& plugin_key, const std::string& plugin_name, + const std::string& target, bool root_scope) +{ + BOOST_LOG_TRIVIAL(info) << "[AUDIT PROMPT] plugin=" << plugin_key << " event=shutil.rmtree scope=subtree target=[" + << target << "]"; + + const std::uint64_t generation = recursive_delete_generation(plugin_key); + + if (s_recursive_delete_prompt_for_testing) { + if (s_recursive_delete_prompt_background_for_testing) { + if (!begin_recursive_delete_prompt(plugin_key, target, generation)) + return false; + RecursiveDeletePromptGuard guard(plugin_key, target, generation); + const bool granted = s_recursive_delete_prompt_for_testing(plugin_name, target); + if (s_recursive_delete_prompt_deferred_for_testing) { + guard.dismiss(); // answered later through answer_recursive_delete_prompt_for_testing + return false; + } + if (granted && recursive_delete_generation(plugin_key) == generation) + PluginAuditManager::instance().add_recursive_delete_approval(plugin_key, target); + return false; + } + return s_recursive_delete_prompt_for_testing(plugin_name, target); + } + + if (wxTheApp == nullptr || GUI::wxGetApp().is_closing() || PluginManager::instance().is_shutting_down() || + PluginManager::instance().is_plugin_load_cancelled(plugin_key)) + return false; + + // A recursive-delete consent joins the same serialized prompt queue as every other audit + // prompt, so it cannot open a second dialog inside another permission dialog's modal loop. + // On the GUI thread an idle queue shows it inline and its answer can authorize this attempt; + // any queued request was raised off the GUI thread (or behind another prompt), so the current + // attempt is denied and a Yes becomes a one-time retry approval. + AuditPromptRequest request; + request.kind = AuditPromptKind::RecursiveDeleteConsent; + request.plugin_key = plugin_key; + request.plugin_name = plugin_name; + request.event_name = "shutil.rmtree"; + request.shown = {target}; + request.root_scope = root_scope; + request.recursive_delete_generation = generation; + + const AuditPromptQueue::Admission admission = runtime_audit_prompts().admit(request, wxIsMainThread() != 0); + if (admission == AuditPromptQueue::Admission::Duplicate || admission == AuditPromptQueue::Admission::Rejected) + return false; + if (admission == AuditPromptQueue::Admission::Queued) { + schedule_runtime_prompt_drain_checked(); + return false; + } + + // A permission edit may have landed between reading the generation and claiming the queue + // slot. Do not show consent for a stale state; the retry will ask again with the new one. + if (recursive_delete_generation(plugin_key) != generation) + return finish_audit_prompt(nullptr, false); + + // ShowNow: no other audit prompt is active, so present this consent synchronously. + bool granted = false; + try { + const bool alive = !PluginManager::instance().is_shutting_down() && + !PluginManager::instance().is_plugin_load_cancelled(plugin_key); + granted = alive && prompt_for_recursive_delete(plugin_name, target, root_scope, /*background=*/false); + } catch (const std::exception& ex) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to show recursive-delete prompt for plugin=" << plugin_key + << ": " << ex.what(); + } catch (...) { + BOOST_LOG_TRIVIAL(error) << "[AUDIT PROMPT] Failed to show recursive-delete prompt for plugin=" << plugin_key + << ": unknown exception"; + } + return finish_audit_prompt(nullptr, granted && recursive_delete_generation(plugin_key) == generation); } // Records a grant in the plugin's sidecar so it is not asked again. Each persist helper re-reads @@ -1781,9 +2881,26 @@ bool persist_declared_permissions(const std::string& plugin_key, const std::vect permission_list_for(bucket.category, /*by_event=*/false, state.permissions); if (!permission_list) continue; - for (const std::string& target : bucket.targets) + if (is_create_delete_category(bucket.category)) { + // A full grant added by another writer while the dialog was open already covers + // every folder; adding a folder beside it would stop it reading as the full form. + if (create_delete_grant_full(*permission_list)) + continue; + if (std::find(bucket.targets.begin(), bucket.targets.end(), "*") != bucket.targets.end()) { + // Unrestricted create/delete is the one-element form; drop folder grants it covers. + permission_list->assign(1, "*"); + continue; + } + } + for (const std::string& target : bucket.targets) { + // Another writer may have added an exact grant or a tree grant that already covers + // this entry while the dialog was open; do not store a redundant duplicate. + if (is_create_delete_category(bucket.category) && + create_delete_grant_covers_grant(*permission_list, target)) + continue; if (std::find(permission_list->begin(), permission_list->end(), target) == permission_list->end()) permission_list->push_back(target); + } } persisted = write_install_state(root, state); @@ -1812,12 +2929,16 @@ bool show_queued_prompt(const AuditPromptRequest& request) { switch (request.kind) { case AuditPromptKind::RuntimeEvent: - return prompt_for_targets(request.category, request.plugin_name, request.event_name, request.shown); + return prompt_for_targets(request.category, request.plugin_name, request.event_name, request.shown, + request.entries); case AuditPromptKind::DeclaredPermissions: return prompt_for_permission_message(build_permission_message(request.plugin_name, request.buckets)); - case AuditPromptKind::DeniedOperation: - show_permission_denied_dialog(request.category, request.plugin_name, request.shown); - return false; + case AuditPromptKind::RecursiveDeleteConsent: + // The request is shown only after the attempt that raised it was denied, so the consent + // must describe itself as applying to the next matching attempt. + return !request.shown.empty() && + prompt_for_recursive_delete(request.plugin_name, request.shown.front(), request.root_scope, + /*background=*/true); } return false; } @@ -1895,8 +3016,14 @@ void drain_runtime_prompts() bool satisfied = false; try { - const bool alive = plugin_available(*request); - const bool granted = alive && show_queued_prompt(*request); + const bool alive = plugin_available(*request); + // A permission edit racing the enqueue can leave a consent queued with the previous + // generation. Do not show it: its Yes could not store anything, and a fresh retry should + // be the prompt the user sees. + const bool stale_consent = + request->kind == AuditPromptKind::RecursiveDeleteConsent && + recursive_delete_generation(request->plugin_key) != request->recursive_delete_generation; + const bool granted = alive && !stale_consent && show_queued_prompt(*request); // Decide under the still-active queue entry so a shutdown/unload that arrives before the // sidecar write cancels this request. begin_commit() makes an accepted answer atomic @@ -1918,7 +3045,15 @@ void drain_runtime_prompts() BOOST_LOG_TRIVIAL(warning) << "[AUDIT PROMPT] Failed to persist declared permissions for " << request->plugin_key; break; - case AuditPromptKind::DeniedOperation: + case AuditPromptKind::RecursiveDeleteConsent: + // One-time consent is never persisted. A permission edit or reinstall while the + // dialog was open invalidated the generation, so a stale Yes stores nothing. + if (!request->shown.empty() && + recursive_delete_generation(request->plugin_key) == request->recursive_delete_generation) + PluginAuditManager::instance().add_recursive_delete_approval(request->plugin_key, + request->shown.front()); + else + satisfied = false; break; } } @@ -1964,8 +3099,11 @@ static const char* audit_category_name(AuditEventCategory category) } // Asks the user to grant an audited event, returning true when they approve an inline prompt. -// `keys` are what a Yes saves: the unresolved targets, or the event-grant key when the event has -// no target (by_event), which the prompt does not show as a target. +// `keys` are what a Yes saves and, for a targeted event, what the prompt shows. For a targetless +// event (by_event) the prompt shows no target and `keys` holds the event-grant key. Create/delete +// pass the canonical parent folder of each target in `keys`, and `entries` additionally pairs +// every triggering target with that folder, so the prompt shows both the reason for the prompt +// and exactly what it saves. // // An audited event can fire on a thread the UI thread may itself be blocked waiting on: the // SlicingPipeline hook runs on the slicing worker thread (see PluginHooks.cpp), and @@ -1980,11 +3118,11 @@ static const char* audit_category_name(AuditEventCategory category) // Runtime prompts are serialized by AuditPromptQueue: at most one is modal at a time, and the next // is scheduled only after the active dialog has closed. An event delivered inside that dialog's // nested event loop is queued and denied instead of opening a second dialog. Create and delete -// have no persistent grant to save, so a queued request for them becomes an informational denial: -// a Yes/No prompt would falsely imply that accepting it could authorize the operation or a later -// retry. +// keep the request's target entries and persist the approved folder, so a queued approval still +// grants what a retry needs; only the inline GUI-thread prompt lets the current operation proceed. bool request_permission(AuditEventCategory category, const std::string& plugin_key, const std::string& plugin_name, - const std::string& event_name, bool by_event, const std::vector& keys) + const std::string& event_name, bool by_event, const std::vector& keys, + const std::vector& entries = {}) { const std::vector shown = by_event ? std::vector{} : keys; std::string targets_text = by_event ? "" : ""; @@ -1999,7 +3137,7 @@ bool request_permission(AuditEventCategory category, const std::string& plugin_k << (by_event && !keys.empty() ? " grant=" + keys.front() : std::string{}); if (s_permission_prompt_for_testing) - return s_permission_prompt_for_testing(event_name, shown); + return s_permission_prompt_for_testing(event_name, shown, entries); if (wxTheApp == nullptr || GUI::wxGetApp().is_closing() || PluginManager::instance().is_shutting_down() || PluginManager::instance().is_plugin_load_cancelled(plugin_key)) @@ -2007,9 +3145,6 @@ bool request_permission(AuditEventCategory category, const std::string& plugin_k const bool on_gui_thread = wxIsMainThread() != 0; - // A queued create/delete prompt cannot grant anything: that path has no persistent permission. - // Show the inline Yes/No prompt only when it can be presented immediately on the GUI thread; - // any queued fallback is the OK-only informational denial, wherever the event originated. AuditPromptRequest request; request.kind = AuditPromptKind::RuntimeEvent; request.category = category; @@ -2019,23 +3154,17 @@ bool request_permission(AuditEventCategory category, const std::string& plugin_k request.by_event = by_event; request.keys = keys; request.shown = shown; + request.entries = entries; - AuditPromptQueue::Admission admission; - if (is_create_delete_category(category)) { - AuditPromptRequest denied = request; - denied.kind = AuditPromptKind::DeniedOperation; - admission = runtime_audit_prompts().admit_with_fallback(request, std::move(denied), on_gui_thread); - } else { - admission = runtime_audit_prompts().admit(request, on_gui_thread); - } - + const AuditPromptQueue::Admission admission = runtime_audit_prompts().admit(request, on_gui_thread); if (admission == AuditPromptQueue::Admission::Duplicate || admission == AuditPromptQueue::Admission::Rejected) return false; if (admission == AuditPromptQueue::Admission::Queued) { // A prompt is already active (this event arrived inside its modal loop) or an earlier one // is waiting. The current operation stays denied, as for an unanswered prompt; the - // queued prompt is shown once the active dialog has fully closed. + // queued prompt is shown once the active dialog has fully closed, and a Yes persists the + // same grant an inline answer would. schedule_runtime_prompt_drain_checked(); return false; } @@ -2058,15 +3187,19 @@ bool request_permission(AuditEventCategory category, const std::string& plugin_k } // Decides an event that no allowed root or running operation covers: a saved grant allows it, -// otherwise the user is asked. A Yes is saved when the category has a persistent grant list; -// create/delete has none and off the main thread only reports the denial. +// otherwise the user is asked. A Yes is saved for every category that has a persistent grant +// list, including create/delete, whose grant is the folder containing each approved target. +// Recursive deletes are the exception: their consent covers one subtree for one operation and +// is never written to the sidecar. `approved_delete_subtree` is set to that canonical subtree so +// the recorded root frame can cover its nested deletes. int decide_audited_event(PluginAuditManager& mgr, PluginInstallState& state, const std::string& plugin_key, const std::string& plugin_name, const std::string& event_name, AuditEventCategory category, - const std::vector& targets) + const std::vector& targets, + boost::filesystem::path& approved_delete_subtree) { // Full access turns permission auditing off for this plugin, so no grant or prompt applies. // This is reached only after audit_plugin_event's unconditional denied-path loop: the @@ -2079,38 +3212,115 @@ int decide_audited_event(PluginAuditManager& mgr, const bool by_event = targets.empty(); const std::vector keys = by_event ? std::vector{event_grant_key(category, event_name)} : targets; const bool threading_category = category == AuditEventCategory::Threading; + const bool create_delete_category = is_create_delete_category(category); std::vector* permission_list = permission_list_for(category, by_event, state.permissions); - std::vector unresolved = keys; - if (permission_list || is_network_category(category) || threading_category) { - unresolved.clear(); - if (threading_category) { - // Threading is a boolean grant rather than a target list. The event still reports the - // fixed sentinel target so it is not treated as a targetless event grant. - if (!state.permissions.threading) - unresolved = keys; - } else { - for (const auto& key : keys) { - // A network grant authorizes a specific host, except for a targetless event such as - // http.client.send, which names no host: any network grant covers that. - const bool granted_network = - is_network_category(category) && - (by_event ? has_any_network_permission(state.permissions) - : has_network_permission(state.permissions, key)); - if (!(permission_list && has_permission(category, by_event, *permission_list, key)) && !granted_network) - unresolved.push_back(key); + // A recursive delete walks and deletes a whole subtree, so it is judged as a subtree + // operation before the ordinary folder-grant check. A plain folder grant names direct + // entries only: even one naming the target folder or its parent is insufficient. Saved tree + // grants must cover both the entries inside the target and removal of the target folder + // itself. Otherwise the user is asked for one-time consent for this canonical subtree before + // the walk starts; that consent is never persisted. + if (category == AuditEventCategory::FsDelete && event_name == "shutil.rmtree" && !by_event) { + if (targets.size() != 1) + return report_denied(mgr, event_name, {false, "recursive delete target cannot be resolved"}); + + boost::filesystem::path root; + if (!resolve_create_delete_folder(boost::filesystem::path(targets.front()), root)) + return report_denied(mgr, event_name, {false, "recursive delete target cannot be resolved"}, targets.front()); + + const std::string canonical_root = root.string(); + const std::string subtree_grant = (root / "*").string(); + const bool subtree_covered = + permission_list && + (create_delete_grant_full(*permission_list) || + create_delete_grant_covers_grant(*permission_list, subtree_grant)); + if (subtree_covered) { + // A tree grant over the target covers the entries inside it, not necessarily deleting + // the target folder itself: a target-rooted "/*" grant leaves the final + // os.rmdir(target) to the containing folder of target. Only return here when that + // removal is separately covered too; otherwise the one-time consent below has to + // authorise the root removal explicitly before the walk starts. + if (has_permission(AuditEventCategory::FsDelete, /*by_event=*/false, *permission_list, targets.front())) { + // A matching consent is obsolete once saved grants cover the whole operation. + mgr.consume_recursive_delete_approval(plugin_key, canonical_root); + return 0; } } - if (unresolved.empty()) + + // A Yes posted by an earlier attempt is bound to this plugin and canonical target. Take + // it before asking again; consuming removes it, so it cannot authorise a second run. + if (mgr.consume_recursive_delete_approval(plugin_key, canonical_root)) { + approved_delete_subtree = root; return 0; + } + + // Letting a root frame go runs finalizers where no dialog may open: what they do must + // already be granted. + if (mgr.releasing_frames()) + return report_denied(mgr, event_name, {false, "recursive delete requires subtree permission"}, canonical_root); + + const bool root_scope = is_filesystem_root(root); + if (!request_recursive_delete_consent(plugin_key, plugin_name, canonical_root, root_scope)) + return report_denied(mgr, event_name, {false, "recursive delete requires subtree permission"}, canonical_root); + + approved_delete_subtree = root; + return 0; } + // Create/delete grants name folders: an approval saves the folder that directly contains + // each unresolved target, and the prompt shows both the triggering target and that canonical + // folder -- including the absolute form of relative targets and the resolved form of + // symlinked parents -- so the user approves exactly the scope that will be stored. Every + // target has to be covered, and a target whose folder cannot be resolved fails closed. + std::vector unresolved; + std::vector prompt_entries; + if (threading_category) { + // Threading is a boolean grant rather than a target list. The event still reports the + // fixed sentinel target so it is not treated as a targetless event grant. + if (!state.permissions.threading) + unresolved = keys; + } else if (create_delete_category && !by_event) { + for (const std::string& target : targets) { + if (permission_list && has_permission(category, /*by_event=*/false, *permission_list, target)) + continue; + boost::filesystem::path folder; + if (!create_delete_target_folder(target, folder)) + return report_denied(mgr, event_name, {false, "target folder cannot be resolved"}, target); + const std::string grant = folder.string(); + // A folder whose own name contains '*' cannot be shown or stored as a literal grant: + // the sidecar would read it as a tree grant over a broader scope. Fail closed. + if (create_delete_folder_has_wildcard(folder)) + return report_denied(mgr, event_name, {false, "target folder contains a wildcard"}, target); + // Show every triggering target, even when several targets resolve to the same folder; + // the folder list stays deduplicated because a Yes saves each folder once. + prompt_entries.push_back({target, grant}); + if (std::find(unresolved.begin(), unresolved.end(), grant) != unresolved.end()) + continue; // another target in this folder already requires the same approval + unresolved.push_back(grant); + } + } else { + for (const auto& key : keys) { + // A network grant authorizes a specific host, except for a targetless event such as + // http.client.send, which names no host: any network grant covers that. + const bool granted_network = + is_network_category(category) && + (by_event ? has_any_network_permission(state.permissions) + : has_network_permission(state.permissions, key)); + if (!(permission_list && has_permission(category, by_event, *permission_list, key)) && !granted_network) + unresolved.push_back(key); + } + } + + if (unresolved.empty()) + return 0; + // Letting a root frame go runs finalizers inside a scope destructor or another event's hook, // where no dialog may open: what they do must already be granted. if (mgr.releasing_frames()) return report_denied(mgr, event_name, {false, "audit permission required"}); - if (!request_permission(category, plugin_key, plugin_name, event_name, by_event, unresolved)) + if (!request_permission(category, plugin_key, plugin_name, event_name, by_event, unresolved, prompt_entries)) return report_denied(mgr, event_name, {false, "audit permission required"}); // persist_grant re-reads the sidecar under the shared lock and handles the threading @@ -2121,11 +3331,63 @@ int decide_audited_event(PluginAuditManager& mgr, return 0; } +// A hardlink makes an existing source writable through its new name, so the source needs write +// authorization independently of the destination's create permission, not merely read access: +// a writable allowed root, a saved fs_readwrite grant, full access, or a read/write approval. +// A read grant is deliberately insufficient because the link turns a read-only path into a +// writable one. A create grant is never stored for the source. Returns false when the source is +// not writable or the approval is missing; the caller then denies the event. Called only after +// root-frame coverage, so a link performed by an approved read/write operation is covered as +// part of that operation. +bool authorize_hardlink_source(PluginAuditManager& mgr, const std::string& event_name, const std::string& source) +{ + if (source.empty()) + return false; + + // check_path_access also consults the deny registry; a denied source already denied the event + // earlier, and a false result here still fails closed. is_write=true admits only writable + // allowed roots, not read-only ones such as the bundled resources folder. + if (mgr.check_path_access(boost::filesystem::path(source), /*is_write=*/true).allowed) + return true; + + PluginInstallState state; + const bool have_state = PluginManager::instance().get_install_state(mgr.current_plugin(), state); + if (have_state && state.permissions.full_access) + return true; + if (have_state && + has_permission(AuditEventCategory::FsReadWrite, /*by_event=*/false, state.permissions.fs_readwrite, source)) + return true; + + // Letting a root frame go runs finalizers where no dialog may open: what they do must already + // be granted, so the source check fails closed instead of prompting. + if (mgr.releasing_frames()) + return false; + + const std::string plugin_name = state.plugin_name.empty() ? mgr.current_plugin() : state.plugin_name; + if (!request_permission(AuditEventCategory::FsReadWrite, mgr.current_plugin(), plugin_name, event_name, + /*by_event=*/false, {source})) + return false; + + persist_grant(mgr.current_plugin(), AuditEventCategory::FsReadWrite, /*by_event=*/false, {source}); + return true; +} + // Judges an audited event raised while a plugin context is active. int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, AuditEventCategory event_type, PyObject* args) { const bool fs_category = is_fs_category(event_type); - const std::vector targets = audit_targets(event_name, event_type, args); + std::vector targets = audit_targets(event_name, event_type, args); + + // A dir_fd makes a relative path name an entry in the descriptor's folder, not in the working + // directory. Resolve it before any check so the deny registry, allowed roots and folder grants + // all see the folder the operation actually uses. A descriptor that cannot be resolved denies + // the operation; every later shortcut would otherwise judge the wrong path. + if (is_create_delete_category(event_type) && !resolve_create_delete_targets(event_name, args, targets)) + return report_denied(mgr, event_name, {false, "directory file descriptor cannot be resolved"}); + + // A link creation writes only its destination; its existing source is not a create target. + const std::vector permission_targets = + event_type == AuditEventCategory::FsCreate ? create_permission_targets(event_name, targets) : targets; // A denied path (secrets, certificates, config files -- see is_denied_path) is an // unconditional block: checked before the running-operation check below, so no granted @@ -2139,25 +3401,71 @@ int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, A } } + // A create/delete event with no readable destination cannot be matched against a folder grant. + if (is_create_delete_category(event_type) && permission_targets.empty()) + return report_denied(mgr, event_name, {false, "target path cannot be resolved"}); + // A nested event of an operation already granted, e.g. socket.connect inside an approved // urlopen(), is not asked again. urllib.Request is always judged on its own URL, so a - // redirect or a nested urlopen() inside a running request is not covered by it. - if (event_name != "urllib.Request" && mgr.covered_by_root_frame()) + // redirect or a nested urlopen() inside a running request is not covered by it. A read/write + // root (copytree, unpack_archive, move) covers the create/delete events it performs, but a + // delete root (rmtree) does not cover nested deletes unless this operation was started with a + // subtree-scoped delete (one-time consent or an implicit writable root). In that case a + // nested delete is covered only while its target stays inside the approved subtree and the + // stack between it and the root holds stdlib frames only; a tree grant can still allow a + // nested delete on its own. Protected paths were already denied above, so they remain blocked + // even inside an approved subtree. + const bool approved_subtree_covers_delete = + event_type == AuditEventCategory::FsDelete && + mgr.delete_target_inside_approved_subtree(permission_targets); + if (event_name != "urllib.Request" && + (mgr.covered_by_root_frame(/*allow_delete_roots=*/event_type != AuditEventCategory::FsDelete) || + approved_subtree_covers_delete)) return 0; + // A hardlink's source becomes writable through the new name, so the source needs write + // authorization on its own. This runs after root-frame coverage, so a link performed by an + // approved read/write operation is covered as part of it, and before implicit allowed roots, + // so a destination inside data_dir cannot authorize a source outside it. The destination's + // create permission does not cover the source. + if (event_name == "os.link" && is_create_delete_category(event_type)) { + if (targets.size() < 2) + return report_denied(mgr, event_name, {false, "hardlink source cannot be resolved"}); + if (!authorize_hardlink_source(mgr, event_name, targets.front())) + return report_denied(mgr, event_name, {false, "hardlink source requires write permission"}, targets.front()); + } + // A filesystem target that resolves entirely inside a pre-determined allowed root -- the // plugin system's own data_dir() tree (which holds each plugin's storage folder and the // installed/system profile cache), the read-only bundled resources folder, or a per-call // scoped root such as the current G-code folder -- is part of the plugin system's normal // workflow and does not need a prompt. - if (fs_category && !targets.empty()) { + if (fs_category && !permission_targets.empty()) { const bool is_write = event_type != AuditEventCategory::FsRead; const bool all_inside_allowed_root = - std::all_of(targets.begin(), targets.end(), [&](const std::string& target) { + std::all_of(permission_targets.begin(), permission_targets.end(), [&](const std::string& target) { + if (event_type == AuditEventCategory::FsDelete) { + // Delete scope is the entry's containing folder (or the root itself), not the + // final symlink's destination. This both keeps an outside link entry outside + // its allowed root and lets a recursive delete remove a link that lives inside + // a writable root but points outside. + return mgr.delete_target_inside_writable_allowed_root(target); + } return mgr.check_path_access(boost::filesystem::path(target), is_write).allowed; }); - if (all_inside_allowed_root) + if (all_inside_allowed_root) { + // A recursive delete allowed by an implicit root still records its operation frame, + // scoped to the target subtree. That covers the fd-based reads and os.open calls + // rmtree performs (os.scandir(fd) exposes no path) and lets the walk remove symlink + // entries without prompting, while nested deletes stay inside the target subtree. + if (event_type == AuditEventCategory::FsDelete && event_name == "shutil.rmtree" && + permission_targets.size() == 1) { + boost::filesystem::path implicit_subtree; + if (resolve_create_delete_folder(boost::filesystem::path(permission_targets.front()), implicit_subtree)) + mgr.record_root_frame(event_type, implicit_subtree); + } return 0; + } } PluginInstallState state; @@ -2168,17 +3476,53 @@ int audit_plugin_event(PluginAuditManager& mgr, const std::string& event_name, A const std::string plugin_name = state.plugin_name.empty() ? mgr.current_plugin() : state.plugin_name; - const int result = decide_audited_event(mgr, state, mgr.current_plugin(), plugin_name, event_name, event_type, targets); + boost::filesystem::path approved_delete_subtree; + const int result = decide_audited_event(mgr, state, mgr.current_plugin(), plugin_name, event_name, event_type, + permission_targets, approved_delete_subtree); - // A granted operation covers its nested events while it runs. A targetless grant names no - // operation, so it covers nothing else. - if (result == 0 && !targets.empty() && operation_root_events.count(event_name)) - mgr.record_root_frame(); + // A granted operation covers its nested events while it runs, except that a delete root does + // not cover a nested delete unless a subtree-scoped delete was recorded on the frame (see the + // coverage check above). A targetless grant names no operation, so it covers nothing else. + if (result == 0 && !permission_targets.empty() && operation_root_events.count(event_name)) + mgr.record_root_frame(event_type, approved_delete_subtree); return result; } } // namespace PluginAuditDetail +bool PluginAuditManager::delete_target_inside_writable_allowed_root(const std::string& target) const +{ + if (target.empty()) + return false; + + // Deleting `target` acts on an entry in its containing folder, or on the root itself. Never + // decide from the final component's symlink destination: an outside link pointing into a + // writable root must not become an implicit delete of the outside entry. + const auto inside_root = [&target](const AllowedRoot& root) { + if (!root.allow_write) + return false; + boost::filesystem::path canonical_root; + return PluginAuditDetail::canonical_folder(root.path, canonical_root) && + PluginAuditDetail::delete_target_within_subtree(target, canonical_root); + }; + + if (std::any_of(m_scoped_allowed_roots.begin(), m_scoped_allowed_roots.end(), inside_root)) + return true; + + std::lock_guard lock(m_mutex); + return std::any_of(m_global_allowed_roots.begin(), m_global_allowed_roots.end(), inside_root); +} + +bool PluginAuditManager::consume_recursive_delete_approval(const std::string& plugin_key, const std::string& canonical_root) +{ + return PluginAuditDetail::take_recursive_delete_approval(plugin_key, canonical_root); +} + +void PluginAuditManager::add_recursive_delete_approval(const std::string& plugin_key, const std::string& canonical_root) +{ + PluginAuditDetail::store_recursive_delete_approval(plugin_key, canonical_root); +} + AuditPromptQueue& runtime_prompt_queue_for_testing() { return PluginAuditDetail::runtime_audit_prompts(); } bool prompt_plugin_is_available(const AuditPromptPluginState& state, AuditPromptKind kind) @@ -2189,10 +3533,11 @@ bool prompt_plugin_is_available(const AuditPromptPluginState& state, AuditPrompt if (state.loaded || state.load_in_progress) return true; - // No worker is left to answer a load-time declaration after its load failed, and an - // informational denial was never an approval request. A runtime event has no worker: its - // denial may be what aborted the load, so an ordinary failure keeps it actionable. - return kind == AuditPromptKind::RuntimeEvent && state.load_failed; + // No worker is left to answer a load-time declaration after its load failed. A runtime event + // or a one-time recursive-delete consent has no worker: its denial may be what aborted the + // load, so an ordinary failure keeps it actionable. + return (kind == AuditPromptKind::RuntimeEvent || kind == AuditPromptKind::RecursiveDeleteConsent) && + state.load_failed; } bool AuditPromptBucket::operator==(const AuditPromptBucket& other) const @@ -2224,27 +3569,35 @@ AuditPromptQueue::Admission AuditPromptQueue::admit_synchronous(AuditPromptReque } AuditPromptQueue::Admission AuditPromptQueue::admit(AuditPromptRequest request, bool may_show_now) -{ - AuditPromptRequest queued = request; - return admit_with_fallback(std::move(request), std::move(queued), may_show_now); -} - -AuditPromptQueue::Admission AuditPromptQueue::admit_with_fallback(AuditPromptRequest immediate_request, - AuditPromptRequest queued_request, bool may_show_now) { std::lock_guard lock(m_mutex); if (may_show_now && !m_active && m_pending.empty()) { - m_active = std::move(immediate_request); + m_active = std::move(request); m_active_cancelled = false; m_active_committing = false; return Admission::ShowNow; } - if (contains_locked(queued_request)) + if (contains_locked(request)) return Admission::Duplicate; - m_pending.push_back(std::move(queued_request)); + // A recursive-delete consent is a modal per target, and a plugin retry loop can name many + // distinct targets. Keep that set bounded, as the direct-prompt path did: at capacity, reject + // the new consent instead of letting pending dialogs grow without limit. The count includes + // the active prompt because its dialog is still on screen. + if (request.kind == AuditPromptKind::RecursiveDeleteConsent) { + const auto is_consent = [](const AuditPromptRequest& queued) { + return queued.kind == AuditPromptKind::RecursiveDeleteConsent; + }; + std::size_t consent_count = std::count_if(m_pending.begin(), m_pending.end(), is_consent); + if (m_active && is_consent(*m_active)) + ++consent_count; + if (consent_count >= PluginAuditDetail::kMaxRecursiveDeletePrompts) + return Admission::Rejected; + } + + m_pending.push_back(std::move(request)); return Admission::Queued; } @@ -2317,6 +3670,15 @@ void AuditPromptQueue::discard_plugin(const std::string& plugin_key) completion->resolve(false); } +void AuditPromptQueue::discard_recursive_delete_consents(const std::string& plugin_key) +{ + // No worker ever waits on a consent, so the returned completions are always empty; ignore + // them. The active consent, if any, is marked cancelled so its answer stores nothing. + discard_matching([&plugin_key](const AuditPromptRequest& request) { + return request.kind == AuditPromptKind::RecursiveDeleteConsent && request.plugin_key == plugin_key; + }); +} + std::vector> AuditPromptQueue::discard_matching(const std::function& matches) { @@ -2345,11 +3707,17 @@ bool AuditPromptQueue::same_request(const AuditPromptRequest& a, const AuditProm switch (a.kind) { case AuditPromptKind::RuntimeEvent: - return a.category == b.category && a.by_event == b.by_event && a.keys == b.keys; + // The entries are what the dialog shows for a create/delete target, so two requests that + // trigger on different paths are not equivalent even when they save the same folder. + return a.category == b.category && a.by_event == b.by_event && a.keys == b.keys && a.shown == b.shown && + a.entries == b.entries; case AuditPromptKind::DeclaredPermissions: return a.buckets == b.buckets; - case AuditPromptKind::DeniedOperation: - return a.category == b.category && a.shown == b.shown; + case AuditPromptKind::RecursiveDeleteConsent: + // One pending consent per plugin and canonical subtree within one permission generation. + // A permission edit or revocation starts a new generation: the stale prompt's Yes is + // ignored, and a retry after the edit must not be coalesced into that dead request. + return a.shown == b.shown && a.recursive_delete_generation == b.recursive_delete_generation; } return false; } @@ -2430,6 +3798,51 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons collect_missing(AuditEventCategory::FsRead, requested.fs_read, state.permissions.fs_read); collect_missing(AuditEventCategory::FsReadWrite, requested.fs_readwrite, state.permissions.fs_readwrite); + + // Create/delete requests name folders and are stored as canonical absolute paths. A trailing + // "/*" requests the folder and every folder below it at any depth; any other wildcard is + // rejected. A sole "*" requests unrestricted access. An entry that cannot be resolved fails + // the whole request: storing a grant with a different scope than the one approved is not + // acceptable. + const auto collect_missing_create_delete = + [&missing_buckets](AuditEventCategory category, const std::vector& requested_folders, + const std::vector& granted_folders) { + const size_t requested_count = static_cast( + std::count_if(requested_folders.begin(), requested_folders.end(), + [](const std::string& folder) { return !folder.empty(); })); + AuditPromptBucket bucket{category, {}}; + for (const std::string& requested_folder : requested_folders) { + if (requested_folder.empty()) + continue; + if (requested_folder == "*") { + // Unrestricted access is the one-element form, matching what the sidecar + // stores. A "*" beside other entries is ambiguous, so the request fails closed + // instead of widening or silently ignoring it. + if (requested_count != 1) + return false; + if (!PluginAuditDetail::create_delete_grant_full(granted_folders)) + bucket.targets.assign(1, "*"); + break; + } + // A trailing "/*" is a tree grant. Declarations accept literal folders, tree + // grants and the sole "*" full form; any other wildcard makes the request fail + // closed instead of being stored as a literal name or widened into a folder grant. + std::string grant; + if (!PluginAuditDetail::absolute_create_delete_grant(requested_folder, grant)) + return false; + if (!PluginAuditDetail::create_delete_grant_covers_grant(granted_folders, grant) && + std::find(bucket.targets.begin(), bucket.targets.end(), grant) == bucket.targets.end()) + bucket.targets.push_back(grant); + } + if (!bucket.targets.empty()) + missing_buckets.push_back(std::move(bucket)); + return true; + }; + + if (!collect_missing_create_delete(AuditEventCategory::FsCreate, requested.fs_create, state.permissions.fs_create) || + !collect_missing_create_delete(AuditEventCategory::FsDelete, requested.fs_delete, state.permissions.fs_delete)) + return false; + collect_missing(AuditEventCategory::Http, requested.network_http, state.permissions.network_http); collect_missing(AuditEventCategory::Socket, requested.network_socket, state.permissions.network_socket); collect_missing(AuditEventCategory::ProcessCreate, requested.process, state.permissions.process); @@ -2554,18 +3967,37 @@ bool PluginAuditManager::request_permissions(const std::string& plugin_key, cons return false; } -void PluginAuditManager::record_root_frame() +bool PluginAuditManager::is_create_delete_tree_grant(const std::string& target) +{ + boost::filesystem::path root; + return PluginAuditDetail::requested_tree_grant_root(target, root); +} + +void PluginAuditManager::record_root_frame(AuditEventCategory category, + const boost::filesystem::path& approved_delete_subtree) { PyObject* frame = reinterpret_cast(PyEval_GetFrame()); // borrowed reference if (!frame || !PluginAuditDetail::is_stdlib_frame(frame)) return; - if (std::find(m_root_frames.begin(), m_root_frames.end(), frame) != m_root_frames.end()) - return; // glob.glob and glob.glob/2 share a frame - Py_INCREF(frame); - m_root_frames.push_back(frame); + + const bool delete_root = category == AuditEventCategory::FsDelete; + auto it = std::find_if(m_root_frames.begin(), m_root_frames.end(), + [frame](const RootFrame& record) { return record.frame == frame; }); + if (it == m_root_frames.end()) { + Py_INCREF(frame); + m_root_frames.push_back({frame, delete_root, approved_delete_subtree}); + return; + } + // The record owns the one reference; the mark is sticky, so a frame first recorded as a + // read/write root still stops covering nested deletes once it is also a delete root. + if (delete_root) + it->delete_root = true; + // Keep a subtree consent already recorded on this frame; a later grant does not widen it. + if (!approved_delete_subtree.empty()) + it->approved_delete_subtree = approved_delete_subtree; } -bool PluginAuditManager::covered_by_root_frame() const +bool PluginAuditManager::covered_by_root_frame(bool allow_delete_roots) const { if (m_root_frames.empty()) return false; @@ -2573,14 +4005,54 @@ bool PluginAuditManager::covered_by_root_frame() const // Only stdlib frames may sit between the event and the operation: plugin or library code // the operation calls back into (an os.walk onerror, a urllib handler) acts on its own. for (PyObject* frame : PluginAuditDetail::stack_frames()) { - if (std::find(m_root_frames.begin(), m_root_frames.end(), frame) != m_root_frames.end()) - return true; + const auto root = std::find_if(m_root_frames.begin(), m_root_frames.end(), + [frame](const RootFrame& record) { return record.frame == frame; }); + if (root != m_root_frames.end()) { + // A delete root does not cover a nested delete by itself: an exact folder grant + // covers direct entries only, while an outer read/write root may still cover the + // same operation, and a tree grant may allow it when the event is judged. A delete + // root started with one-time subtree consent is handled by + // delete_target_inside_approved_subtree(), which also checks the target's scope. + if (!root->delete_root || allow_delete_roots) + return true; + continue; + } if (!PluginAuditDetail::is_stdlib_frame(frame)) return false; } return false; } +bool PluginAuditManager::delete_target_inside_approved_subtree(const std::vector& targets) const +{ + if (m_root_frames.empty() || targets.empty()) + return false; + + // Same frame walk as covered_by_root_frame: stop at plugin or third-party code, so a callback + // the operation invokes is judged on its own. The first delete root carrying a one-time + // consent is the operation boundary; only its canonical subtree covers the nested deletes. + for (PyObject* frame : PluginAuditDetail::stack_frames()) { + const auto root = std::find_if(m_root_frames.begin(), m_root_frames.end(), + [frame](const RootFrame& record) { return record.frame == frame; }); + if (root == m_root_frames.end()) { + if (!PluginAuditDetail::is_stdlib_frame(frame)) + break; + continue; + } + + if (!root->delete_root || root->approved_delete_subtree.empty()) + continue; // keep looking for an outer operation with subtree consent + + const boost::filesystem::path& approved_subtree = root->approved_delete_subtree; + for (const std::string& target : targets) { + if (!PluginAuditDetail::delete_target_within_subtree(target, approved_subtree)) + return false; + } + return true; + } + return false; +} + bool PluginAuditManager::releasing_frames() const { return m_releasing_frames > 0; } bool PluginAuditManager::is_stdlib_file(const std::string& filename) @@ -2617,7 +4089,7 @@ bool PluginAuditManager::is_stdlib_path(const boost::filesystem::path& path) return inside_any(PluginAuditDetail::s_stdlib_dirs) && !inside_any(PluginAuditDetail::s_site_package_dirs); } -void PluginAuditManager::release_frames(std::vector& frames) +void PluginAuditManager::release_frames(std::vector& frames) { if (frames.empty()) return; @@ -2629,11 +4101,11 @@ void PluginAuditManager::release_frames(std::vector& frames) const bool has_violation = m_has_last_violation; const AuditViolation violation = m_last_violation; - std::vector released; + std::vector released; released.swap(frames); ++m_releasing_frames; - for (PyObject* frame : released) - Py_DECREF(frame); + for (const RootFrame& record : released) + Py_DECREF(record.frame); --m_releasing_frames; m_audit_denial_pending = denial_pending; @@ -2647,6 +4119,90 @@ void PluginAuditManager::set_permission_prompt_for_testing(PermissionPrompt prom PluginAuditDetail::s_permission_prompt_for_testing = std::move(prompt); } +void PluginAuditManager::set_recursive_delete_prompt_for_testing(RecursiveDeletePrompt prompt) +{ + PluginAuditDetail::s_recursive_delete_prompt_for_testing = std::move(prompt); +} + +void PluginAuditManager::set_recursive_delete_prompt_background_for_testing(bool background) +{ + PluginAuditDetail::s_recursive_delete_prompt_background_for_testing = background; +} + +std::string PluginAuditManager::format_recursive_delete_permission_prompt_for_testing(const std::string& plugin_name, + const std::string& target, + bool root_scope, + bool background) +{ + return PluginAuditDetail::formatted_recursive_delete_message(wxString::FromUTF8(plugin_name.c_str()), + wxString::FromUTF8(target.c_str()), root_scope, + background) + .text.utf8_string(); +} + +void PluginAuditManager::set_recursive_delete_prompt_deferred_for_testing(bool deferred) +{ + PluginAuditDetail::s_recursive_delete_prompt_deferred_for_testing = deferred; +} + +std::uint64_t PluginAuditManager::recursive_delete_generation_for_testing(const std::string& plugin_key) +{ + return PluginAuditDetail::recursive_delete_generation(plugin_key); +} + +void PluginAuditManager::answer_recursive_delete_prompt_for_testing(const std::string& plugin_key, + const std::string& canonical_root, bool granted, + std::uint64_t generation) +{ + PluginAuditDetail::finish_recursive_delete_prompt(plugin_key, canonical_root, generation); + if (granted && PluginAuditDetail::recursive_delete_generation(plugin_key) == generation) + PluginAuditDetail::store_recursive_delete_approval(plugin_key, canonical_root); +} + +void PluginAuditManager::invalidate_recursive_delete_state(const std::string& plugin_key) +{ + PluginAuditDetail::invalidate_recursive_delete_state(plugin_key); +} + +std::size_t PluginAuditManager::pending_recursive_delete_prompts_for_testing() +{ + return PluginAuditDetail::pending_recursive_delete_prompts(); +} + +bool PluginAuditManager::delete_target_inside_subtree_for_testing(const std::string& target, + const std::string& canonical_subtree) +{ + boost::filesystem::path subtree; + if (!PluginAuditDetail::canonical_folder(boost::filesystem::path(canonical_subtree), subtree)) + return false; + return PluginAuditDetail::delete_target_within_subtree(target, subtree); +} + +void PluginAuditManager::clear_recursive_delete_approvals_for_testing() +{ + std::lock_guard lock(PluginAuditDetail::s_recursive_delete_approval_mutex); + PluginAuditDetail::s_recursive_delete_approvals.clear(); + PluginAuditDetail::s_pending_recursive_delete_prompts.clear(); +} + +void PluginAuditManager::set_recursive_delete_approval_lifetime_for_testing(std::chrono::milliseconds lifetime) +{ + std::lock_guard lock(PluginAuditDetail::s_recursive_delete_approval_mutex); + PluginAuditDetail::s_recursive_delete_approval_lifetime = lifetime; +} + +std::size_t PluginAuditManager::pending_recursive_delete_approvals_for_testing() +{ + return PluginAuditDetail::pending_recursive_delete_approvals(); +} + +std::string PluginAuditManager::format_create_delete_permission_prompt_for_testing( + AuditEventCategory category, const std::string& plugin_name, const std::vector& entries) +{ + return PluginAuditDetail::formatted_create_delete_message(category, wxString::FromUTF8(plugin_name.c_str()), entries) + .text.utf8_string(); +} + void PluginAuditManager::set_permission_message_prompt_for_testing(PermissionMessagePrompt prompt) { PluginAuditDetail::s_permission_message_prompt_for_testing = std::move(prompt); @@ -2691,7 +4247,7 @@ int PluginAuditManager::audit_hook(const char* event, PyObject* args, void* user // Root frames whose operation has returned are let go once this event is decided, so that a // finalizer they run re-enters a hook whose held frames are already consistent. - std::vector returned_frames; + std::vector returned_frames; PluginAuditDetail::take_returned_frames(m_root_frames, returned_frames); int result = -1; // A C++ exception must not unwind through the interpreter that raised the event, so a check diff --git a/src/slic3r/plugin/PluginAuditManager.hpp b/src/slic3r/plugin/PluginAuditManager.hpp index de3343ff4f..04498a5eba 100644 --- a/src/slic3r/plugin/PluginAuditManager.hpp +++ b/src/slic3r/plugin/PluginAuditManager.hpp @@ -4,7 +4,9 @@ // Via pybind11 so this file requests the same python3xx.lib as everything else. #include #include +#include #include +#include #include #include #include @@ -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 + // "/*" 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; + 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& 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& 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& targets, + const std::vector& 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& 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& frames); + void release_frames(std::vector& frames); static thread_local std::string m_current_plugin_key; static thread_local std::string m_current_capability_name; static thread_local std::vector m_scoped_allowed_roots; - static thread_local std::vector m_root_frames; // strong references + static thread_local std::vector 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 m_previous_scoped_roots; - std::vector 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 m_previous_scoped_roots; + std::vector m_previous_root_frames; }; -// What a queued prompt asks the user. A runtime event and a permission declaration can both grant -// what they show; an informational denial cannot, so it has no Yes/No choice. +// 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 keys; std::vector shown; + std::vector entries; // DeclaredPermissions only: the missing buckets the combined dialog lists. std::vector buckets; // DeclaredPermissions only: whether the sidecar was readable when the declaration was read. // The queued write must not recreate a sidecar that was readable then but has since // disappeared; only one absent at both reads is treated as a new install to seed. bool sidecar_was_readable = false; + // 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 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 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; diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index 071a8331e0..480fc3f2e7 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -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 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& 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}, diff --git a/src/slic3r/plugin/PluginFsUtils.hpp b/src/slic3r/plugin/PluginFsUtils.hpp index bd35f823eb..5845aa3acf 100644 --- a/src/slic3r/plugin/PluginFsUtils.hpp +++ b/src/slic3r/plugin/PluginFsUtils.hpp @@ -23,6 +23,20 @@ struct PluginPermissions // component. Reads and writes stay separate buckets: a wildcard in one never grants the other. std::vector fs_read; std::vector 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 fs_create; + std::vector fs_delete; std::vector network_http; std::vector network_socket; std::vector 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& allowed_dirs); diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index 95b8261496..4a802c1c59 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -65,6 +65,8 @@ std::vector* 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 ─────────────────────────────────────────────────────────────────────────────── diff --git a/src/slic3r/plugin/PluginManager.hpp b/src/slic3r/plugin/PluginManager.hpp index 77eb04de8f..5775f5021e 100644 --- a/src/slic3r/plugin/PluginManager.hpp +++ b/src/slic3r/plugin/PluginManager.hpp @@ -117,6 +117,8 @@ struct ScriptCompletion enum class PluginPermissionCategory { FsRead, FsReadWrite, + FsCreate, + FsDelete, NetworkHttp, NetworkSocket, Process, diff --git a/src/slic3r/plugin/PythonPluginBridge.cpp b/src/slic3r/plugin/PythonPluginBridge.cpp index b27a8b1431..050a60a285 100644 --- a/src/slic3r/plugin/PythonPluginBridge.cpp +++ b/src/slic3r/plugin/PythonPluginBridge.cpp @@ -189,6 +189,7 @@ std::vector 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& network_socket, const std::vector& process, bool threading, - const std::vector& network) { + const std::vector& network, + const std::vector& fs_create, + const std::vector& 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& 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{}, py::arg("threading") = false, py::arg("network") = std::vector{}, + py::arg("fs_create") = std::vector{}, + py::arg("fs_delete") = std::vector{}, 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 diff --git a/tests/slic3rutils/test_plugin_audit.cpp b/tests/slic3rutils/test_plugin_audit.cpp index 634c20f444..98b3c2e05a 100644 --- a/tests/slic3rutils/test_plugin_audit.cpp +++ b/tests/slic3rutils/test_plugin_audit.cpp @@ -4,6 +4,7 @@ #include #include +#include #include #include // GCODEVIEWER_APP_KEY, SLIC3R_APP_KEY (via libslic3r_version.h) #include @@ -35,6 +36,8 @@ #include #include +#include +#include #include #include #include @@ -48,6 +51,16 @@ #include #include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#endif + using namespace Slic3r; namespace fs = boost::filesystem; namespace py = pybind11; @@ -81,6 +94,29 @@ std::string read_text_file(const fs::path& path) return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); } +#ifdef _WIN32 +// The 8.3 short form of an existing path. Empty when the volume does not generate short names +// (the conversion then returns the input unchanged) or the call fails. Whether a machine spells a +// path short is environment-dependent, so tests build the alias here instead of assuming one. +fs::path short_name_alias(const fs::path& long_path) +{ + const std::wstring native = long_path.native(); + std::wstring buffer(native.size() + 1, L'\0'); + for (;;) { + const DWORD length = ::GetShortPathNameW(native.c_str(), buffer.data(), static_cast(buffer.size())); + if (length == 0) + return {}; + if (length < buffer.size()) { + buffer.resize(length); + break; + } + buffer.resize(static_cast(length) + 1); + } + const fs::path alias(buffer); + return alias == long_path ? fs::path() : alias; +} +#endif + } // namespace namespace { @@ -115,18 +151,6 @@ AuditPromptRequest declared_request(const std::string& plugin_key, std::vector targets) -{ - AuditPromptRequest request = prompt_request(plugin_key, category, std::move(targets)); - request.event_name = category == AuditEventCategory::FsDelete ? "os.remove" : "open"; - request.kind = AuditPromptKind::DeniedOperation; - return request; -} - // A request plus the completion a blocked load worker waits on, and the future that worker holds. struct WaitingRequest { @@ -274,20 +298,19 @@ TEST_CASE("Unloading a plugin drops only that plugin's queued audit prompts", "[ CHECK(queue.idle()); } -TEST_CASE("Runtime, declared, and informational audit prompts are serialized in arrival order", "[audit][Python]") +TEST_CASE("Runtime and declared audit prompts are serialized in arrival order", "[audit][Python]") { AuditPromptQueue queue; - // A GUI-thread event arrives first and is on screen; the declaration and the informational - // denial that follow both have to wait for it, whatever their kind. + // A GUI-thread event arrives first and is on screen; the declaration and the create/delete + // runtime prompt that follow both have to wait for it. CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/runtime"}), /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); CHECK(queue.admit(declared_request("plugin", {bucket(AuditEventCategory::Http, {"https://api.example.com"})}), /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); - // A create/delete event falls back to its informational denial while a dialog is up. - CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsDelete, {"/deleted"}), - denied_request("plugin", AuditEventCategory::FsDelete, {"/deleted"}), - /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); + AuditPromptRequest create = prompt_request("plugin", AuditEventCategory::FsCreate, {"/work"}); + create.entries = {{"/work/new.txt", "/work"}}; + CHECK(queue.admit(create, /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); CHECK(queue.pending_count() == 2); // At most one prompt is on screen: nothing is handed out until the active dialog returns. @@ -301,21 +324,22 @@ TEST_CASE("Runtime, declared, and informational audit prompts are serialized in CHECK(declared->buckets.front().category == AuditEventCategory::Http); const std::vector declared_targets{"https://api.example.com"}; CHECK(declared->buckets.front().targets == declared_targets); - // The declaration's dialog is up now: the informational prompt still waits behind it. + // The declaration's dialog is up now: the runtime prompt still waits behind it. CHECK_FALSE(queue.take_next().has_value()); CHECK(queue.pending_count() == 1); queue.complete(); - std::optional denied = queue.take_next(); - REQUIRE(denied.has_value()); - CHECK(denied->kind == AuditPromptKind::DeniedOperation); - CHECK(denied->category == AuditEventCategory::FsDelete); - const std::vector denied_targets{"/deleted"}; - CHECK(denied->shown == denied_targets); - // A denial copies the runtime request it denies, so its keys are present even though the - // category grants nothing via a denial, and no worker waits on it. - CHECK(denied->keys == denied_targets); - CHECK(denied->completion == nullptr); + std::optional queued_create = queue.take_next(); + REQUIRE(queued_create.has_value()); + CHECK(queued_create->kind == AuditPromptKind::RuntimeEvent); + CHECK(queued_create->category == AuditEventCategory::FsCreate); + // A queued create/delete prompt keeps both the folder a Yes saves and the triggering path the + // dialog shows. + const std::vector saved_folders{"/work"}; + CHECK(queued_create->keys == saved_folders); + CHECK(queued_create->entries == + std::vector{{"/work/new.txt", "/work"}}); + CHECK(queued_create->completion == nullptr); queue.complete(); CHECK(queue.idle()); } @@ -345,77 +369,215 @@ TEST_CASE("Only exactly equivalent declared permission prompts are coalesced", " CHECK_FALSE(shown.idle()); } -TEST_CASE("An informational denial never coalesces with a runtime prompt for the same operation", "[audit][Python]") +TEST_CASE("Queued create/delete prompts are coalesced only when their triggering paths match", "[audit][Python]") { AuditPromptQueue queue; - // A GUI-thread create is a real Yes/No prompt; the informational denial of a worker create - // must not be mistaken for a duplicate of it and dropped unseen. - CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/true) == - AuditPromptQueue::Admission::ShowNow); - CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/false) == - AuditPromptQueue::Admission::Queued); - CHECK(queue.pending_count() == 1); + AuditPromptRequest first = prompt_request("plugin", AuditEventCategory::FsCreate, {"/work"}); + first.entries = {{"/work/new.txt", "/work"}}; + CHECK(queue.admit(first, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(first, /*may_show_now=*/false) == AuditPromptQueue::Admission::Duplicate); - // Two informational denials of the same operation show nothing new the second time. - CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/false) == - AuditPromptQueue::Admission::Duplicate); - // Another target, another category, or another plugin is a separate denial to show. - CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsCreate, {"/other"}), /*may_show_now=*/false) == - AuditPromptQueue::Admission::Queued); - CHECK(queue.admit(denied_request("plugin", AuditEventCategory::FsDelete, {"/new"}), /*may_show_now=*/false) == - AuditPromptQueue::Admission::Queued); - CHECK(queue.admit(denied_request("other_plugin", AuditEventCategory::FsCreate, {"/new"}), /*may_show_now=*/false) == - AuditPromptQueue::Admission::Queued); + // The same saved folder reached through another path is a different prompt: it shows a + // different target, so dropping it would hide why the plugin was stopped. + AuditPromptRequest second = first; + second.entries = {{"/work/other.txt", "/work"}}; + CHECK(queue.admit(second, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + + // Another category, another saved folder, or another plugin is a separate prompt too. + AuditPromptRequest deleted = prompt_request("plugin", AuditEventCategory::FsDelete, {"/work"}); + deleted.entries = {{"/work/old.txt", "/work"}}; + CHECK(queue.admit(deleted, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + AuditPromptRequest other_plugin = first; + other_plugin.plugin_key = "other_plugin"; + CHECK(queue.admit(other_plugin, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); CHECK(queue.pending_count() == 4); } -TEST_CASE("A create/delete prompt falls back to an informational denial when another prompt is up", "[audit][Python]") +TEST_CASE("A queued create/delete prompt keeps the target entries and the folder a Yes saves", "[audit][Python]") { AuditPromptQueue queue; - // Idle GUI thread: the immediate Yes/No prompt is shown, so a create can really be approved. - CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), - denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), - /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); - CHECK(queue.pending_count() == 0); - - // Its dialog is up, so the same create cannot be shown as a second Yes/No prompt; it queues as - // the informational denial that matches what the user can actually do. - CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), - denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), - /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); - // The queued denial is not a duplicate of the active Yes/No prompt, and is not queued twice. - CHECK(queue.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsCreate, {"/new"}), - denied_request("plugin", AuditEventCategory::FsCreate, {"/new"}), - /*may_show_now=*/true) == AuditPromptQueue::Admission::Duplicate); + // Another dialog is up, so the create prompt waits rather than opening a second modal. Its + // approval still saves the folder, so a retry can succeed. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/busy"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::ShowNow); + AuditPromptRequest create = prompt_request("plugin", AuditEventCategory::FsCreate, {"/work"}); + create.entries = {{"/work/new.txt", "/work"}}; + CHECK(queue.admit(create, /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); CHECK(queue.pending_count() == 1); - queue.complete(); + std::optional queued = queue.take_next(); REQUIRE(queued.has_value()); - CHECK(queued->kind == AuditPromptKind::DeniedOperation); + CHECK(queued->kind == AuditPromptKind::RuntimeEvent); CHECK(queued->category == AuditEventCategory::FsCreate); - const std::vector expected{"/new"}; - CHECK(queued->shown == expected); - CHECK(queued->keys == expected); + const std::vector expected_folder{"/work"}; + CHECK(queued->keys == expected_folder); + CHECK(queued->entries == + std::vector{{"/work/new.txt", "/work"}}); CHECK(queued->completion == nullptr); queue.complete(); CHECK(queue.idle()); - // A worker create also gets the informational denial while the queue is idle: it cannot - // authorize the operation, so showing a Yes/No prompt would promise a grant it cannot keep. + // A worker create also keeps its Yes/No prompt while the queue is idle; the current operation + // stays denied, but the queued answer persists the folder for a retry. AuditPromptQueue worker; - CHECK(worker.admit_with_fallback(prompt_request("plugin", AuditEventCategory::FsDelete, {"/gone"}), - denied_request("plugin", AuditEventCategory::FsDelete, {"/gone"}), - /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); - std::optional denial = worker.take_next(); - REQUIRE(denial.has_value()); - CHECK(denial->kind == AuditPromptKind::DeniedOperation); + CHECK(worker.admit(create, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + std::optional retry = worker.take_next(); + REQUIRE(retry.has_value()); + CHECK(retry->kind == AuditPromptKind::RuntimeEvent); + CHECK(retry->keys == expected_folder); + CHECK(retry->entries == + std::vector{{"/work/new.txt", "/work"}}); worker.complete(); CHECK(worker.idle()); } +TEST_CASE("A recursive-delete consent shares the serialized audit prompt queue", "[audit][Python]") +{ + AuditPromptQueue queue; + + AuditPromptRequest consent; + consent.kind = AuditPromptKind::RecursiveDeleteConsent; + consent.plugin_key = "plugin"; + consent.plugin_name = "Plugin"; + consent.event_name = "shutil.rmtree"; + consent.shown = {"/work/sub"}; + consent.root_scope = false; + consent.recursive_delete_generation = 7; + + // A permission dialog is on screen: the consent waits and is not duplicated by a retry loop. + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/busy"}), /*may_show_now=*/true) == + AuditPromptQueue::Admission::ShowNow); + CHECK(queue.admit(consent, /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(consent, /*may_show_now=*/true) == AuditPromptQueue::Admission::Duplicate); + CHECK(queue.pending_count() == 1); + queue.complete(); + + std::optional queued = queue.take_next(); + REQUIRE(queued.has_value()); + CHECK(queued->kind == AuditPromptKind::RecursiveDeleteConsent); + const std::vector target{"/work/sub"}; + CHECK(queued->shown == target); + CHECK(queued->root_scope == false); + CHECK(queued->recursive_delete_generation == 7); + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("Discarding a plugin drops its queued recursive-delete consent", "[audit][Python]") +{ + AuditPromptQueue queue; + + AuditPromptRequest consent; + consent.kind = AuditPromptKind::RecursiveDeleteConsent; + consent.plugin_key = "unloaded"; + consent.shown = {"/work/sub"}; + CHECK(queue.admit(consent, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + + queue.discard_plugin("unloaded"); + CHECK_FALSE(queue.has_pending()); + queue.complete(); + CHECK_FALSE(queue.take_next().has_value()); + CHECK(queue.idle()); +} + +TEST_CASE("A permission change drops only that plugin's queued recursive-delete consents", "[audit][Python]") +{ + AuditPromptQueue queue; + + AuditPromptRequest consent; + consent.kind = AuditPromptKind::RecursiveDeleteConsent; + consent.plugin_key = "plugin"; + consent.shown = {"/work/sub"}; + CHECK(queue.admit(consent, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + CHECK(queue.admit(prompt_request("plugin", AuditEventCategory::FsRead, {"/still-needed"}), /*may_show_now=*/false) == + AuditPromptQueue::Admission::Queued); + + queue.discard_recursive_delete_consents("plugin"); + CHECK(queue.pending_count() == 1); + + std::optional kept = queue.take_next(); + REQUIRE(kept.has_value()); + CHECK(kept->kind == AuditPromptKind::RuntimeEvent); + queue.complete(); + CHECK(queue.idle()); + + // An active consent cannot be withdrawn, but it is marked cancelled so its answer stores + // nothing. + CHECK(queue.admit(consent, /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + queue.discard_recursive_delete_consents("plugin"); + CHECK(queue.complete()); + CHECK(queue.idle()); +} + +TEST_CASE("A recursive-delete retry after a permission change is not coalesced into the stale consent", "[audit][Python]") +{ + AuditPromptQueue queue; + + AuditPromptRequest stale; + stale.kind = AuditPromptKind::RecursiveDeleteConsent; + stale.plugin_key = "plugin"; + stale.shown = {"/work/sub"}; + stale.recursive_delete_generation = 1; + CHECK(queue.admit(stale, /*may_show_now=*/true) == AuditPromptQueue::Admission::ShowNow); + + // The permission edit bumped the generation while the old dialog was up. The retry must not + // be dropped as a duplicate of a prompt whose Yes can no longer store anything. + AuditPromptRequest retry = stale; + retry.recursive_delete_generation = 2; + CHECK(queue.admit(retry, /*may_show_now=*/true) == AuditPromptQueue::Admission::Queued); + CHECK(queue.pending_count() == 1); + + queue.complete(); + std::optional fresh = queue.take_next(); + REQUIRE(fresh.has_value()); + CHECK(fresh->kind == AuditPromptKind::RecursiveDeleteConsent); + CHECK(fresh->recursive_delete_generation == 2); + queue.complete(); + CHECK(queue.idle()); +} + +TEST_CASE("A permission invalidation drops queued recursive-delete consents", "[audit][Python]") +{ + ScopedRuntimePromptQueue queue; + + AuditPromptRequest consent; + consent.kind = AuditPromptKind::RecursiveDeleteConsent; + consent.plugin_key = "queue-invalidation-test"; + consent.shown = {"/work/sub"}; + consent.recursive_delete_generation = PluginAuditManager::recursive_delete_generation_for_testing(consent.plugin_key); + CHECK(queue.queue.admit(consent, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + + PluginAuditManager::instance().invalidate_recursive_delete_state(consent.plugin_key); + CHECK_FALSE(queue.queue.has_pending()); + + // A retry now carries the new generation and is accepted as a fresh consent. + consent.recursive_delete_generation = PluginAuditManager::recursive_delete_generation_for_testing(consent.plugin_key); + CHECK(queue.queue.admit(consent, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); +} + +TEST_CASE("The serialized queue bounds pending recursive-delete consents", "[audit][Python]") +{ + AuditPromptQueue queue; + + AuditPromptRequest consent; + consent.kind = AuditPromptKind::RecursiveDeleteConsent; + consent.plugin_key = "plugin"; + for (int i = 0; i < 16; ++i) { + consent.shown = {"/work/" + std::to_string(i)}; + CHECK(queue.admit(consent, /*may_show_now=*/false) == AuditPromptQueue::Admission::Queued); + } + // The bound is the same as the direct-prompt path: a new distinct target is rejected, while + // the request already queued is still recognised as a duplicate. + consent.shown = {"/work/extra"}; + CHECK(queue.admit(consent, /*may_show_now=*/false) == AuditPromptQueue::Admission::Rejected); + consent.shown = {"/work/0"}; + CHECK(queue.admit(consent, /*may_show_now=*/false) == AuditPromptQueue::Admission::Duplicate); + CHECK(queue.pending_count() == 16); +} + TEST_CASE("A synchronous audit prompt is shown only while the queue is idle", "[audit][Python]") { AuditPromptQueue queue; @@ -594,9 +756,10 @@ TEST_CASE("A queued runtime prompt survives an ordinary load failure", "[audit]" CHECK(prompt_plugin_is_available(failed, AuditPromptKind::RuntimeEvent)); // A declaration is answered by the load worker that is loading; once no load is in progress, - // nothing waits on it. An informational denial was never an approval request. + // nothing waits on it. A one-time recursive-delete consent is a runtime prompt: its denial + // may be what aborted the load, so an ordinary failure keeps it actionable too. CHECK_FALSE(prompt_plugin_is_available(failed, AuditPromptKind::DeclaredPermissions)); - CHECK_FALSE(prompt_plugin_is_available(failed, AuditPromptKind::DeniedOperation)); + CHECK(prompt_plugin_is_available(failed, AuditPromptKind::RecursiveDeleteConsent)); // Explicit cancellation and unload discard the prompt instead: the queue removes its entry // and a request admitted after that discard must not become a stale dialog. @@ -1343,9 +1506,10 @@ class TrackedRequest(urllib.request.Request): struct Prompt { - std::string plugin; - std::string event; - std::vector targets; + std::string plugin; + std::string event; + std::vector targets; + std::vector entries; }; // One line per prompt, "event: target ...", so a failed check shows every prompt. @@ -1376,6 +1540,7 @@ struct AuditHarness ScopedTemporaryDir outside{"orca-plugin-audit-outside"}; std::vector prompts; std::function approve = [](const Prompt&) { return false; }; + std::function approve_recursive_delete = [](const Prompt&) { return false; }; AuditHarness() { @@ -1384,16 +1549,32 @@ struct AuditHarness audit.clear_current_capability(); audit.clear_audit_denial(); audit.clear_last_violation(); + PluginAuditManager::clear_recursive_delete_approvals_for_testing(); + PluginAuditManager::set_recursive_delete_approval_lifetime_for_testing(std::chrono::minutes(1)); + PluginAuditManager::set_recursive_delete_prompt_background_for_testing(false); + PluginAuditManager::set_recursive_delete_prompt_deferred_for_testing(false); PluginAuditManager::set_permission_prompt_for_testing( - [this](const std::string& event, const std::vector& targets) { - prompts.push_back({PluginAuditManager::instance().current_plugin(), event, targets}); + [this](const std::string& event, const std::vector& targets, + const std::vector& entries) { + prompts.push_back({PluginAuditManager::instance().current_plugin(), event, targets, entries}); return approve(prompts.back()); }); + PluginAuditManager::set_recursive_delete_prompt_for_testing( + [this](const std::string&, const std::string& target) { + prompts.push_back({PluginAuditManager::instance().current_plugin(), "shutil.rmtree", {target}, + {{target, ""}}}); + return approve_recursive_delete(prompts.back()); + }); } ~AuditHarness() { PluginAuditManager::set_permission_prompt_for_testing(nullptr); + PluginAuditManager::set_recursive_delete_prompt_for_testing(nullptr); + PluginAuditManager::set_recursive_delete_prompt_background_for_testing(false); + PluginAuditManager::set_recursive_delete_prompt_deferred_for_testing(false); + PluginAuditManager::clear_recursive_delete_approvals_for_testing(); + PluginAuditManager::set_recursive_delete_approval_lifetime_for_testing(std::chrono::minutes(1)); PluginManager::instance().shutdown(); } @@ -1682,21 +1863,22 @@ TEST_CASE("A freshly approved operation covers its nested events", "[audit][Pyth const char* prompts; const char* code; }; - // Each operation names targets no earlier one saved, so each is asked once. FsCreate and - // FsDelete grants are never saved, so those operations are asked every time. Only the - // expected prompts are approved, so a nested event left uncovered fails the operation. + // Each case starts with no saved grants, so its root event is asked once. A freshly approved + // create or delete saves the parent folder, so the stored grants are reset between cases. + // Only the expected prompts are approved, so a nested event left uncovered fails the + // operation. std::vector cases = { {"shutil.copytree", "shutil.copytree(TREE, os.path.join(OUTSIDE, 'copy'))"}, {"shutil.copyfile", "shutil.copyfile(APPROVED, os.path.join(OUTSIDE, 'copied.txt'))"}, {"shutil.move", "shutil.move(os.path.join(OUTSIDE, 'copied.txt'), os.path.join(OUTSIDE, 'moved.txt'))"}, {"shutil.copystat", "shutil.copystat(os.path.join(TREE, 'one', 'f.txt'), PRIVATE)"}, {"shutil.make_archive", "shutil.make_archive(os.path.join(OUTSIDE, 'archive'), 'zip', root_dir=TREE)"}, - {"shutil.unpack_archive", "shutil.unpack_archive(os.path.join(OUTSIDE, 'archive.zip'), os.path.join(OUTSIDE, 'unpacked'))"}, + {"shutil.unpack_archive", + "shutil.unpack_archive(os.path.join(OUTSIDE, 'archive.zip'), os.path.join(OUTSIDE, 'unpacked'))"}, {"pathlib.Path.glob", "list(pathlib.Path(TREE).glob('**/*'))"}, {"subprocess.Popen", "subprocess.run(TRUE_COMMAND, check=True)"}, {"tempfile.mkdtemp", "tempfile.mkdtemp(dir=OUTSIDE)"}, {"tempfile.mkstemp", "os.close(tempfile.mkstemp(dir=OUTSIDE)[0])"}, - {"shutil.rmtree", "shutil.rmtree(os.path.join(OUTSIDE, 'copy'))"}, // The host grant from connect() also authorizes targetless send() events. {"http.client.connect", "connection = http.client.HTTPConnection('127.0.0.1', PORT)\n" @@ -1713,6 +1895,9 @@ TEST_CASE("A freshly approved operation covers its nested events", "[audit][Pyth for (const Case& operation : cases) { INFO(operation.code); + // Dropping the grants from the previous case keeps its persisted create/delete parent + // folder from covering this one. + harness.save_permissions(PLUGIN, {}); const std::string expected = std::string(operation.prompts) + "\n"; harness.approve = [&expected](const Prompt& prompt) { return expected.find(prompt.event + "\n") != std::string::npos; @@ -1908,6 +2093,41 @@ except PermissionError as error: CHECK(mgr.audit_denial_pending()); } +TEST_CASE("A finalizer hardlink to an ungranted source is denied without prompting during frame release", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + PluginPermissions permissions = http_grants({python.str("URL_A")}); + harness.save_permissions(PLUGIN, permissions); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + python.exec(R"PY( +FINALIZER_LINK_SOURCE = os.path.join(OUTSIDE, "finalizer-link-source.txt") +with open(FINALIZER_LINK_SOURCE, "w") as f: + f.write("x") +FINALIZER_LINK_DEST = os.path.join(OUTSIDE, "finalizer-link-dest.txt") +finalizer_link_outcomes = [] + +class LinkTrackedRequest(urllib.request.Request): + def __del__(self): + finalizer_link_outcomes.append(attempt(lambda: os.link(FINALIZER_LINK_SOURCE, FINALIZER_LINK_DEST))) +)PY"); + + // The request is kept alive by the approved fetch's root frame. When the frame is released, its + // finalizer tries to hardlink a source that was never granted. Releasing frames runs finalizers + // where a modal cannot open, so the source check must fail closed without prompting. + python.run_as(PLUGIN, "fetch(LinkTrackedRequest(URL_A))"); + + CHECK(python.strings("finalizer_link_outcomes") == std::vector{"denied"}); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("FINALIZER_LINK_DEST")))); + CHECK_FALSE(mgr.audit_denial_pending()); +} + TEST_CASE("A nested audit scope does not see the outer scope's running operations", "[audit][Python]") { AuditHarness harness; @@ -2385,6 +2605,45 @@ forward_slash_outcome = attempt(lambda: open(FORWARD_SLASH_FILE).read()) CHECK_FALSE(fs::exists(outside / "not-created.txt")); } +TEST_CASE("A saved exact file grant covers the file's 8.3 alias without another prompt", "[audit][Python]") +{ +#ifndef _WIN32 + SKIP("Windows 8.3 short names exist only on Windows"); +#else + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + // No symlink is involved, so this check does not depend on the privilege to create one. The + // file name and the temp folder both need their long spelling, so the alias differs from the + // grant even where the volume names the temp root short. + python.exec(R"PY( +GRANTED_FILE = os.path.join(OUTSIDE, "short-name-granted-file.txt") +with open(GRANTED_FILE, "w") as f: + f.write("x") +)PY"); + + const fs::path file = python.str("GRANTED_FILE"); + const fs::path alias = short_name_alias(file); + if (alias.empty()) + SKIP("This volume does not expose an 8.3 alias for the granted file"); + + PluginPermissions permissions; + permissions.fs_read = {file.string()}; + harness.save_permissions(PLUGIN, permissions); + + python.globals["ALIAS_FILE"] = alias.string(); + python.run_as(PLUGIN, "alias_outcome = attempt(lambda: open(ALIAS_FILE).read())"); + + // The grant was saved under the long spelling; reading through the alias must not ask again. + CHECK(python.str("alias_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); +#endif +} + TEST_CASE("A saved exact file grant covers an equivalent spelling in a permission request", "[audit]") { AuditHarness harness; @@ -2480,6 +2739,122 @@ TEST_CASE("A relative wildcard permission request is shown and stored as an abso CHECK(describe(harness.prompts).empty()); } +TEST_CASE("A create or delete tree declaration is stored as an absolute subtree grant", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + const fs::path folder = harness.outside.path() / "declared"; + fs::create_directories(folder); + + std::vector prompted; + PluginAuditManager::set_permission_message_prompt_for_testing( + [&prompted](const std::string& message) { + prompted.push_back(message); + return true; + }); + + // "/*" asks for the folder and every folder below it. The prompt names, and the sidecar + // stores, the canonical absolute scope the grant actually covers. + PluginPermissions tree_create; + tree_create.fs_create = {(folder / "*").string()}; + CHECK(mgr.request_permissions(PLUGIN, tree_create)); + REQUIRE(prompted.size() == 1); + const std::vector saved_create = harness.saved_permissions(PLUGIN).fs_create; + REQUIRE(saved_create.size() == 1); + const fs::path saved_create_path(saved_create.front()); + CHECK(saved_create_path.filename() == "*"); + CHECK(fs::equivalent(saved_create_path.parent_path(), folder)); + CHECK(prompted.front().find(saved_create.front()) != std::string::npos); + + // The saved tree grant also covers a later literal request for the same folder. + PluginPermissions literal_create; + literal_create.fs_create = {folder.string()}; + CHECK(mgr.request_permissions(PLUGIN, literal_create)); + CHECK(prompted.size() == 1); + CHECK(harness.saved_permissions(PLUGIN).fs_create == saved_create); + + // Delete is an independent bucket with the same subtree syntax. + PluginPermissions tree_delete; + tree_delete.fs_delete = {(folder / "*").string()}; + CHECK(mgr.request_permissions(PLUGIN, tree_delete)); + REQUIRE(prompted.size() == 2); + const std::vector saved_delete = harness.saved_permissions(PLUGIN).fs_delete; + REQUIRE(saved_delete.size() == 1); + CHECK(fs::path(saved_delete.front()).filename() == "*"); + CHECK(fs::equivalent(fs::path(saved_delete.front()).parent_path(), folder)); + CHECK(harness.saved_permissions(PLUGIN).fs_create == saved_create); + + // A saved tree grant already covers a nested tree request, so it is neither prompted nor + // stored again. + const fs::path nested = folder / "nested"; + fs::create_directories(nested); + PluginPermissions nested_create; + nested_create.fs_create = {(nested / "*").string()}; + CHECK(mgr.request_permissions(PLUGIN, nested_create)); + CHECK(prompted.size() == 2); + CHECK(harness.saved_permissions(PLUGIN).fs_create == saved_create); + + // A wildcard that is not the final tree marker does not name a scope the prompt could show. + PluginPermissions pattern_delete; + pattern_delete.fs_delete = {(folder / "*.txt").string()}; + CHECK_FALSE(mgr.request_permissions(PLUGIN, pattern_delete)); + CHECK(prompted.size() == 2); + CHECK(harness.saved_permissions(PLUGIN).fs_delete == saved_delete); + + // The all-folders marker is only valid on its own. + PluginPermissions mixed; + mixed.fs_delete = {"*", folder.string()}; + CHECK_FALSE(mgr.request_permissions(PLUGIN, mixed)); + CHECK(prompted.size() == 2); + CHECK(harness.saved_permissions(PLUGIN).fs_delete == saved_delete); + + // Positive control: the one-element all-folders form is accepted and stored alone. + PluginPermissions full; + full.fs_delete = {"*"}; + CHECK(mgr.request_permissions(PLUGIN, full)); + const std::vector saved_full = harness.saved_permissions(PLUGIN).fs_delete; + REQUIRE(saved_full.size() == 1); + CHECK(saved_full.front() == "*"); + CHECK(prompted.size() == 3); + + PluginAuditManager::set_permission_message_prompt_for_testing(nullptr); +} + +#if !defined(_WIN32) +TEST_CASE("A tree declaration rooted at / discloses the subtree scope, not full access", "[audit]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + std::string shown; + PluginAuditManager::set_permission_message_prompt_for_testing( + [&shown](const std::string& message) { + shown = message; + return true; + }); + + // "/*" is the tree grant rooted at "/". It is a subtree scope, not the "*" all-folders marker. + PluginPermissions requested; + requested.fs_create = {"/*"}; + CHECK(mgr.request_permissions(PLUGIN, requested)); + CHECK(harness.saved_permissions(PLUGIN).fs_create == std::vector{"/*"}); + + // The prompt keeps the root and discloses its filesystem-wide scope. + CHECK(shown.find("/*") != std::string::npos); + CHECK(shown.find("entire filesystem, drive, or network share") != std::string::npos); + CHECK(shown.find("anywhere on this computer") == std::string::npos); + + PluginAuditManager::set_permission_message_prompt_for_testing(nullptr); +} +#endif + TEST_CASE("A threading permission request is prompted once and saved as a boolean", "[audit]") { AuditHarness harness; @@ -2837,6 +3212,8 @@ TEST_CASE("A permission mutation changes only the named entries and preserves th initial.capabilities = {{"Echo", false}, {"Other", true}}; initial.permissions.fs_read = {"/kept/read", "/removed/read"}; initial.permissions.fs_readwrite = {"/kept/write"}; + initial.permissions.fs_create = {"/kept/create", "/removed/create"}; + initial.permissions.fs_delete = {"/kept/delete", "/removed/delete"}; initial.permissions.network_http = {"https://kept.example"}; REQUIRE(write_install_state(plugin_dir, initial)); @@ -2846,12 +3223,17 @@ TEST_CASE("A permission mutation changes only the named entries and preserves th {PluginPermissionCategory::FsRead, "/added/read"}, // duplicate is collapsed {PluginPermissionCategory::FsRead, ""}, // empty values are skipped {PluginPermissionCategory::FsRead, "/removed/read"}, + {PluginPermissionCategory::FsCreate, "/added/create"}, + {PluginPermissionCategory::FsCreate, "/removed/create"}, + {PluginPermissionCategory::FsDelete, "/added/delete"}, {PluginPermissionCategory::NetworkSocket, "127.0.0.1:8080"}, }; mutation.remove = { {PluginPermissionCategory::FsRead, "/removed/read"}, {PluginPermissionCategory::FsRead, "/never/granted"}, {PluginPermissionCategory::FsRead, ""}, + {PluginPermissionCategory::FsCreate, "/removed/create"}, + {PluginPermissionCategory::FsDelete, "/removed/delete"}, {PluginPermissionCategory::Process, "/never/granted"}, }; @@ -2859,13 +3241,19 @@ TEST_CASE("A permission mutation changes only the named entries and preserves th REQUIRE(PluginManager::instance().mutate_plugin_permissions(PLUGIN, mutation, &applied)); // Removals run first, so a value named in both lists ends present; absent removals are ignored. const std::vector expected_fs_read{"/kept/read", "/added/read", "/removed/read"}; + const std::vector expected_fs_create{"/kept/create", "/added/create", "/removed/create"}; + const std::vector expected_fs_delete{"/kept/delete", "/added/delete"}; const std::vector expected_sockets{"127.0.0.1:8080"}; CHECK(applied.fs_read == expected_fs_read); + CHECK(applied.fs_create == expected_fs_create); + CHECK(applied.fs_delete == expected_fs_delete); CHECK(applied.network_socket == expected_sockets); PluginInstallState stored; REQUIRE(read_install_state(plugin_dir, stored)); CHECK(stored.permissions.fs_read == expected_fs_read); + CHECK(stored.permissions.fs_create == expected_fs_create); + CHECK(stored.permissions.fs_delete == expected_fs_delete); CHECK(stored.permissions.network_socket == expected_sockets); // Every grant the mutation did not name stays as it was. @@ -3042,6 +3430,1835 @@ reread_outcome = attempt(lambda: open(NESTED_FILE).read()) CHECK(describe(harness.prompts) == reread_prompt); } +TEST_CASE("Create and delete folder grants cover direct entries but not subfolders", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +GRANTED = os.path.realpath(os.path.join(OUTSIDE, "granted")) +SUBFOLDER = os.path.join(GRANTED, "sub") +os.makedirs(SUBFOLDER) +DELETE_FILE = os.path.join(GRANTED, "delete-me.txt") +with open(DELETE_FILE, "w") as f: + f.write("x") +NESTED_DELETE_FILE = os.path.join(SUBFOLDER, "delete-me-too.txt") +with open(NESTED_DELETE_FILE, "w") as f: + f.write("x") +NEW_DIR = os.path.join(GRANTED, "new-dir") +OTHER_DIR = os.path.join(GRANTED, "other-dir") +NESTED_NEW_DIR = os.path.join(SUBFOLDER, "new-dir") +)PY"); + + PluginPermissions permissions; + permissions.fs_create = {python.str("GRANTED")}; + permissions.fs_delete = {python.str("GRANTED")}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +create_outcome = attempt(lambda: os.mkdir(NEW_DIR)) +delete_outcome = attempt(lambda: os.remove(DELETE_FILE)) +nested_create_outcome = attempt(lambda: os.mkdir(NESTED_NEW_DIR)) +nested_delete_outcome = attempt(lambda: os.remove(NESTED_DELETE_FILE)) +)PY"); + + // The literal grant names the exact folder, so an operation directly inside it is covered; an + // operation in a child folder is not. The tree form below covers both. + CHECK(python.str("create_outcome") == "ok"); + CHECK(python.str("delete_outcome") == "ok"); + CHECK(python.str("nested_create_outcome") == "denied"); + CHECK(python.str("nested_delete_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("SUBFOLDER") + "\n" + + "os.remove: " + python.str("SUBFOLDER") + "\n"); + CHECK(fs::is_directory(fs::path(python.str("NEW_DIR")))); + CHECK(fs::exists(fs::path(python.str("NESTED_DELETE_FILE")))); + CHECK_FALSE(fs::exists(fs::path(python.str("NESTED_NEW_DIR")))); + + // Create and delete are independent buckets: a delete grant does not authorize a create in + // the same folder, and the reverse. + permissions.fs_create.clear(); + permissions.fs_delete = {python.str("GRANTED")}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +other_create_outcome = attempt(lambda: os.mkdir(OTHER_DIR)) +other_delete_outcome = attempt(lambda: os.rmdir(NEW_DIR)) +)PY"); + + CHECK(python.str("other_create_outcome") == "denied"); + CHECK(python.str("other_delete_outcome") == "ok"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("GRANTED") + "\n"); +} + +TEST_CASE("A create and delete tree grant covers direct entries and subfolders but not a sibling", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +GRANTED = os.path.realpath(os.path.join(OUTSIDE, "tree-granted")) +SIBLING = os.path.realpath(os.path.join(OUTSIDE, "tree-granted-sibling")) +SUBFOLDER = os.path.join(GRANTED, "sub") +os.makedirs(SUBFOLDER) +os.makedirs(SIBLING) +TREE_GRANT = GRANTED + os.sep + "*" +DIRECT_FILE = os.path.join(GRANTED, "direct.txt") +NESTED_FILE = os.path.join(SUBFOLDER, "nested.txt") +SIBLING_FILE = os.path.join(SIBLING, "sibling.txt") +for path in (DIRECT_FILE, NESTED_FILE, SIBLING_FILE): + with open(path, "w") as f: + f.write("x") +DIRECT_NEW = os.path.join(GRANTED, "direct-new") +NESTED_NEW = os.path.join(SUBFOLDER, "nested-new") +SIBLING_NEW = os.path.join(SIBLING, "sibling-new") +)PY"); + + // "/*" is a subtree grant, unlike the literal folder grant in the previous test. + PluginPermissions permissions; + permissions.fs_create = {python.str("TREE_GRANT")}; + permissions.fs_delete = {python.str("TREE_GRANT")}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +direct_create_outcome = attempt(lambda: os.mkdir(DIRECT_NEW)) +nested_create_outcome = attempt(lambda: os.mkdir(NESTED_NEW)) +direct_delete_outcome = attempt(lambda: os.remove(DIRECT_FILE)) +nested_delete_outcome = attempt(lambda: os.remove(NESTED_FILE)) +sibling_create_outcome = attempt(lambda: os.mkdir(SIBLING_NEW)) +sibling_delete_outcome = attempt(lambda: os.remove(SIBLING_FILE)) +)PY"); + + CHECK(python.str("direct_create_outcome") == "ok"); + CHECK(python.str("nested_create_outcome") == "ok"); + CHECK(python.str("direct_delete_outcome") == "ok"); + CHECK(python.str("nested_delete_outcome") == "ok"); + // A sibling whose name only shares the granted folder's text prefix is a different folder. + CHECK(python.str("sibling_create_outcome") == "denied"); + CHECK(python.str("sibling_delete_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("SIBLING") + "\n" + + "os.remove: " + python.str("SIBLING") + "\n"); + CHECK(fs::is_directory(fs::path(python.str("DIRECT_NEW")))); + CHECK(fs::is_directory(fs::path(python.str("NESTED_NEW")))); + CHECK_FALSE(fs::exists(fs::path(python.str("DIRECT_FILE")))); + CHECK_FALSE(fs::exists(fs::path(python.str("NESTED_FILE")))); + CHECK_FALSE(fs::exists(fs::path(python.str("SIBLING_NEW")))); + CHECK(fs::exists(fs::path(python.str("SIBLING_FILE")))); + + // Create and delete stay separate: dropping the create grant denies a later create in the + // same subtree while the delete grant keeps working. + permissions.fs_create.clear(); + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +cross_create_outcome = attempt(lambda: os.mkdir(os.path.join(GRANTED, "cross-new"))) +cross_delete_outcome = attempt(lambda: os.rmdir(NESTED_NEW)) +)PY"); + CHECK(python.str("cross_create_outcome") == "denied"); + CHECK(python.str("cross_delete_outcome") == "ok"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("GRANTED") + "\n"); +} + +TEST_CASE("A create and delete tree grant does not follow a symlink out of its root", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +GRANTED = os.path.realpath(os.path.join(OUTSIDE, "tree-link-granted")) +ESCAPE_TARGET = os.path.realpath(os.path.join(OUTSIDE, "tree-link-target")) +os.makedirs(GRANTED) +os.makedirs(ESCAPE_TARGET) +TREE_GRANT = GRANTED + os.sep + "*" +VICTIM = os.path.join(ESCAPE_TARGET, "victim.txt") +with open(VICTIM, "w") as f: + f.write("x") +LINK = os.path.join(GRANTED, "escape") +try: + os.symlink(ESCAPE_TARGET, LINK, target_is_directory=True) + SYMLINK_OK = True +except (OSError, NotImplementedError): + SYMLINK_OK = False +)PY"); + if (python.eval("SYMLINK_OK") != "True") + SKIP("Cannot create a directory symlink here"); + + PluginPermissions permissions; + permissions.fs_create = {python.str("TREE_GRANT")}; + permissions.fs_delete = {python.str("TREE_GRANT")}; + harness.save_permissions(PLUGIN, permissions); + + // The link is inside the granted tree, but the folder it resolves to is outside it. Creating + // or deleting through the link must be judged against that outside folder. + python.run_as(PLUGIN, R"PY( +escaped_create_outcome = attempt(lambda: os.mkdir(os.path.join(LINK, "new"))) +escaped_delete_outcome = attempt(lambda: os.remove(os.path.join(LINK, "victim.txt"))) +)PY"); + + CHECK(python.str("escaped_create_outcome") == "denied"); + CHECK(python.str("escaped_delete_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("ESCAPE_TARGET") + "\n" + + "os.remove: " + python.str("ESCAPE_TARGET") + "\n"); + CHECK(fs::exists(fs::path(python.str("VICTIM")))); + CHECK_FALSE(fs::exists(fs::path(python.str("ESCAPE_TARGET")) / "new")); + + // Removing the link itself acts on the link inside the granted folder, not on its target. + harness.prompts.clear(); + python.run_as(PLUGIN, "link_delete_outcome = attempt(lambda: os.remove(LINK))"); + CHECK(python.str("link_delete_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::is_symlink(fs::path(python.str("LINK")))); + CHECK(fs::exists(fs::path(python.str("VICTIM")))); +} + +#if !defined(_WIN32) +TEST_CASE("A create or delete target inside a folder literally named * fails closed without a tree grant", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +BASE = os.path.realpath(os.path.join(OUTSIDE, "star-parent")) +STAR = os.path.join(BASE, "*") +os.makedirs(STAR) +os.makedirs(os.path.join(BASE, "sibling")) +STAR_FILE = os.path.join(STAR, "kept.txt") +with open(STAR_FILE, "w") as f: + f.write("x") +STAR_NEW = os.path.join(STAR, "new") +SIBLING_NEW = os.path.join(BASE, "sibling", "new") +)PY"); + + // The parent folder is spelled "/.../*". Storing it as-is would be read back as a tree grant + // for the whole parent, so an approval here must fail closed instead. + harness.approve = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, "star_create_outcome = attempt(lambda: os.mkdir(STAR_NEW))"); + + CHECK(python.str("star_create_outcome") == "denied"); + CHECK_FALSE(fs::exists(fs::path(python.str("STAR_NEW")))); + CHECK(harness.saved_permissions(PLUGIN).fs_create.empty()); + + // Nothing was widened to the parent: an operation beside the literal "*" folder is still + // prompted and denied, and no tree grant for BASE was stored. + harness.prompts.clear(); + harness.approve = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "sibling_outcome = attempt(lambda: os.mkdir(SIBLING_NEW))"); + + CHECK(python.str("sibling_outcome") == "denied"); + CHECK_FALSE(fs::exists(fs::path(python.str("SIBLING_NEW")))); + CHECK(harness.saved_permissions(PLUGIN).fs_create.empty()); + + // Delete resolves the same parent folder and must not persist a tree grant either. + harness.prompts.clear(); + harness.approve = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, "star_delete_outcome = attempt(lambda: os.remove(STAR_FILE))"); + + CHECK(python.str("star_delete_outcome") == "denied"); + CHECK(fs::exists(fs::path(python.str("STAR_FILE")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); +} +#endif + +TEST_CASE("A full create and delete grant allows any folder but not a denied path", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +FIRST = os.path.join(OUTSIDE, "full-create") +os.makedirs(FIRST) +NESTED = os.path.join(TREE, "one", "full-create") +DELETE_FILES = [os.path.join(FIRST, "a.txt"), os.path.join(TREE, "two", "b.txt")] +for path in DELETE_FILES: + with open(path, "w") as f: + f.write("x") +DENIED_DIR = os.path.join(OUTSIDE, "secrets") +os.makedirs(DENIED_DIR) +DENIED_FILE = os.path.join(DENIED_DIR, "token.txt") +with open(DENIED_FILE, "w") as f: + f.write("x") +DENIED_NEW = os.path.join(DENIED_DIR, "new") +)PY"); + + // "*" is the stored form of "all folders", while a "/*" entry grants one subtree. + PluginPermissions permissions; + permissions.fs_create = {"*"}; + permissions.fs_delete = {"*"}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +create_outcome = attempt(lambda: os.mkdir(NESTED)) +delete_outcome = attempt(lambda: [os.remove(path) for path in DELETE_FILES]) +denied_create_outcome = attempt(lambda: os.mkdir(DENIED_NEW)) +denied_delete_outcome = attempt(lambda: os.remove(DENIED_FILE)) +)PY"); + + CHECK(python.str("create_outcome") == "ok"); + CHECK(python.str("delete_outcome") == "ok"); + CHECK(python.str("denied_create_outcome") == "denied"); + CHECK(python.str("denied_delete_outcome") == "denied"); + CHECK(describe(harness.prompts).empty()); + CHECK(fs::is_directory(fs::path(python.str("NESTED")))); + CHECK(fs::exists(fs::path(python.str("DENIED_FILE")))); + CHECK_FALSE(fs::exists(fs::path(python.str("DENIED_NEW")))); + + AuditViolation violation; + REQUIRE(PluginAuditManager::instance().last_violation(violation)); + CHECK(violation.reason == "denied path"); +} + +TEST_CASE("An approved create or delete prompt saves the parent folder and is not asked again", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +CREATE_ROOT = os.path.realpath(os.path.join(OUTSIDE, "approved-create")) +os.makedirs(CREATE_ROOT) +NESTED_FOLDER = os.path.join(CREATE_ROOT, "sub") +os.makedirs(NESTED_FOLDER) +FIRST_CREATE = os.path.join(CREATE_ROOT, "first") +SECOND_CREATE = os.path.join(CREATE_ROOT, "second") +NESTED_CREATE = os.path.join(NESTED_FOLDER, "nested") +DELETE_ROOT = os.path.realpath(os.path.join(OUTSIDE, "approved-delete")) +os.makedirs(DELETE_ROOT) +FIRST_DELETE = os.path.join(DELETE_ROOT, "one.txt") +SECOND_DELETE = os.path.join(DELETE_ROOT, "two.txt") +for path in (FIRST_DELETE, SECOND_DELETE): + with open(path, "w") as f: + f.write("x") +CROSS_CREATE = os.path.join(DELETE_ROOT, "cross") +)PY"); + + harness.approve = [](const Prompt& prompt) { return prompt.event == "os.mkdir"; }; + python.run_as(PLUGIN, "first_create_outcome = attempt(lambda: os.mkdir(FIRST_CREATE))"); + + CHECK(python.str("first_create_outcome") == "ok"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("CREATE_ROOT") + "\n"); + REQUIRE(harness.prompts.size() == 1); + // The prompt shows the triggering path, not only the folder the approval saves. + CHECK(harness.prompts.front().entries == + std::vector{ + {python.str("FIRST_CREATE"), python.str("CREATE_ROOT")}}); + PluginPermissions after_create = harness.saved_permissions(PLUGIN); + // The prompt approval is saved as the folder containing the target, not the target itself. + REQUIRE(after_create.fs_create.size() == 1); + CHECK(fs::equivalent(fs::path(after_create.fs_create.front()), fs::path(python.str("CREATE_ROOT")))); + CHECK(after_create.fs_delete.empty()); + + // The saved parent folder covers another operation directly inside it, without a prompt. + harness.prompts.clear(); + python.run_as(PLUGIN, "second_create_outcome = attempt(lambda: os.mkdir(SECOND_CREATE))"); + CHECK(python.str("second_create_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // A subfolder is a descendant, not the granted folder, so it still asks. + harness.approve = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "nested_create_outcome = attempt(lambda: os.mkdir(NESTED_CREATE))"); + CHECK(python.str("nested_create_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("NESTED_FOLDER") + "\n"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().entries == + std::vector{ + {python.str("NESTED_CREATE"), python.str("NESTED_FOLDER")}}); + const PluginPermissions after_denial = harness.saved_permissions(PLUGIN); + REQUIRE(after_denial.fs_create.size() == 1); + CHECK(fs::equivalent(fs::path(after_denial.fs_create.front()), fs::path(python.str("CREATE_ROOT")))); + + // Delete approval persists its own folder and leaves the create grant alone. + harness.prompts.clear(); + harness.approve = [](const Prompt& prompt) { return prompt.event == "os.remove"; }; + python.run_as(PLUGIN, "first_delete_outcome = attempt(lambda: os.remove(FIRST_DELETE))"); + CHECK(python.str("first_delete_outcome") == "ok"); + CHECK(describe(harness.prompts) == "os.remove: " + python.str("DELETE_ROOT") + "\n"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().entries == + std::vector{ + {python.str("FIRST_DELETE"), python.str("DELETE_ROOT")}}); + PluginPermissions after_delete = harness.saved_permissions(PLUGIN); + REQUIRE(after_delete.fs_delete.size() == 1); + CHECK(fs::equivalent(fs::path(after_delete.fs_delete.front()), fs::path(python.str("DELETE_ROOT")))); + REQUIRE(after_delete.fs_create.size() == 1); + CHECK(fs::equivalent(fs::path(after_delete.fs_create.front()), fs::path(python.str("CREATE_ROOT")))); + + harness.prompts.clear(); + python.run_as(PLUGIN, "second_delete_outcome = attempt(lambda: os.remove(SECOND_DELETE))"); + CHECK(python.str("second_delete_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // The delete grant does not authorize a create in the same folder. + harness.approve = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "cross_create_outcome = attempt(lambda: os.mkdir(CROSS_CREATE))"); + CHECK(python.str("cross_create_outcome") == "denied"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("DELETE_ROOT") + "\n"); + REQUIRE(harness.prompts.size() == 1); + // A delete grant in this folder does not cover the create target, so the prompt still shows + // the target and the folder a create grant would save. + CHECK(harness.prompts.front().entries == + std::vector{ + {python.str("CROSS_CREATE"), python.str("DELETE_ROOT")}}); +} + +TEST_CASE("A create prompt lists each target with its saved folder and states the exact grant scope", "[audit]") +{ + const std::string text = PluginAuditManager::format_create_delete_permission_prompt_for_testing( + AuditEventCategory::FsCreate, "PromptPlugin", + {{"/work/first.txt", "/work"}, {"/work/second.txt", "/work"}, {"/other/third.txt", "/other"}}); + + const std::string expected = + "Plugin \"PromptPlugin\" is requesting to create the following entries:\n" + "Target: /work/first.txt\n" + "Saved folder: /work\n" + "Target: /work/second.txt\n" + "Saved folder: /work\n" + "Target: /other/third.txt\n" + "Saved folder: /other\n" + "\n" + "If you approve, the folder shown with each target is saved as a grant for future operations. " + "Each grant covers creating entries directly inside its folder. It does not cover the subfolders inside that folder."; + CHECK(text == expected); +} + +TEST_CASE("A delete prompt names the target and the folder saved as its exact grant", "[audit]") +{ + const std::string text = PluginAuditManager::format_create_delete_permission_prompt_for_testing( + AuditEventCategory::FsDelete, "PromptPlugin", {{"/work/old.txt", "/work"}}); + + const std::string expected = + "Plugin \"PromptPlugin\" is requesting to delete the following entry:\n" + "Target: /work/old.txt\n" + "Saved folder: /work\n" + "\n" + "If you approve, the folder shown with this target is saved as a grant for future operations. " + "The grant covers deleting entries directly inside that folder. It does not cover the subfolders inside that folder."; + CHECK(text == expected); +} + +TEST_CASE("A create prompt shows the target and the canonical folder the approval will grant", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +REAL_FOLDER = os.path.realpath(os.path.join(OUTSIDE, "prompt-real")) +os.makedirs(REAL_FOLDER) +LINK = os.path.join(OUTSIDE, "prompt-link") +CREATED = os.path.join(REAL_FOLDER, "new") +RAW_CREATE = os.path.join(LINK, "new") +try: + os.symlink(REAL_FOLDER, LINK, target_is_directory=True) + SYMLINK_OK = True +except (OSError, NotImplementedError): + SYMLINK_OK = False +)PY"); + if (python.eval("SYMLINK_OK") != "True") + SKIP("Cannot create a directory symlink here"); + + harness.approve = [](const Prompt& prompt) { return prompt.event == "os.mkdir"; }; + python.run_as(PLUGIN, "outcome = attempt(lambda: os.mkdir(RAW_CREATE))"); + + CHECK(python.str("outcome") == "ok"); + // The user approved creating inside the symlink's target. Showing only the raw path would hide + // which folder is actually stored and granted, so the prompt shows both. + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == std::vector{python.str("REAL_FOLDER")}); + CHECK(harness.prompts.front().entries == + std::vector{ + {python.str("RAW_CREATE"), python.str("REAL_FOLDER")}}); + CHECK(harness.saved_permissions(PLUGIN).fs_create == std::vector{python.str("REAL_FOLDER")}); + CHECK(fs::is_directory(fs::path(python.str("CREATED")))); +} + +TEST_CASE("A relative create target is resolved against the working directory and disclosed absolutely", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RELATIVE_ROOT = os.path.realpath(os.path.join(OUTSIDE, "relative-root")) +os.makedirs(RELATIVE_ROOT) +RELATIVE_VICTIM = os.path.join(RELATIVE_ROOT, "victim.txt") +RELATIVE_SECOND_VICTIM = os.path.join(RELATIVE_ROOT, "victim2.txt") +for path in (RELATIVE_VICTIM, RELATIVE_SECOND_VICTIM): + with open(path, "w") as f: + f.write("x") +)PY"); + + harness.approve = [](const Prompt& prompt) { return prompt.event == "os.mkdir"; }; + python.run_as(PLUGIN, R"PY( +os.chdir(RELATIVE_ROOT) +try: + first_outcome = attempt(lambda: os.mkdir("direct")) +finally: + os.chdir(OUTSIDE) +)PY"); + + CHECK(python.str("first_outcome") == "ok"); + // A relative target is resolved when the event is judged, and the prompt shows both the + // relative spelling that triggered it and the absolute folder whose grant the approval stores. + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == std::vector{python.str("RELATIVE_ROOT")}); + CHECK(harness.prompts.front().entries == + std::vector{{"direct", python.str("RELATIVE_ROOT")}}); + CHECK(harness.saved_permissions(PLUGIN).fs_create == std::vector{python.str("RELATIVE_ROOT")}); + + // The saved absolute folder covers another relative operation in the same directory. + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +os.chdir(RELATIVE_ROOT) +try: + second_outcome = attempt(lambda: os.mkdir("second")) +finally: + os.chdir(OUTSIDE) +)PY"); + CHECK(python.str("second_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // A relative entry saved by hand never matches: its meaning would move with the working + // directory. The operation asks again for the canonical folder. + PluginPermissions relative_only; + relative_only.fs_create = {"relative-root"}; + harness.save_permissions(PLUGIN, relative_only); + harness.approve = [](const Prompt&) { return false; }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +os.chdir(RELATIVE_ROOT) +try: + third_outcome = attempt(lambda: os.mkdir("third")) +finally: + os.chdir(OUTSIDE) +)PY"); + CHECK(python.str("third_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == std::vector{python.str("RELATIVE_ROOT")}); + CHECK(harness.prompts.front().entries == + std::vector{{"third", python.str("RELATIVE_ROOT")}}); + + // Delete targets resolve the same way. A relative removal inside the granted folder is + // allowed without a prompt. + PluginPermissions delete_root; + delete_root.fs_delete = {python.str("RELATIVE_ROOT")}; + harness.save_permissions(PLUGIN, delete_root); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +os.chdir(RELATIVE_ROOT) +try: + relative_delete_outcome = attempt(lambda: os.remove("victim.txt")) +finally: + os.chdir(OUTSIDE) +)PY"); + CHECK(python.str("relative_delete_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + + // Without a grant the prompt names the resolved folder, not the relative spelling. + harness.save_permissions(PLUGIN, {}); + harness.approve = [](const Prompt&) { return false; }; + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +os.chdir(RELATIVE_ROOT) +try: + relative_delete_denied = attempt(lambda: os.remove("victim2.txt")) +finally: + os.chdir(OUTSIDE) +)PY"); + CHECK(python.str("relative_delete_denied") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == std::vector{python.str("RELATIVE_ROOT")}); + CHECK(harness.prompts.front().entries == + std::vector{{"victim2.txt", python.str("RELATIVE_ROOT")}}); +} + +TEST_CASE("A link create grant covers only the destination folder", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +SOURCE_FOLDER = os.path.realpath(os.path.join(OUTSIDE, "link-source")) +DEST_FOLDER = os.path.realpath(os.path.join(OUTSIDE, "link-dest")) +os.makedirs(SOURCE_FOLDER) +os.makedirs(DEST_FOLDER) +SOURCE_FILE = os.path.join(SOURCE_FOLDER, "source.txt") +with open(SOURCE_FILE, "w") as f: + f.write("x") +SYMLINK_DEST = os.path.join(DEST_FOLDER, "symlink.txt") +HARDLINK_DEST = os.path.join(DEST_FOLDER, "hardlink.txt") +SECOND_LINK = os.path.join(DEST_FOLDER, "second-link.txt") +try: + os.symlink(SOURCE_FILE, os.path.join(OUTSIDE, "probe-link")) + os.remove(os.path.join(OUTSIDE, "probe-link")) + SYMLINK_OK = True +except (OSError, NotImplementedError): + SYMLINK_OK = False +try: + os.link(SOURCE_FILE, os.path.join(OUTSIDE, "probe-hardlink")) + os.remove(os.path.join(OUTSIDE, "probe-hardlink")) + HARDLINK_OK = True +except (OSError, NotImplementedError): + HARDLINK_OK = False +)PY"); + if (python.eval("SYMLINK_OK") != "True" || python.eval("HARDLINK_OK") != "True") + SKIP("Symbolic or hard links are unavailable"); + + // Only the path being created is a create target; the source the link points at is not. A + // hardlink still needs read/write access to its source, so grant that separately to keep this + // test focused on the destination folder grant. + PluginPermissions source_access; + source_access.fs_readwrite = {python.str("SOURCE_FILE")}; + harness.save_permissions(PLUGIN, source_access); + harness.approve = [](const Prompt& prompt) { return prompt.event == "os.symlink" || prompt.event == "os.link"; }; + python.run_as(PLUGIN, R"PY( +symlink_outcome = attempt(lambda: os.symlink(SOURCE_FILE, SYMLINK_DEST)) +hardlink_outcome = attempt(lambda: os.link(SOURCE_FILE, HARDLINK_DEST)) +)PY"); + + CHECK(python.str("symlink_outcome") == "ok"); + CHECK(python.str("hardlink_outcome") == "ok"); + // The source a link points at is not a create target, so the prompt shows only the new entry + // and the folder the approval saves. + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().entries == + std::vector{ + {python.str("SYMLINK_DEST"), python.str("DEST_FOLDER")}}); + const PluginPermissions after_links = harness.saved_permissions(PLUGIN); + REQUIRE(after_links.fs_create.size() == 1); + CHECK(fs::equivalent(fs::path(after_links.fs_create.front()), fs::path(python.str("DEST_FOLDER")))); + CHECK(after_links.fs_readwrite == source_access.fs_readwrite); + + // The source folder alone does not authorize creating an entry in another folder. + PluginPermissions source_only; + source_only.fs_create = {python.str("SOURCE_FOLDER")}; + harness.save_permissions(PLUGIN, source_only); + harness.approve = [](const Prompt&) { return false; }; + harness.prompts.clear(); + python.run_as(PLUGIN, "second_outcome = attempt(lambda: os.symlink(SOURCE_FILE, SECOND_LINK))"); + + CHECK(python.str("second_outcome") == "denied"); + CHECK_FALSE(fs::exists(fs::path(python.str("SECOND_LINK")))); + CHECK(harness.saved_permissions(PLUGIN).fs_create == std::vector{python.str("SOURCE_FOLDER")}); +} + +TEST_CASE("A hardlink nested in an approved read/write root needs no extra prompt", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + const fs::path destination = harness.outside.path() / "hardlinked-copy"; + python.globals["HARDLINKED_COPY"] = destination.string(); + python.exec(R"PY( +try: + PROBE = os.path.join(OUTSIDE, "copytree-hardlink-probe.txt") + os.link(os.path.join(TREE, "one", "f.txt"), PROBE) + os.remove(PROBE) + COPY_HARDLINK_OK = True +except OSError: + COPY_HARDLINK_OK = False +)PY"); + if (python.eval("COPY_HARDLINK_OK") != "True") + SKIP("Hard links are unavailable here"); + + // copytree is the approved read/write root. os.link is called from its stdlib frames, so the + // hardlink source inside TREE must not need a separate read/write prompt. + harness.approve = [](const Prompt& prompt) { return prompt.event == "shutil.copytree"; }; + python.run_as(PLUGIN, "shutil.copytree(TREE, HARDLINKED_COPY, copy_function=os.link)"); + + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "shutil.copytree"); + const fs::path copied_file = destination / "one" / "f.txt"; + REQUIRE(fs::exists(copied_file)); + CHECK(fs::equivalent(copied_file, fs::path(python.str("TREE")) / "one" / "f.txt")); + CHECK(harness.saved_permissions(PLUGIN).fs_read.empty()); + const std::vector expected_readwrite{python.str("TREE"), destination.string()}; + CHECK(harness.saved_permissions(PLUGIN).fs_readwrite == expected_readwrite); +} + +TEST_CASE("A hardlink needs read/write permission for a source outside a writable root", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + python.globals["DATA_DIR"] = harness.data.dir.string(); + + python.exec(R"PY( +SOURCE = os.path.join(OUTSIDE, "hardlink-source.txt") +with open(SOURCE, "w") as f: + f.write("secret") +DATA_SOURCE = os.path.join(DATA_DIR, "hardlink-data-source.txt") +with open(DATA_SOURCE, "w") as f: + f.write("data") +DEST_DENIED = os.path.join(DATA_DIR, "hardlink-denied.txt") +DEST_READ_ONLY = os.path.join(DATA_DIR, "hardlink-read-only.txt") +DEST_GRANTED = os.path.join(DATA_DIR, "hardlink-granted.txt") +DEST_FROM_DATA_SOURCE = os.path.join(DATA_DIR, "hardlink-from-data-source.txt") +try: + PROBE = os.path.join(DATA_DIR, "hardlink-probe.txt") + os.link(SOURCE, PROBE) + os.remove(PROBE) + HARDLINK_OK = True +except OSError: + HARDLINK_OK = False +)PY"); + if (python.eval("HARDLINK_OK") != "True") + SKIP("Hard links are unavailable here"); + + // The destination sits inside data_dir(), an implicitly writable allowed root. That must not + // authorize writing through a hardlink to a source outside it. + python.run_as(PLUGIN, "denied_outcome = attempt(lambda: os.link(SOURCE, DEST_DENIED))"); + CHECK(python.str("denied_outcome") == "denied"); + CHECK_FALSE(fs::exists(fs::path(python.str("DEST_DENIED")))); + + // A read grant is not enough either: the hardlink still has to ask for write access to the + // source, and denying that prompt leaves the operation blocked. + PluginPermissions read_only; + read_only.fs_read = {python.str("SOURCE")}; + harness.save_permissions(PLUGIN, read_only); + harness.approve = [](const Prompt&) { return false; }; + harness.prompts.clear(); + python.run_as(PLUGIN, "read_only_outcome = attempt(lambda: os.link(SOURCE, DEST_READ_ONLY))"); + CHECK(python.str("read_only_outcome") == "denied"); + CHECK_FALSE(fs::exists(fs::path(python.str("DEST_READ_ONLY")))); + CHECK(describe(harness.prompts) == "os.link: " + python.str("SOURCE") + "\n"); + + // A read/write grant for the source makes the same link creation succeed without another + // prompt. + PluginPermissions read_write; + read_write.fs_readwrite = {python.str("SOURCE")}; + harness.save_permissions(PLUGIN, read_write); + harness.prompts.clear(); + python.run_as(PLUGIN, "granted_outcome = attempt(lambda: os.link(SOURCE, DEST_GRANTED))"); + CHECK(python.str("granted_outcome") == "ok"); + CHECK(fs::exists(fs::path(python.str("DEST_GRANTED")))); + CHECK(describe(harness.prompts).empty()); + + // A source inside the writable allowed root itself needs no separate grant: writing through + // the new name stays inside a folder the plugin may already write. + harness.save_permissions(PLUGIN, {}); + harness.prompts.clear(); + python.run_as(PLUGIN, "data_source_outcome = attempt(lambda: os.link(DATA_SOURCE, DEST_FROM_DATA_SOURCE))"); + CHECK(python.str("data_source_outcome") == "ok"); + CHECK(fs::exists(fs::path(python.str("DEST_FROM_DATA_SOURCE")))); + CHECK(describe(harness.prompts).empty()); +} + +TEST_CASE("A recursive delete needs one-time subtree consent instead of a direct folder grant", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_PARENT = os.path.realpath(os.path.join(OUTSIDE, "rmtree-parent")) +RMTREE_TARGET = os.path.join(RMTREE_PARENT, "sub") +os.makedirs(RMTREE_TARGET) +for name in ("a.txt", "b.txt"): + with open(os.path.join(RMTREE_TARGET, name), "w") as f: + f.write("x") +RMTREE_EXACT_TARGET = os.path.join(RMTREE_PARENT, "exact") +os.makedirs(RMTREE_EXACT_TARGET) +with open(os.path.join(RMTREE_EXACT_TARGET, "one.txt"), "w") as f: + f.write("x") +)PY"); + + // A grant naming the parent folder authorises deleting the direct entry "sub", not walking + // and deleting what is inside it. The recursive delete asks for subtree consent instead. + PluginPermissions permissions; + permissions.fs_delete = {python.str("RMTREE_PARENT")}; + harness.save_permissions(PLUGIN, permissions); + harness.approve_recursive_delete = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "denied_outcome = attempt(lambda: shutil.rmtree(RMTREE_TARGET))"); + + CHECK(python.str("denied_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "shutil.rmtree"); + CHECK(harness.prompts.front().targets == std::vector{python.str("RMTREE_TARGET")}); + // The prompt has no saved folder: recursive-delete consent is for this operation only. + CHECK(harness.prompts.front().entries == + std::vector{{python.str("RMTREE_TARGET"), ""}}); + CHECK(fs::is_directory(fs::path(python.str("RMTREE_TARGET")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete == std::vector{python.str("RMTREE_PARENT")}); + + // A grant naming the recursive target itself is also a direct folder grant, so it does not + // cover the subtree either. + harness.prompts.clear(); + permissions.fs_delete = {python.str("RMTREE_EXACT_TARGET")}; + harness.save_permissions(PLUGIN, permissions); + python.run_as(PLUGIN, "exact_outcome = attempt(lambda: shutil.rmtree(RMTREE_EXACT_TARGET))"); + CHECK(python.str("exact_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().targets == std::vector{python.str("RMTREE_EXACT_TARGET")}); + CHECK(fs::exists(fs::path(python.str("RMTREE_EXACT_TARGET")) / "one.txt")); + + // One-time consent lets this operation proceed, including its nested deletes, and stores + // nothing: the saved direct grant is unchanged. + harness.prompts.clear(); + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, "approved_outcome = attempt(lambda: shutil.rmtree(RMTREE_TARGET))"); + + CHECK(python.str("approved_outcome") == "ok"); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_TARGET")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete == std::vector{python.str("RMTREE_EXACT_TARGET")}); +} + +TEST_CASE("A saved delete tree grant covers a recursive delete without a prompt", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_TREE_ROOT = os.path.realpath(os.path.join(OUTSIDE, "rmtree-tree-grant")) +RMTREE_TREE_TARGET = os.path.join(RMTREE_TREE_ROOT, "sub") +os.makedirs(RMTREE_TREE_TARGET) +with open(os.path.join(RMTREE_TREE_TARGET, "a.txt"), "w") as f: + f.write("x") +RMTREE_FULL_TARGET = os.path.join(RMTREE_TREE_ROOT, "full") +os.makedirs(RMTREE_FULL_TARGET) +with open(os.path.join(RMTREE_FULL_TARGET, "a.txt"), "w") as f: + f.write("x") +RMTREE_SELF_GRANT = os.path.join(RMTREE_TREE_ROOT, "self-grant") +os.makedirs(RMTREE_SELF_GRANT) +with open(os.path.join(RMTREE_SELF_GRANT, "a.txt"), "w") as f: + f.write("x") +RMTREE_SELF_COVERED = os.path.join(RMTREE_TREE_ROOT, "self-covered") +os.makedirs(RMTREE_SELF_COVERED) +with open(os.path.join(RMTREE_SELF_COVERED, "a.txt"), "w") as f: + f.write("x") +)PY"); + + PluginPermissions permissions; + permissions.fs_delete = {python.str("RMTREE_TREE_ROOT") + "/*"}; + harness.save_permissions(PLUGIN, permissions); + python.run_as(PLUGIN, "tree_outcome = attempt(lambda: shutil.rmtree(RMTREE_TREE_TARGET))"); + + CHECK(python.str("tree_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_TREE_TARGET")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete == + std::vector{python.str("RMTREE_TREE_ROOT") + "/*"}); + + // Full delete access likewise covers the operation without a prompt. + permissions.fs_delete = {"*"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, "full_outcome = attempt(lambda: shutil.rmtree(RMTREE_FULL_TARGET))"); + CHECK(python.str("full_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_FULL_TARGET")))); + + // A tree grant rooted at the target itself covers its contents but not the final rmdir of + // the target: that entry lives in the parent folder. The grant must not be silently extended + // to remove the directory; consent is asked before the walk starts, so denial leaves the tree + // intact and approval lets the whole operation finish without a mid-walk prompt. + permissions.fs_delete = {python.str("RMTREE_SELF_GRANT") + "/*"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + harness.approve_recursive_delete = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "self_grant_denied = attempt(lambda: shutil.rmtree(RMTREE_SELF_GRANT))"); + CHECK(python.str("self_grant_denied") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "shutil.rmtree"); + CHECK(harness.prompts.front().targets == std::vector{python.str("RMTREE_SELF_GRANT")}); + CHECK(fs::exists(fs::path(python.str("RMTREE_SELF_GRANT")) / "a.txt")); + CHECK(harness.saved_permissions(PLUGIN).fs_delete == + std::vector{python.str("RMTREE_SELF_GRANT") + "/*"}); + + harness.prompts.clear(); + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, "self_grant_approved = attempt(lambda: shutil.rmtree(RMTREE_SELF_GRANT))"); + CHECK(python.str("self_grant_approved") == "ok"); + CHECK(harness.prompts.size() == 1); // only the pre-walk consent, no nested prompt + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_SELF_GRANT")))); + + // The same target-rooted tree grant plus a separate grant for the parent covers the root + // removal too, so the saved grants suffice without a prompt. + permissions.fs_delete = {python.str("RMTREE_SELF_COVERED") + "/*", python.str("RMTREE_TREE_ROOT")}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, "self_covered_outcome = attempt(lambda: shutil.rmtree(RMTREE_SELF_COVERED))"); + CHECK(python.str("self_covered_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_SELF_COVERED")))); +} + +TEST_CASE("Recursive delete consent is not persisted and does not follow a symlink out of the subtree", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_SCOPE_ROOT = os.path.realpath(os.path.join(OUTSIDE, "rmtree-scope-root")) +RMTREE_OUTSIDE = os.path.realpath(os.path.join(OUTSIDE, "rmtree-scope-outside")) +os.makedirs(RMTREE_SCOPE_ROOT) +os.makedirs(RMTREE_OUTSIDE) +RMTREE_OUTSIDE_FILE = os.path.join(RMTREE_OUTSIDE, "keep.txt") +with open(RMTREE_OUTSIDE_FILE, "w") as f: + f.write("x") +with open(os.path.join(RMTREE_SCOPE_ROOT, "delete.txt"), "w") as f: + f.write("x") +try: + os.symlink(RMTREE_OUTSIDE, os.path.join(RMTREE_SCOPE_ROOT, "alias"), target_is_directory=True) + RMTREE_SYMLINK_OK = True +except (OSError, NotImplementedError): + RMTREE_SYMLINK_OK = False +)PY"); + if (python.eval("RMTREE_SYMLINK_OK") != "True") + SKIP("Cannot create a directory symlink here"); + + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, "scope_outcome = attempt(lambda: shutil.rmtree(RMTREE_SCOPE_ROOT))"); + + CHECK(python.str("scope_outcome") == "ok"); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_SCOPE_ROOT")))); + // The symlink is an entry in the approved folder, not consent to follow it outside. + CHECK(fs::exists(fs::path(python.str("RMTREE_OUTSIDE_FILE")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); + + // Approval covers one operation only: the same target asks again instead of inheriting a + // remembered subtree grant. + python.exec("os.makedirs(RMTREE_SCOPE_ROOT)"); + harness.prompts.clear(); + harness.approve_recursive_delete = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "second_scope_outcome = attempt(lambda: shutil.rmtree(RMTREE_SCOPE_ROOT))"); + CHECK(python.str("second_scope_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "shutil.rmtree"); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); +} + +TEST_CASE("A recursive delete resolves a symlink/.. spelling using platform semantics", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + python.globals["DATA_DIR"] = harness.data.dir.string(); + + python.exec(R"PY( +RMTREE_ESCAPE_LINK = os.path.join(DATA_DIR, "orca-rmtree-bypass-%d" % os.getpid()) +if os.path.lexists(RMTREE_ESCAPE_LINK): + os.remove(RMTREE_ESCAPE_LINK) +RMTREE_ESCAPE_OUTSIDE = os.path.realpath(os.path.join(OUTSIDE, "rmtree-escape-outside")) +RMTREE_ESCAPE_DEEP = os.path.join(RMTREE_ESCAPE_OUTSIDE, "deep") +# The name the spelling folds to on Win32, where data_dir() is an implicit writable root and the +# delete is expected to run, and the folder POSIX reaches instead once the link is followed. Both +# are folders of their own, so a delete of either one cannot touch the data directory itself. +RMTREE_ESCAPE_NAME = "rmtree-escape-name" +RMTREE_ESCAPE_INSIDE = os.path.join(DATA_DIR, RMTREE_ESCAPE_NAME) +RMTREE_ESCAPE_TARGET = os.path.join(RMTREE_ESCAPE_OUTSIDE, RMTREE_ESCAPE_NAME) +os.makedirs(RMTREE_ESCAPE_DEEP) +os.makedirs(RMTREE_ESCAPE_INSIDE) +with open(os.path.join(RMTREE_ESCAPE_INSIDE, "inside.txt"), "w") as f: + f.write("x") +os.makedirs(RMTREE_ESCAPE_TARGET) +with open(os.path.join(RMTREE_ESCAPE_TARGET, "keep.txt"), "w") as f: + f.write("x") +try: + os.symlink(RMTREE_ESCAPE_DEEP, RMTREE_ESCAPE_LINK, target_is_directory=True) + RMTREE_ESCAPE_SYMLINK_OK = True +except (OSError, NotImplementedError): + RMTREE_ESCAPE_SYMLINK_OK = False +# Lexically this folds to DATA_DIR/, inside the implicit writable root. POSIX follows +# the link first, so there it names OUTSIDE/ instead. +RMTREE_ESCAPE_PATH = os.path.join(DATA_DIR, os.path.basename(RMTREE_ESCAPE_LINK), "..", RMTREE_ESCAPE_NAME) +)PY"); + if (python.eval("RMTREE_ESCAPE_SYMLINK_OK") != "True") + SKIP("Cannot create a directory symlink inside the data directory"); + + // On POSIX the link is followed before the + // step-up, so the target is outside the implicit root and the recursive delete must ask first; + // denied, it must leave both folders in place. Win32 expands the ".." lexically before the file + // system sees the path, so the same spelling stays inside the implicit writable root: the walk + // runs without a prompt and removes the isolated folder created for it above, never the link's + // destination. + harness.approve_recursive_delete = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "escape_outcome = attempt(lambda: shutil.rmtree(RMTREE_ESCAPE_PATH))"); + + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); + CHECK(fs::exists(fs::path(python.str("RMTREE_ESCAPE_TARGET")) / "keep.txt")); +#if defined(_WIN32) + CHECK(python.str("escape_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_ESCAPE_INSIDE")))); +#else + CHECK(python.str("escape_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "shutil.rmtree"); + CHECK(harness.prompts.front().targets == std::vector{python.str("RMTREE_ESCAPE_TARGET")}); + CHECK(fs::exists(fs::path(python.str("RMTREE_ESCAPE_INSIDE")) / "inside.txt")); +#endif + + python.exec("os.remove(RMTREE_ESCAPE_LINK)"); +} + +TEST_CASE("A recursive delete inside an implicit writable root removes symlink entries without prompts", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + python.globals["DATA_DIR"] = harness.data.dir.string(); + + python.exec(R"PY( +RMTREE_IMPLICIT_TREE = os.path.realpath(os.path.join(DATA_DIR, "rmtree-implicit")) +RMTREE_IMPLICIT_OUTSIDE = os.path.realpath(os.path.join(OUTSIDE, "rmtree-implicit-outside")) +os.makedirs(RMTREE_IMPLICIT_TREE) +os.makedirs(RMTREE_IMPLICIT_OUTSIDE) +RMTREE_IMPLICIT_KEEP = os.path.join(RMTREE_IMPLICIT_OUTSIDE, "keep.txt") +with open(RMTREE_IMPLICIT_KEEP, "w") as f: + f.write("x") +with open(os.path.join(RMTREE_IMPLICIT_TREE, "a.txt"), "w") as f: + f.write("x") +try: + os.symlink(RMTREE_IMPLICIT_OUTSIDE, os.path.join(RMTREE_IMPLICIT_TREE, "alias"), target_is_directory=True) + RMTREE_IMPLICIT_SYMLINK_OK = True +except (OSError, NotImplementedError): + RMTREE_IMPLICIT_SYMLINK_OK = False +)PY"); + if (python.eval("RMTREE_IMPLICIT_SYMLINK_OK") != "True") + SKIP("Cannot create a directory symlink here"); + + // data_dir() is an implicit writable root. The recursive delete needs no consent, and the + // fd-based reads plus the symlink entry must not interrupt or partially delete the walk. + python.run_as(PLUGIN, "implicit_outcome = attempt(lambda: shutil.rmtree(RMTREE_IMPLICIT_TREE))"); + + CHECK(python.str("implicit_outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_IMPLICIT_TREE")))); + CHECK(fs::exists(fs::path(python.str("RMTREE_IMPLICIT_KEEP")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); +} + +TEST_CASE("A recursive delete keeps protected paths blocked inside an approved subtree", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + seed_denied_keywords(); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + python.exec(R"PY( +RMTREE_PROTECTED_ROOT = os.path.realpath(os.path.join(OUTSIDE, "rmtree-protected-root")) +RMTREE_PROTECTED_DIR = os.path.join(RMTREE_PROTECTED_ROOT, "secrets") +os.makedirs(RMTREE_PROTECTED_DIR) +RMTREE_PROTECTED_FILE = os.path.join(RMTREE_PROTECTED_DIR, "token.txt") +with open(RMTREE_PROTECTED_FILE, "w") as f: + f.write("x") +with open(os.path.join(RMTREE_PROTECTED_ROOT, "ordinary.txt"), "w") as f: + f.write("x") +)PY"); + + // The subtree consent covers the folder, but the deny registry is checked before any + // operation coverage, so the protected entry stops the walk. + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, "protected_outcome = attempt(lambda: shutil.rmtree(RMTREE_PROTECTED_ROOT))"); + + CHECK(python.str("protected_outcome") == "denied"); + CHECK(fs::exists(fs::path(python.str("RMTREE_PROTECTED_FILE")))); + CHECK(fs::is_directory(fs::path(python.str("RMTREE_PROTECTED_DIR")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); + AuditViolation violation; + REQUIRE(mgr.last_violation(violation)); + CHECK(violation.reason == "denied path"); +} + +TEST_CASE("A delete is scoped by the entry, not by a final symlink's destination", "[audit]") +{ + ScopedTemporaryDir temp{"orca-plugin-audit-delete-scope"}; + const fs::path approved = temp.path() / "approved"; + const fs::path outside = temp.path() / "outside"; + fs::create_directories(approved / "sub"); + fs::create_directories(outside); + + boost::system::error_code ec; + fs::create_directory_symlink(approved, outside / "link_to_approved", ec); + if (ec) + SKIP("Cannot create a directory symlink here"); + + const std::string subtree = fs::weakly_canonical(approved).string(); + + // An entry below the subtree and the subtree root itself are covered. + CHECK(PluginAuditManager::delete_target_inside_subtree_for_testing((approved / "sub" / "a.txt").string(), subtree)); + CHECK(PluginAuditManager::delete_target_inside_subtree_for_testing(approved.string(), subtree)); + + // Deleting this link acts on the link entry in `outside`, even though its destination is the + // approved subtree. The destination must not authorise removing the outside entry. + CHECK_FALSE(PluginAuditManager::delete_target_inside_subtree_for_testing((outside / "link_to_approved").string(), + subtree)); + CHECK_FALSE(PluginAuditManager::delete_target_inside_subtree_for_testing(outside.string(), subtree)); + + // `link/..` is resolved by the platform, and the platforms differ. Win32 expands "." and ".." + // lexically, before the file system sees the path, so this spelling is the approved root itself + // and a link cannot carry the step-up out of the tree. POSIX follows the link first, so there it + // is `outside/approved`. The check must give the answer the delete reaches on that platform. + fs::create_directories(outside / "deep"); + fs::create_directories(outside / "approved"); + fs::create_directory_symlink(outside / "deep", temp.path() / "escape_link", ec); + REQUIRE_FALSE(ec); +#if defined(_WIN32) + CHECK(PluginAuditManager::delete_target_inside_subtree_for_testing( + (temp.path() / "escape_link" / ".." / "approved").string(), subtree)); +#else + CHECK_FALSE(PluginAuditManager::delete_target_inside_subtree_for_testing( + (temp.path() / "escape_link" / ".." / "approved").string(), subtree)); +#endif + + // Both readings of the same spelling name the approved root: POSIX reaches it through the link, + // Win32 by folding. It is covered either way. + fs::create_directories(temp.path() / "inside"); + fs::create_directory_symlink(temp.path() / "inside", temp.path() / "safe_link", ec); + REQUIRE_FALSE(ec); + CHECK(PluginAuditManager::delete_target_inside_subtree_for_testing( + (temp.path() / "safe_link" / ".." / "approved").string(), subtree)); + + // A final ".." names no entry of the subtree: POSIX refuses it as a final component, and Win32 + // folds it to the approved root's parent, which is outside. Either way it fails closed. + CHECK_FALSE(PluginAuditManager::delete_target_inside_subtree_for_testing((approved / "..").string(), subtree)); + + // A link inside the subtree is an entry inside it; deleting the link does not follow it out. + fs::create_directory_symlink(outside, approved / "link_to_outside", ec); + REQUIRE_FALSE(ec); + CHECK(PluginAuditManager::delete_target_inside_subtree_for_testing((approved / "link_to_outside").string(), subtree)); +} + +TEST_CASE("An implicit writable root contains a target whose tail does not exist yet", "[audit]") +{ +#ifndef _WIN32 + SKIP("Covers the Windows status errors for a missing path; POSIX reports it without an error"); +#else + ScopedTemporaryDir temp{"orca-plugin-audit-missing-tail"}; + const fs::path root = temp.path() / "root"; + const fs::path outside = temp.path() / "outside"; + fs::create_directories(root); + fs::create_directories(outside); + + PluginAuditManager& mgr = PluginAuditManager::instance(); + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(root); + + // Windows reports a missing path as a status error (ERROR_FILE_NOT_FOUND or + // ERROR_PATH_NOT_FOUND), not as a successful "does not exist" check, so the existing-prefix walk + // has to keep the missing tail as written instead of failing. No 8.3 alias is needed here. + CHECK(is_inside_allowed_root(root / "missing-leaf", root)); + CHECK(is_inside_allowed_root(root / "missing" / "nested" / "file.txt", root)); + CHECK(mgr.delete_target_inside_writable_allowed_root((root / "missing" / "nested" / "file.txt").string())); + + // A missing tail outside the root stays outside. + CHECK_FALSE(is_inside_allowed_root(outside / "missing-leaf", root)); + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root((outside / "missing" / "nested").string())); +#endif +} + +TEST_CASE("An implicit writable root matches a target spelled with the other 8.3 name form", "[audit]") +{ +#ifndef _WIN32 + SKIP("Windows 8.3 short names exist only on Windows"); +#else + ScopedTemporaryDir temp{"orca-plugin-audit-short-names"}; + const fs::path long_root = temp.path() / "OrcaAuditShortNameRoot"; + const fs::path long_sibling = temp.path() / "OrcaAuditShortNameSibling"; + const fs::path outside = temp.path() / "outside"; + fs::create_directories(long_root / "sub"); + fs::create_directories(long_sibling); + fs::create_directories(outside); + + // Python names a path in its long form (os.path.realpath() and os.scandir() both report long + // names), while the C++ side may hold the short spelling it was started with. Whether a machine + // spells its temp root short is environment-dependent, so build the alias here and skip when the + // volume offers none: there is nothing to compare in that case. + const fs::path short_root = short_name_alias(long_root); + if (short_root.empty()) + SKIP("This volume does not expose an 8.3 short name for the test folder"); + // An alias on an ancestor alone would not exercise the final-component comparison, so require + // the test folder itself to have its own alias. + if (short_root.filename() == long_root.filename()) + SKIP("The test folder has no 8.3 alias of its own on this volume"); + + PluginAuditManager& mgr = PluginAuditManager::instance(); + + SECTION("a root registered under its short name contains long-spelled targets") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(short_root); + + CHECK(mgr.delete_target_inside_writable_allowed_root((long_root / "sub").string())); + CHECK(mgr.delete_target_inside_writable_allowed_root(long_root.string())); + // The same folder spelled short throughout was already comparable before normalization; + // keep that working rather than trading one spelling pair for the other. + CHECK(mgr.delete_target_inside_writable_allowed_root(short_root.string())); + // The tail below an existing prefix has no short name of its own; the existing prefix must + // still match, so an rmtree target that does not exist yet is judged the same way. + CHECK(mgr.delete_target_inside_writable_allowed_root((long_root / "not-created-yet").string())); + CHECK(mgr.delete_target_inside_writable_allowed_root((long_root / "not-created-yet" / "file.txt").string())); + + // Outside stays outside, including a path that only shares the root's name prefix. + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root(outside.string())); + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root((outside / "not-created-yet").string())); + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root(long_sibling.string())); + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root( + (temp.path() / "OrcaAuditShortNameRoot-sibling").string())); + } + + SECTION("a root registered under its long name contains short-spelled targets") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(long_root); + + CHECK(mgr.delete_target_inside_writable_allowed_root((short_root / "sub").string())); + CHECK(mgr.delete_target_inside_writable_allowed_root(short_root.string())); + CHECK(mgr.delete_target_inside_writable_allowed_root((short_root / "not-created-yet").string())); + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root(short_name_alias(long_sibling).string())); + } + + SECTION("the final symlink entry is still judged by where the entry lives") + { + ScopedPluginAuditContext ctx("test_plugin", ""); + mgr.add_scoped_allowed_root(short_root); + + boost::system::error_code ec; + fs::create_directory_symlink(outside, long_root / "link_to_outside", ec); + if (ec) + SKIP("Cannot create a directory symlink here"); + fs::create_directory_symlink(long_root, outside / "link_to_root", ec); + REQUIRE_FALSE(ec); + + // Deleting the link acts on its entry inside the long-spelled root, not on the outside + // folder it points at, and the short root spelling does not change that. + CHECK(mgr.delete_target_inside_writable_allowed_root((long_root / "link_to_outside").string())); + // The reverse link lives outside, so its destination being the root does not make it + // implicit. + CHECK_FALSE(mgr.delete_target_inside_writable_allowed_root((outside / "link_to_root").string())); + } +#endif +} + +TEST_CASE("An asynchronous recursive delete approval is single-use and bound to its plugin and target", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + const std::string other_plugin = "OtherAuditPlugin"; + harness.add_plugin(PLUGIN); + harness.add_plugin(other_plugin); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_ASYNC_A = os.path.realpath(os.path.join(OUTSIDE, "rmtree-async-a")) +RMTREE_ASYNC_B = os.path.realpath(os.path.join(OUTSIDE, "rmtree-async-b")) +for root in (RMTREE_ASYNC_A, RMTREE_ASYNC_B): + os.makedirs(root) + with open(os.path.join(root, "a.txt"), "w") as f: + f.write("x") +)PY"); + + // The posted prompt is answered Yes, but the attempt that raised it was already denied. + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + PluginAuditManager::set_recursive_delete_prompt_background_for_testing(true); + python.run_as(PLUGIN, "first_outcome = attempt(lambda: shutil.rmtree(RMTREE_ASYNC_A))"); + + CHECK(python.str("first_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().plugin == PLUGIN); + CHECK(harness.prompts.front().event == "shutil.rmtree"); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 1); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); + CHECK(fs::is_directory(fs::path(python.str("RMTREE_ASYNC_A")))); + + // The first retry consumes the approval and proceeds without another prompt. + python.run_as(PLUGIN, "retry_outcome = attempt(lambda: shutil.rmtree(RMTREE_ASYNC_A))"); + CHECK(python.str("retry_outcome") == "ok"); + CHECK(harness.prompts.size() == 1); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 0); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_ASYNC_A")))); + + // The approval is single use: a second recursive delete of the same folder asks again. + python.exec("os.makedirs(RMTREE_ASYNC_A)"); + python.run_as(PLUGIN, "second_outcome = attempt(lambda: shutil.rmtree(RMTREE_ASYNC_A))"); + CHECK(python.str("second_outcome") == "denied"); + CHECK(harness.prompts.size() == 2); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 1); + + // A different target cannot spend that approval. + python.run_as(PLUGIN, "other_target_outcome = attempt(lambda: shutil.rmtree(RMTREE_ASYNC_B))"); + CHECK(python.str("other_target_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 3); + CHECK(harness.prompts.back().targets == std::vector{python.str("RMTREE_ASYNC_B")}); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 2); + + // Another plugin cannot spend this plugin's pending approval. + python.run_as(other_plugin, "other_plugin_outcome = attempt(lambda: shutil.rmtree(RMTREE_ASYNC_B))"); + CHECK(python.str("other_plugin_outcome") == "denied"); + REQUIRE(harness.prompts.size() == 4); + CHECK(harness.prompts.back().plugin == other_plugin); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 3); + + // The original plugin still has its own approval for this target and can consume it. + python.run_as(PLUGIN, "own_retry_outcome = attempt(lambda: shutil.rmtree(RMTREE_ASYNC_B))"); + CHECK(python.str("own_retry_outcome") == "ok"); + CHECK(harness.prompts.size() == 4); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 2); +} + +TEST_CASE("A pending recursive delete prompt is not posted twice for the same plugin and target", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_DEDUP_ROOT = os.path.realpath(os.path.join(OUTSIDE, "rmtree-dedup")) +os.makedirs(RMTREE_DEDUP_ROOT) +with open(os.path.join(RMTREE_DEDUP_ROOT, "a.txt"), "w") as f: + f.write("x") +)PY"); + + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + PluginAuditManager::set_recursive_delete_prompt_background_for_testing(true); + PluginAuditManager::set_recursive_delete_prompt_deferred_for_testing(true); + const std::uint64_t generation = PluginAuditManager::recursive_delete_generation_for_testing(PLUGIN); + python.run_as(PLUGIN, "first_outcome = attempt(lambda: shutil.rmtree(RMTREE_DEDUP_ROOT))"); + CHECK(python.str("first_outcome") == "denied"); + CHECK(harness.prompts.size() == 1); + CHECK(PluginAuditManager::pending_recursive_delete_prompts_for_testing() == 1); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 0); + + // The dialog is still open, so a retry loop must not queue another modal for the same target. + python.run_as(PLUGIN, "second_outcome = attempt(lambda: shutil.rmtree(RMTREE_DEDUP_ROOT))"); + CHECK(python.str("second_outcome") == "denied"); + CHECK(harness.prompts.size() == 1); + CHECK(PluginAuditManager::pending_recursive_delete_prompts_for_testing() == 1); + + // Answering the posted prompt stores the single retry approval and releases the dedup key. + PluginAuditManager::answer_recursive_delete_prompt_for_testing(PLUGIN, python.str("RMTREE_DEDUP_ROOT"), true, + generation); + CHECK(PluginAuditManager::pending_recursive_delete_prompts_for_testing() == 0); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 1); + + python.run_as(PLUGIN, "retry_outcome = attempt(lambda: shutil.rmtree(RMTREE_DEDUP_ROOT))"); + CHECK(python.str("retry_outcome") == "ok"); + CHECK(harness.prompts.size() == 1); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 0); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_DEDUP_ROOT")))); +} + +TEST_CASE("The pending recursive delete prompt store rejects new prompts at capacity", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_CAP_ROOTS = [] +for index in range(17): + root = os.path.realpath(os.path.join(OUTSIDE, "rmtree-cap-%d" % index)) + os.makedirs(root) + with open(os.path.join(root, "a.txt"), "w") as f: + f.write("x") + RMTREE_CAP_ROOTS.append(root) +RMTREE_CAP_OUTCOMES = [] +)PY"); + + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + PluginAuditManager::set_recursive_delete_prompt_background_for_testing(true); + PluginAuditManager::set_recursive_delete_prompt_deferred_for_testing(true); + const std::uint64_t generation = PluginAuditManager::recursive_delete_generation_for_testing(PLUGIN); + python.run_as(PLUGIN, R"PY( +for root in RMTREE_CAP_ROOTS: + RMTREE_CAP_OUTCOMES.append(attempt(lambda root=root: shutil.rmtree(root))) +)PY"); + + CHECK(python.strings("RMTREE_CAP_OUTCOMES") == std::vector(17, "denied")); + // The first sixteen queue dialogs; the seventeenth is rejected rather than evicting a key + // whose dialog is already queued. That keeps the dedup set bounded and prevents unlimited + // dialogs from repeated distinct targets. + CHECK(harness.prompts.size() == 16); + CHECK(PluginAuditManager::pending_recursive_delete_prompts_for_testing() == 16); + + // Answering one releases its key and allows that target's retry. + PluginAuditManager::answer_recursive_delete_prompt_for_testing( + PLUGIN, python.eval("RMTREE_CAP_ROOTS[0]"), true, generation); + CHECK(PluginAuditManager::pending_recursive_delete_prompts_for_testing() == 15); + python.run_as(PLUGIN, "cap_retry_outcome = attempt(lambda: shutil.rmtree(RMTREE_CAP_ROOTS[0]))"); + CHECK(python.str("cap_retry_outcome") == "ok"); + CHECK_FALSE(fs::exists(fs::path(python.eval("RMTREE_CAP_ROOTS[0]")))); +} + +TEST_CASE("Revoking permissions invalidates recursive delete approvals and posted prompt tokens", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_REVOKE_A = os.path.realpath(os.path.join(OUTSIDE, "rmtree-revoke-a")) +RMTREE_REVOKE_B = os.path.realpath(os.path.join(OUTSIDE, "rmtree-revoke-b")) +for root in (RMTREE_REVOKE_A, RMTREE_REVOKE_B): + os.makedirs(root) + with open(os.path.join(root, "a.txt"), "w") as f: + f.write("x") +)PY"); + + PluginAuditManager::set_recursive_delete_prompt_background_for_testing(true); + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, "approval_outcome = attempt(lambda: shutil.rmtree(RMTREE_REVOKE_A))"); + CHECK(python.str("approval_outcome") == "denied"); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 1); + + PluginAuditManager::set_recursive_delete_prompt_deferred_for_testing(true); + python.run_as(PLUGIN, "pending_outcome = attempt(lambda: shutil.rmtree(RMTREE_REVOKE_B))"); + CHECK(python.str("pending_outcome") == "denied"); + CHECK(PluginAuditManager::pending_recursive_delete_prompts_for_testing() == 1); + const std::uint64_t stale_generation = PluginAuditManager::recursive_delete_generation_for_testing(PLUGIN); + const std::size_t prompts_before = harness.prompts.size(); + + PluginAuditManager::instance().invalidate_recursive_delete_state(PLUGIN); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 0); + CHECK(PluginAuditManager::pending_recursive_delete_prompts_for_testing() == 0); + + // A callback from the old dialog generation must not recreate an approval. + PluginAuditManager::answer_recursive_delete_prompt_for_testing(PLUGIN, python.str("RMTREE_REVOKE_B"), true, + stale_generation); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 0); + + // The old approval for A is gone too; the retry is denied and prompts again. + PluginAuditManager::set_recursive_delete_prompt_deferred_for_testing(false); + harness.approve_recursive_delete = [](const Prompt&) { return false; }; + python.run_as(PLUGIN, "revoked_retry_outcome = attempt(lambda: shutil.rmtree(RMTREE_REVOKE_A))"); + CHECK(python.str("revoked_retry_outcome") == "denied"); + CHECK(harness.prompts.size() == prompts_before + 1); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 0); + CHECK(fs::exists(fs::path(python.str("RMTREE_REVOKE_A")))); +} + +TEST_CASE("An expired recursive delete approval is not reused", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +RMTREE_EXPIRED_ROOT = os.path.realpath(os.path.join(OUTSIDE, "rmtree-expired")) +os.makedirs(RMTREE_EXPIRED_ROOT) +with open(os.path.join(RMTREE_EXPIRED_ROOT, "a.txt"), "w") as f: + f.write("x") +)PY"); + + // A negative lifetime makes the approval expired as soon as it is stored, so the retry must + // prompt again instead of proceeding. + PluginAuditManager::set_recursive_delete_approval_lifetime_for_testing(std::chrono::milliseconds(-1)); + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + PluginAuditManager::set_recursive_delete_prompt_background_for_testing(true); + python.run_as(PLUGIN, "first_outcome = attempt(lambda: shutil.rmtree(RMTREE_EXPIRED_ROOT))"); + CHECK(python.str("first_outcome") == "denied"); + CHECK(PluginAuditManager::pending_recursive_delete_approvals_for_testing() == 0); + + python.run_as(PLUGIN, "retry_outcome = attempt(lambda: shutil.rmtree(RMTREE_EXPIRED_ROOT))"); + CHECK(python.str("retry_outcome") == "denied"); + CHECK(harness.prompts.size() == 2); + CHECK(fs::is_directory(fs::path(python.str("RMTREE_EXPIRED_ROOT")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); +} + +TEST_CASE("A recursive delete prompt shows the subtree and states the consent is one-time", "[audit]") +{ + const std::string text = + PluginAuditManager::format_recursive_delete_permission_prompt_for_testing("PromptPlugin", "/work/tree"); + + const std::string expected = + "Plugin \"PromptPlugin\" is requesting to recursively delete the following folder:\n" + "/work/tree\n" + "\n" + "Approval covers deleting the entries in this folder and everything inside it while this operation runs. " + "It is not saved as a permission and cannot be reused for another operation. Protected paths stay blocked."; + CHECK(text == expected); + + // A posted prompt can only be answered for a later retry, so it must not claim the current + // operation will proceed, and it must name the short lifetime of that retry approval. + const std::string background = + PluginAuditManager::format_recursive_delete_permission_prompt_for_testing("PromptPlugin", "/work/tree", false, true); + const std::string expected_background = + "Plugin \"PromptPlugin\" is requesting to recursively delete the following folder:\n" + "/work/tree\n" + "\n" + "Approval covers deleting the entries in this folder and everything inside it, and applies to the next " + "matching attempt within one minute after you approve. The current attempt has already been denied. It is " + "not saved as a permission and cannot be reused for another operation. Protected paths stay blocked."; + CHECK(background == expected_background); + + // A filesystem, drive, or network share root gets an explicit warning about its scope. + const std::string root = PluginAuditManager::format_recursive_delete_permission_prompt_for_testing( + "PromptPlugin", "/", /*root_scope=*/true, /*background=*/false); + const std::string expected_root = + "Plugin \"PromptPlugin\" is requesting to recursively delete the following folder:\n" + "/\n" + "\n" + "This target is a filesystem, drive, or network share root. Approval covers that entire filesystem, drive, " + "or network share while this operation runs. It is not saved as a permission and cannot be reused for " + "another operation. Protected paths stay blocked."; + CHECK(root == expected_root); +} + +TEST_CASE("A trailing symlink is judged by its containing folder, not its target", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +LINK_PARENT = os.path.realpath(os.path.join(OUTSIDE, "link-parent")) +LINK_TARGET = os.path.realpath(os.path.join(OUTSIDE, "link-target")) +os.makedirs(LINK_PARENT) +os.makedirs(LINK_TARGET) +TARGET_FILE = os.path.join(LINK_TARGET, "target.txt") +with open(TARGET_FILE, "w") as f: + f.write("x") +LINK = os.path.join(LINK_PARENT, "alias.txt") +DANGLING = os.path.join(LINK_PARENT, "missing-link.txt") +try: + os.symlink(TARGET_FILE, LINK) + os.symlink(os.path.join(LINK_TARGET, "missing.txt"), DANGLING) + SYMLINKS_OK = True +except (OSError, NotImplementedError): + SYMLINKS_OK = False +)PY"); + if (python.eval("SYMLINKS_OK") != "True") + SKIP("Cannot create symbolic links here"); + + // Deleting a link acts on the link in LINK_PARENT, never on what it points at. + PluginPermissions permissions; + permissions.fs_delete = {python.str("LINK_TARGET")}; + harness.save_permissions(PLUGIN, permissions); + python.run_as(PLUGIN, R"PY( +target_folder_outcome = attempt(lambda: os.remove(LINK)) +dangling_target_folder_outcome = attempt(lambda: os.remove(DANGLING)) +)PY"); + + CHECK(python.str("target_folder_outcome") == "denied"); + CHECK(python.str("dangling_target_folder_outcome") == "denied"); + CHECK(fs::is_symlink(fs::path(python.str("LINK")))); + CHECK(fs::is_symlink(fs::path(python.str("DANGLING")))); + CHECK(fs::exists(fs::path(python.str("TARGET_FILE")))); + + // Granting the containing folder allows deleting the links themselves, without touching the + // link target or creating the dangling link's missing destination. + permissions.fs_delete = {python.str("LINK_PARENT")}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +link_outcome = attempt(lambda: os.remove(LINK)) +dangling_link_outcome = attempt(lambda: os.remove(DANGLING)) +)PY"); + + CHECK(python.str("link_outcome") == "ok"); + CHECK(python.str("dangling_link_outcome") == "ok"); + CHECK_FALSE(fs::is_symlink(fs::path(python.str("LINK")))); + CHECK_FALSE(fs::is_symlink(fs::path(python.str("DANGLING")))); + CHECK(fs::exists(fs::path(python.str("TARGET_FILE")))); + CHECK_FALSE(fs::exists(fs::path(python.str("LINK_TARGET")) / "missing.txt")); +} + +#if !defined(_WIN32) && (defined(__linux__) || defined(__APPLE__)) +TEST_CASE("A non-default dir_fd is checked against the folder it actually names", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + PluginAuditManager& mgr = PluginAuditManager::instance(); + + python.exec(R"PY( +FD_GRANTED = os.path.realpath(os.path.join(OUTSIDE, "fd-granted")) +FD_TARGET = os.path.realpath(os.path.join(OUTSIDE, "fd-target")) +FD_DENIED = os.path.join(OUTSIDE, "secrets") +os.makedirs(FD_GRANTED) +os.makedirs(FD_TARGET) +os.makedirs(FD_DENIED) +FD_VICTIM = os.path.join(FD_TARGET, "victim.txt") +with open(FD_VICTIM, "w") as f: + f.write("x") +# Open the descriptors before entering any plugin audit scope: os.open itself is an +# FsRead/FsReadWrite audited event and must not fail the test before the descriptor is used. +FD_TARGET_FD = os.open(FD_TARGET, os.O_RDONLY) +FD_DENIED_FD = os.open(FD_DENIED, os.O_RDONLY) +)PY"); + + // The working directory is granted, but the operations happen in FD_TARGET through dir_fd. + // Resolving the relative path against the working directory would authorize or deny the + // wrong folder, so the hook must resolve the descriptor first. + PluginPermissions permissions; + permissions.fs_create = {python.str("FD_GRANTED")}; + permissions.fs_delete = {python.str("FD_GRANTED")}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +os.chdir(FD_GRANTED) +try: + plain_outcome = attempt(lambda: os.mkdir("plain")) + prompted_create = attempt(lambda: os.mkdir("child", dir_fd=FD_TARGET_FD)) + prompted_delete = attempt(lambda: os.remove("victim.txt", dir_fd=FD_TARGET_FD)) +finally: + os.chdir(OUTSIDE) +)PY"); + + // A default dir_fd must still be allowed: the audit arguments include the mode, which must + // not be mistaken for a descriptor. + CHECK(python.str("plain_outcome") == "ok"); + CHECK(fs::is_directory(fs::path(python.str("FD_GRANTED")) / "plain")); + // Without a grant for FD_TARGET, the prompt names that actual folder and denial leaves both + // folders untouched. + CHECK(python.str("prompted_create") == "denied"); + CHECK(python.str("prompted_delete") == "denied"); + CHECK(describe(harness.prompts) == "os.mkdir: " + python.str("FD_TARGET") + "\n" + + "os.remove: " + python.str("FD_TARGET") + "\n"); + CHECK_FALSE(fs::exists(fs::path(python.str("FD_TARGET")) / "child")); + CHECK(fs::exists(fs::path(python.str("FD_VICTIM")))); + + // A grant naming the resolved folder covers the operations. + permissions.fs_create = {python.str("FD_TARGET")}; + permissions.fs_delete = {python.str("FD_TARGET")}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +os.chdir(FD_GRANTED) +try: + granted_create = attempt(lambda: os.mkdir("child", dir_fd=FD_TARGET_FD)) + granted_delete = attempt(lambda: os.remove("victim.txt", dir_fd=FD_TARGET_FD)) + granted_rmdir = attempt(lambda: os.rmdir("child", dir_fd=FD_TARGET_FD)) +finally: + os.chdir(OUTSIDE) +)PY"); + CHECK(python.str("granted_create") == "ok"); + CHECK(python.str("granted_delete") == "ok"); + CHECK(python.str("granted_rmdir") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("FD_TARGET")) / "child")); + CHECK_FALSE(fs::exists(fs::path(python.str("FD_VICTIM")))); + + // The resolved target still goes through the deny registry before any folder grant applies. + permissions.fs_create = {"*"}; + harness.save_permissions(PLUGIN, permissions); + harness.prompts.clear(); + python.run_as(PLUGIN, R"PY( +os.chdir(FD_GRANTED) +try: + denied_create = attempt(lambda: os.mkdir("child", dir_fd=FD_DENIED_FD)) +finally: + os.chdir(OUTSIDE) +)PY"); + CHECK(python.str("denied_create") == "denied"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("FD_DENIED")) / "child")); + python.exec("os.close(FD_TARGET_FD)\nos.close(FD_DENIED_FD)"); + AuditViolation violation; + REQUIRE(mgr.last_violation(violation)); + CHECK(violation.reason == "denied path"); +} + +TEST_CASE("A dir_fd rmtree succeeds when full access allows the resolved folder", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +import inspect +RMTREE_DIR_FD_SUPPORTED = "dir_fd" in inspect.signature(shutil.rmtree).parameters +RMTREE_PARENT = os.path.join(OUTSIDE, "rmtree-fd-parent") +RMTREE_TREE = os.path.join(RMTREE_PARENT, "tree") +os.makedirs(RMTREE_TREE) +for name in ("a.txt", "b.txt"): + with open(os.path.join(RMTREE_TREE, name), "w") as f: + f.write("x") +# Open outside the plugin scope: os.open is audited and would otherwise need a read grant. +RMTREE_FD = os.open(RMTREE_PARENT, os.O_RDONLY) +)PY"); + if (python.eval("RMTREE_DIR_FD_SUPPORTED") != "True") + SKIP("This Python's shutil.rmtree has no dir_fd parameter"); + + // Full access is the "always allowed" counterpart: descriptor resolution must not turn an + // otherwise authorized recursive delete into a denial. + PluginPermissions permissions; + permissions.full_access = true; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +outcome = attempt(lambda: shutil.rmtree("tree", dir_fd=RMTREE_FD)) +)PY"); + + CHECK(python.str("outcome") == "ok"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_TREE")))); + python.exec("os.close(RMTREE_FD)"); +} +TEST_CASE("A dir_fd recursive delete resolves the target before asking for consent", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +import inspect +RMTREE_CONSENT_DIR_FD_SUPPORTED = "dir_fd" in inspect.signature(shutil.rmtree).parameters +RMTREE_CONSENT_PARENT = os.path.realpath(os.path.join(OUTSIDE, "rmtree-consent-fd-parent")) +RMTREE_CONSENT_TREE = os.path.join(RMTREE_CONSENT_PARENT, "tree") +os.makedirs(RMTREE_CONSENT_TREE) +with open(os.path.join(RMTREE_CONSENT_TREE, "a.txt"), "w") as f: + f.write("x") +RMTREE_CONSENT_FD = os.open(RMTREE_CONSENT_PARENT, os.O_RDONLY) +)PY"); + if (python.eval("RMTREE_CONSENT_DIR_FD_SUPPORTED") != "True") + SKIP("This Python's shutil.rmtree has no dir_fd parameter"); + + // Without a grant, the resolved folder is what the consent prompt shows and approves. The + // operation must also be able to finish: rmtree's fd-based reads and nested deletes run inside + // the approved subtree. + harness.approve_recursive_delete = [](const Prompt&) { return true; }; + python.run_as(PLUGIN, R"PY( +fd_outcome = attempt(lambda: shutil.rmtree("tree", dir_fd=RMTREE_CONSENT_FD)) +)PY"); + + CHECK(python.str("fd_outcome") == "ok"); + REQUIRE(harness.prompts.size() == 1); + CHECK(harness.prompts.front().event == "shutil.rmtree"); + CHECK(harness.prompts.front().targets == std::vector{python.str("RMTREE_CONSENT_TREE")}); + CHECK_FALSE(fs::exists(fs::path(python.str("RMTREE_CONSENT_TREE")))); + CHECK(harness.saved_permissions(PLUGIN).fs_delete.empty()); + python.exec("os.close(RMTREE_CONSENT_FD)"); +} +#elif !defined(_WIN32) +TEST_CASE("A non-default dir_fd fails closed when the platform cannot resolve it", "[audit][Python]") +{ + AuditHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + harness.add_plugin(PLUGIN); + py::gil_scoped_acquire gil; + PythonSide python(harness); + + python.exec(R"PY( +import inspect +DIR_FD_SUPPORTED = "dir_fd" in inspect.signature(os.mkdir).parameters +FD_GRANTED = os.path.realpath(os.path.join(OUTSIDE, "fd-granted")) +FD_TARGET = os.path.realpath(os.path.join(OUTSIDE, "fd-target")) +os.makedirs(FD_GRANTED) +os.makedirs(FD_TARGET) +FD_VICTIM = os.path.join(FD_TARGET, "victim.txt") +with open(FD_VICTIM, "w") as f: + f.write("x") +# Open outside the plugin scope so the audited os.open cannot fail before descriptor use. +FD_TARGET_FD = os.open(FD_TARGET, os.O_RDONLY) +)PY"); + if (python.eval("DIR_FD_SUPPORTED") != "True") + SKIP("This Python does not support dir_fd here"); + + // Even a grant naming the descriptor's folder cannot make an unresolvable descriptor safe. + PluginPermissions permissions; + permissions.fs_create = {python.str("FD_GRANTED"), python.str("FD_TARGET")}; + permissions.fs_delete = {python.str("FD_GRANTED"), python.str("FD_TARGET")}; + harness.save_permissions(PLUGIN, permissions); + + python.run_as(PLUGIN, R"PY( +os.chdir(FD_GRANTED) +try: + plain_outcome = attempt(lambda: os.mkdir("plain")) + created_outcome = attempt(lambda: os.mkdir("child", dir_fd=FD_TARGET_FD)) + removed_outcome = attempt(lambda: os.remove("victim.txt", dir_fd=FD_TARGET_FD)) +finally: + os.chdir(OUTSIDE) +)PY"); + + CHECK(python.str("plain_outcome") == "ok"); + CHECK(python.str("created_outcome") == "denied"); + CHECK(python.str("removed_outcome") == "denied"); + CHECK(describe(harness.prompts).empty()); + CHECK_FALSE(fs::exists(fs::path(python.str("FD_TARGET")) / "child")); + CHECK(fs::exists(fs::path(python.str("FD_VICTIM")))); + python.exec("os.close(FD_TARGET_FD)"); +} +#endif + TEST_CASE("A filesystem wildcard does not override a denied path", "[audit][Python]") { AuditHarness harness; diff --git a/tests/slic3rutils/test_plugin_install.cpp b/tests/slic3rutils/test_plugin_install.cpp index 04468f0ca4..9fb39f277f 100644 --- a/tests/slic3rutils/test_plugin_install.cpp +++ b/tests/slic3rutils/test_plugin_install.cpp @@ -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{"/allowed/create", "/allowed/tree/*"}); + CHECK(permissions.fs_delete == std::vector{"*"}); + } + + 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");