From 0cb79b191484eca0d17404423f47c68f279e411d Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 11:44:03 -0600 Subject: [PATCH 1/4] feat(assistant): full access for the built-in assistant, for the session The built-in assistant asked before every file, web request, script and plugin, with no way to say "just do it". Above the message box (and in the phone's sheet) there is now an access choice: Ask, as before, or Full access, for this session. Full access runs files, the internet, SQL, scripts, tasks, notebooks, models and installed plugins without asking. It still asks before installing, enabling or removing plugins and the GeoLibre tools, before changing connections, sign-ins and saved credentials, extensions and other app settings, and before replacing the open project. Which Reserved commands run is a short list in the policy table, so a new one asks until it is listed. Unreviewed runners stay refused, and tasks from files stay limited to project edits. The level is never saved, is read afresh for each call (a working subagent follows it), and ends when the assistant is turned off. While it is on, a warning by the message box and a status bar item say so, each with one click back to Ask. No command sets it. Connected agents and agent windows keep their own settings. For #3568 (checklist item 2). --- SECURITY.md | 3 +- crates/assistant/src/agent.rs | 26 +++- crates/assistant/src/lib.rs | 1 + crates/assistant/src/tests.rs | 32 +++++ crates/engine/src/policy/decide.rs | 49 +++++-- crates/engine/src/policy/dispatch.rs | 17 ++- crates/engine/src/policy/mod.rs | 2 +- crates/engine/src/policy/plan.rs | 13 +- crates/engine/src/policy/scope.rs | 29 +++- crates/engine/src/tests/permission_policy.rs | 144 ++++++++++++++++++- crates/ui-egui/src/assistant.rs | 48 ++++++- crates/ui-egui/src/assistantpane.rs | 100 ++++++++++++- crates/ui-egui/src/chrome.rs | 12 ++ crates/ui-egui/src/connectui.rs | 5 +- crates/ui-touch/src/assistant.rs | 96 ++++++++++++- docs/user-guide/assistant.md | 37 ++++- 16 files changed, 571 insertions(+), 43 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 70f1c6432d..8e5907916a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -58,7 +58,8 @@ around one of them is a security problem: registry blocklist or a hash mismatch. See [Plugins › Safety](docs/plugins.md#safety). - **Agents**: anything reaching the MCP relay or MCP over HTTP without its token, or from another host or a web page; the AI Assistant running a file, network or plugin command without the - user's approval. See [MCP](docs/mcp.md) and the [AI Assistant](docs/user-guide/assistant.md). + user's approval or the [full access](docs/user-guide/assistant.md#access) they chose, or giving + itself that access. See [MCP](docs/mcp.md) and the [AI Assistant](docs/user-guide/assistant.md). - **Credentials**: passwords, keys or tokens written to the audit log, other logs, project files or exports, or stored outside the OS keychain where the docs say they're kept there. - **Files and links**: opening a data file, project, style, package or URL that runs code, diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index d73a994f53..8fbf658f79 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -8,7 +8,7 @@ use crate::attach::Picture; use crate::provider::{self, Config, HttpRequest, HttpResponse, Note, ToolCall, ToolImage, ToolResult, Turn}; use crate::{acp, compact, skills, tools}; use rustgis_engine::Session; -use rustgis_engine::policy::{Outcome, Pending, Permit, Remembered, Scope}; +use rustgis_engine::policy::{AssistantAccess, Outcome, Pending, Permit, Remembered, Scope}; use std::sync::{ Arc, atomic::{AtomicU64, Ordering}, @@ -159,6 +159,8 @@ pub struct Agent { summary_limit: usize, /// Explicit opt-in: local delegations and their MCP access need no RustGIS approval. agents_auto: bool, + /// What the commands run without asking; a subagent's is its parent's. + access: AssistantAccess, /// Bytes of summary input actually sent. summary_input_len: usize, /// A subagent doing a task this agent delegated ([`Agent::delegate_tool`]), while it works. @@ -251,6 +253,7 @@ impl Agent { retrying_summary: None, summary_limit: compact::BUDGET, agents_auto: false, + access: AssistantAccess::Ask, summary_input_len: 0, child: None, child_shown: 0, @@ -278,6 +281,22 @@ impl Agent { self.agents_auto = auto; } + /// Chooses what runs without asking, from the next call on, a working subagent's included. A + /// new agent asks; the choice isn't part of the conversation and is never saved with it. It + /// doesn't reach agent threads on this computer, which ask by their own setting + /// ([`Agent::set_agents_auto`]). + pub fn set_access(&mut self, access: AssistantAccess) { + self.access = access; + if let Some(child) = self.child.as_mut() { + child.set_access(access); + } + } + + /// What runs without asking ([`Agent::set_access`]). + pub fn access(&self) -> AssistantAccess { + self.access + } + fn local_delegation(&self, call: &ToolCall) -> bool { if call.name != "delegate" || self.depth != 0 @@ -371,6 +390,7 @@ impl Agent { child.allowed = allowed; child.always = self.always.clone(); child.conversation = self.conversation; + child.access = self.access; child.no_reasoning = self.no_reasoning.clone(); child.no_images = self.no_images.clone(); // The budget is the main assistant's: what's left of it for this message. @@ -484,7 +504,7 @@ impl Agent { } fn scope(&self) -> Scope { - Scope::assistant(self.conversation, self.live.clone()) + Scope::assistant(self.conversation, self.live.clone()).with_access(self.access) } /// The tokens the last message's requests took so far, as the provider counts them. `None` when @@ -1554,7 +1574,7 @@ guessing. it reads a tool's output table too. \ Where clauses are SQL-like: pop_max > 1000000 AND continent = 'Asia'. - Every change can be undone (edit.undo), so act when the request is clear and ask only when it is ambiguous. -- Commands that read or write files, use the internet or replace the project wait for the user's approval; they may decline. +- Commands that read or write files, use the internet or replace the project may wait for the user's approval; they may decline. - Keep replies short. Markdown is fine: **bold**, `code`, lists and short tables. Common commands:", diff --git a/crates/assistant/src/lib.rs b/crates/assistant/src/lib.rs index 8b300c2b54..61863522c8 100644 --- a/crates/assistant/src/lib.rs +++ b/crates/assistant/src/lib.rs @@ -39,3 +39,4 @@ pub mod tools; pub use agent::{Agent, Asking, DECLINED, Entry, Step}; pub use provider::{Api, Config, HttpRequest, HttpResponse, Note, PRESETS, Preset}; +pub use rustgis_engine::policy::AssistantAccess; diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 4f3b7d52e4..d9d2b090fb 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -6135,3 +6135,35 @@ fn content_part_notes_are_bounded() { let notes = notes_for(json!([{"type":"a"}, {"type":"b"}])); assert_eq!(notes.len(), 2); } + +/// The chosen access holds from the next call: full access runs an export that asks by default, +/// a subagent has its parent's level and loses it when the user goes back to asking, and neither +/// installs a plugin without an approval. +#[test] +fn full_access_applies_from_the_next_call_to_the_assistant_and_its_subagent() { + let mut s = sample(); + let mut a = Agent::new(cfg("openai"), &s); + assert_eq!(a.access(), crate::AssistantAccess::Ask); + let dir = tempfile::tempdir().unwrap(); + let map = |name: &str| dir.path().join(name); + let export = |name: &str| calls("run_command", json!({"command": "share.exportMap", "params": {"path": map(name)}})); + assert!(matches!(a.ask("export maps", &s), Step::Send(_))); + a.set_access(crate::AssistantAccess::Full); + assert!(matches!(a.receive(a.generation(), ok(export("a.png")), &mut s), Step::Send(_))); + assert!(map("a.png").is_file()); + let install = calls("run_command", json!({"command": "plugin.install", "params": {"path": map("plugin.zip")}})); + assert_eq!(a.receive(a.generation(), ok(install), &mut s), Step::Confirm); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); + // The subagent exports without asking, until the user goes back to asking. + let delegate = calls("delegate", json!({"task": "Export two maps"})); + assert!(matches!(a.receive(a.generation(), ok(delegate), &mut s), Step::Send(_))); + assert!(matches!(a.receive(a.generation(), ok(export("b.png")), &mut s), Step::Send(_))); + assert!(map("b.png").is_file()); + a.set_access(crate::AssistantAccess::Ask); + assert_eq!(a.receive(a.generation(), ok(export("c.png")), &mut s), Step::Confirm); + assert!(!map("c.png").exists()); + // A new conversation keeps the choice, which is the user's and not the conversation's. + a.set_access(crate::AssistantAccess::Full); + a.clear(); + assert_eq!(a.access(), crate::AssistantAccess::Full); +} diff --git a/crates/engine/src/policy/decide.rs b/crates/engine/src/policy/decide.rs index c63aa22148..66f82d2617 100644 --- a/crates/engine/src/policy/decide.rs +++ b/crates/engine/src/policy/decide.rs @@ -1,7 +1,7 @@ use super::{ Effect, Effects, plan::{Node, Op}, - scope::{AgentAccess, Kind, Scope}, + scope::{AgentAccess, AssistantAccess, Kind, Scope}, }; use crate::Session; use rustgis_plugins::manifest::Permission; @@ -37,17 +37,21 @@ fn kind(s: &Session, k: &Kind, node: &Node) -> Decision { Deny } } - Kind::Assistant => node - .effects - .iter() - .map(|e| match e { - Edits | History => Allow, - Files | Network => Remember, - Plugin | Automation | Reserved | Replaces => Ask, - Unreviewed => Deny, - }) - .max() - .unwrap_or(Allow), + Kind::Assistant(access) => { + let full = *access == AssistantAccess::Full; + node.effects + .iter() + .map(|e| match e { + Edits | History => Allow, + Files | Network | Plugin | Automation if full => Allow, + Reserved if full && full_access_runs(node.id()) => Allow, + Files | Network => Remember, + Plugin | Automation | Reserved | Replaces => Ask, + Unreviewed => Deny, + }) + .max() + .unwrap_or(Allow) + } Kind::Agent { access: AgentAccess::Full, .. } => Allow, Kind::Agent { access, users_project, actor } => node .effects @@ -193,6 +197,27 @@ fn refusal(s: &Session, k: &Kind, n: &Node) -> String { } } +/// The `Reserved` commands the assistant's Full access runs without asking: they work with data, +/// models and plugins already there. Every other one asks: installing, enabling or removing +/// plugins and the GeoLibre runner, sign-ins, connections and their saved credentials, S3 listings +/// that use a connection, extensions, the command log and other app settings. A new `Reserved` +/// command asks until it is listed here. +fn full_access_runs(id: &str) -> bool { + matches!( + id, + "gpkg.saveEdits" + | "pg.saveEdits" + | "layer.addDownload" + | "model.new" + | "model.save" + | "project.importGeolibre" + | "project.importQgis" + | "plugin.list" + | "plugin.registry" + | "plugin.panel" + ) +} + /// Direct database and SQL commands are excluded from plugins even when a plugin holds `files` /// and `network` permissions: they can use the user's live PostGIS session, reach local database /// hosts outside HTTP address checks, or run DuckDB SQL. A DuckDB or GeoPackage file's tables diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 79743d6af6..73d1aa6dd7 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -1,6 +1,6 @@ use super::plan::OutputRef; use super::{ - Call, Node, Outcome, Pending, Permit, PluginPin, Remembered, Scope, ToolPin, + AssistantAccess, Call, Node, Outcome, Pending, Permit, PluginPin, Remembered, Scope, ToolPin, decide::{self, Decision}, plan::{CallKind, LayerKey, Op, Plan, Target}, scope::{Continuation, Kind, Narrow}, @@ -383,7 +383,7 @@ impl Session { pub(crate) fn policy_allows_reserved(&self) -> bool { match &self.scope().kind { Kind::User | Kind::Agent { access: super::AgentAccess::Full, .. } => true, - Kind::Assistant => self.policy.nodes.last().is_some_and(|n| n.effects.contains(super::Effect::Reserved)), + Kind::Assistant(_) => self.policy.nodes.last().is_some_and(|n| n.effects.contains(super::Effect::Reserved)), Kind::Peer | Kind::Agent { .. } | Kind::Item { .. } | Kind::Plugin { .. } => false, } } @@ -440,7 +440,15 @@ impl Session { let result = (|| { let node = self.call_node(scope, call)?; if node.decision(self, scope)? == Decision::Allow { - return Ok(Outcome::Allowed); + // A script, task, notebook or model that runs as a whole may hold a step that still + // asks: planned to find it, so it's shown now rather than refused partway. One too + // large to plan runs, and each of its steps is checked as it comes. + let step_asks = matches!(scope.kind, Kind::Assistant(_)) + && node.effects.contains(super::Effect::Automation) + && self.plan(scope, call).and_then(|p| p.decision(self, scope)).is_ok_and(|d| d != Decision::Allow); + if !step_asks { + return Ok(Outcome::Allowed); + } } let plan = self.plan(scope, call)?; let decision = plan.decision(self, scope)?; @@ -461,7 +469,8 @@ impl Session { } )); } - let review = plan.review(decision == Decision::Remember)?; + let full_access = matches!(scope.kind, Kind::Assistant(AssistantAccess::Full)); + let review = plan.review(decision == Decision::Remember, full_access)?; Ok(Outcome::NeedsApproval(Pending { plan: Arc::new(plan), review: Box::new(review), request: call.request.clone() })) })(); result.unwrap_or_else(Outcome::Refused) diff --git a/crates/engine/src/policy/mod.rs b/crates/engine/src/policy/mod.rs index a9899074cd..08836918a2 100644 --- a/crates/engine/src/policy/mod.rs +++ b/crates/engine/src/policy/mod.rs @@ -22,7 +22,7 @@ pub use handler::Handler; pub use plan::{Call, Review, ReviewDetail}; pub(crate) use plan::{Node, PluginPin, ToolPin}; pub(crate) use provenance::Trust; -pub use scope::{AgentAccess, Deferred, Outcome, Pending, Permit, Principal, Remembered, Revocation, Scope}; +pub use scope::{AgentAccess, AssistantAccess, Deferred, Outcome, Pending, Permit, Principal, Remembered, Revocation, Scope}; pub(crate) use scope::{Continuation, Narrow}; /// Compatibility projection for native metadata consumers; policy itself keeps additive effects. diff --git a/crates/engine/src/policy/plan.rs b/crates/engine/src/policy/plan.rs index ba1b7fc7dd..3f85745a50 100644 --- a/crates/engine/src/policy/plan.rs +++ b/crates/engine/src/policy/plan.rs @@ -1331,8 +1331,9 @@ impl Plan { pub(super) fn decision(&self, s: &Session, scope: &Scope) -> Result { self.root.decision(s, scope) } - /// Produces a bounded sanitized display copy; raw equality data remains private. - pub(super) fn review(&self, remember: bool) -> Result { + /// Produces a bounded sanitized display copy; raw equality data remains private. At the + /// assistant's full access (`full_access`) the reason is one of the few that still ask there. + pub(super) fn review(&self, remember: bool, full_access: bool) -> Result { /// Refuses parameters too large to present before constructing an approval card. fn raw_size(n: &Node) -> usize { n.params.to_string().len().saturating_add(n.children.iter().map(raw_size).sum::()) @@ -1405,7 +1406,13 @@ impl Plan { fn all_effects(n: &Node) -> Effects { n.children.iter().fold(n.effects, |e, c| e.union(all_effects(c))) } - let explanation = self.root.explanation(all_effects(&self.root)); + let all = all_effects(&self.root); + // Files, the internet, scripts and plugins don't ask at full access, so they aren't why. + let explanation = match full_access { + true if all.contains(Effect::Replaces) => (decide::reason(Effects::NONE.with(Effect::Replaces)), vec![]), + true => ("it changes plugins, connections, sign-ins, saved credentials or app settings", vec![]), + false => self.root.explanation(all), + }; let mut why = explanation.0.to_string(); for (key, value) in &explanation.1 { why = why.replace(&format!("{{{key}}}"), value); diff --git a/crates/engine/src/policy/scope.rs b/crates/engine/src/policy/scope.rs index 4b751ad588..fa8628a46b 100644 --- a/crates/engine/src/policy/scope.rs +++ b/crates/engine/src/policy/scope.rs @@ -48,6 +48,17 @@ pub enum AgentAccess { Allow, Full, } +/// How much the assistant built into RustGIS does without asking. Connected agents have their own +/// [`AgentAccess`]. Never saved with a project; a new [`Scope::assistant`] asks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum AssistantAccess { + /// Project edits run; files and the internet ask, and may be remembered; the rest asks. + #[default] + Ask, + /// Files, the internet, SQL, scripts and installed plugins run too. Installing plugins and + /// other programs, sign-ins, saved credentials, app settings and replacing the project still ask. + Full, +} /// Live authority, checked at dispatch and at the actual start and application of late work. pub trait Revocation: Send + Sync { /// Answers from live adapter state at each new start or application, including workers. @@ -62,7 +73,7 @@ pub struct Scope { #[derive(Clone)] pub(super) enum Kind { User, - Assistant, + Assistant(AssistantAccess), Agent { access: AgentAccess, users_project: bool, actor: Option }, Plugin { pin: PluginPin, within: Box }, Item { kind: &'static str, name: String, within: Box }, @@ -85,9 +96,19 @@ impl Scope { } actor(&self.kind).map(str::to_owned) } - /// Names one assistant conversation and its revocable lifetime. + /// Names one assistant conversation and its revocable lifetime. It asks + /// ([`AssistantAccess::Ask`]) unless [`Scope::with_access`] says otherwise. pub fn assistant(conversation: u64, live: Arc) -> Self { - Self { kind: Kind::Assistant, owner: Owner { kind: "assistant", id: conversation.to_string() }, live: Some(live) } + let kind = Kind::Assistant(AssistantAccess::Ask); + Self { kind, owner: Owner { kind: "assistant", id: conversation.to_string() }, live: Some(live) } + } + /// The assistant's scope at the access the user has chosen, read afresh for each call. Other + /// callers' scopes are left as they are. + pub fn with_access(mut self, access: AssistantAccess) -> Self { + if let Kind::Assistant(held) = &mut self.kind { + *held = access; + } + self } /// Names an explicit ingress grant, actor and access setting; payload JSON cannot create it. pub fn agent(access: AgentAccess, users_project: bool, grant: &str, actor: Option, live: Arc) -> Self { @@ -101,7 +122,7 @@ impl Scope { pub fn principal(&self) -> Principal { match &self.kind { Kind::User => Principal::User, - Kind::Assistant => Principal::Assistant, + Kind::Assistant(_) => Principal::Assistant, Kind::Agent { access, users_project, .. } => Principal::Agent { access: *access, users_project: *users_project }, Kind::Plugin { pin, .. } => Principal::Plugin { id: pin.0.manifest.id.clone() }, Kind::Item { kind, name, .. } => Principal::Item { kind, name: name.clone() }, diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index 571e117f6c..7e07ee5c8d 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -1,7 +1,7 @@ //! Public dispatch, frozen consent and owned late work share the engine's permission outcome. #![expect(clippy::disallowed_methods, reason = "a thread the system refuses fails the test, as it should")] use super::*; -use crate::policy::{Call, Effects, Outcome, Pending, Revocation, Scope}; +use crate::policy::{AssistantAccess, Call, Effects, Outcome, Pending, Revocation, Scope}; use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, @@ -2204,3 +2204,145 @@ fn permission_policy_a_called_script_gives_the_project_its_system() { assert_eq!(s.map().projection.code(), "EPSG:2056"); std::fs::remove_dir_all(&dir).ok(); } + +/// The assistant at full access, and at the default. +fn full_and_ask(id: u64) -> (Scope, Scope) { + let (ask, _) = assistant(id); + (ask.clone().with_access(AssistantAccess::Full), ask) +} + +/// Full access runs files, the internet, SQL, scripts, tasks and installed plugins without a +/// review; the default still asks for each, and remembers only files and the internet. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn permission_policy_assistant_full_access_runs_what_ask_waits_for() { + if isolate_process_test("tests::permission_policy::permission_policy_assistant_full_access_runs_what_ask_waits_for") { + return; + } + let path = std::env::temp_dir().join(format!("rustgis-engine-full-access-{}.geojson", std::process::id())); + let _ = std::fs::remove_file(&path); + let path = path.to_string_lossy().into_owned(); + let mut s = world(); + s.leave_downloads = true; + plugin("policy-full-plugin", &["edit"]); + let step = json!({"title":"Export","command":"share.exportLayer","params":{"layer":"Cities","path":path}}); + s.run("task.new", &json!({"name":"Export cities","steps":[step]})).unwrap(); + let (full, ask) = full_and_ask(35681); + let calls = [ + (Call::command("share.exportLayer", json!({"layer":"Cities","path":path})), true), + (Call::command("map.addTiles", json!({"url":"https://example.com/{z}/{x}/{y}.png"})), true), + (Call::command("sql.query", json!({"sql":"SELECT 1"})), true), + (Call::command("script.run", json!({"script":"select.clear"})), false), + (Call::command("task.run", json!({"task":"Export cities"})), false), + (Call::command("plugin:policy-full-plugin/h", Value::Null), false), + (Call::tool("plugin:policy-full-plugin/x", json!({"input":"Cities"})), false), + ]; + for (call, remembered) in &calls { + let asked = pending(&s, &ask, call); + assert_eq!(asked.review().remember, *remembered, "{}", asked.review().what); + assert!(matches!(s.review(&full, call), Outcome::Allowed), "{}", asked.review().what); + } + s.run_scoped(full.clone(), &calls[0].0).unwrap(); + assert!(std::fs::metadata(&path).unwrap().len() > 0); + std::fs::remove_file(&path).unwrap(); + s.run_scoped(full.clone(), &calls[4].0).unwrap(); + assert!(std::fs::metadata(&path).unwrap().len() > 0, "a task of the user's own runs through"); + // A task from a file keeps to project edits at any level. + s.run("task.new", &json!({"name":"From a file","imported":true,"steps":[step]})).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert!(s.run_scoped(full.clone(), &Call::command("task.run", json!({"task":"From a file"}))).is_err()); + assert!(!std::path::Path::new(&path).exists()); + // Another caller's scope isn't widened by it. + let refused = Scope::agent(crate::policy::AgentAccess::Refuse, false, "not-the-assistant", None, Arc::new(Live(AtomicBool::new(true)))); + for other in [refused.with_access(AssistantAccess::Full), Scope::peer().with_access(AssistantAccess::Full)] { + assert!(matches!(s.review(&other, &calls[0].0), Outcome::Refused(_))); + } + rustgis_plugins::unload("policy-full-plugin"); +} + +/// What full access still asks about, never remembered: installs, sign-ins and saved credentials, +/// app settings and replacing the project, also as a line of a script or a step of a task. +#[test] +fn permission_policy_assistant_full_access_still_asks() { + let mut s = world(); + let (full, _) = full_and_ask(35682); + let calls = [ + ("plugin.install", json!({"path":"plugin.zip"})), + ("plugin.installFromRegistry", json!({"id":"somebody/plugin"})), + ("plugin.enable", json!({"id":"somebody/plugin"})), + ("plugin.uninstall", json!({"id":"somebody/plugin"})), + ("plugin.prepare", json!({"id":"somebody/plugin"})), + ("gp.installGeolibre", Value::Null), + ("gp.setGeolibre", json!({"path":"geolibre"})), + ("connection.new", json!({"kind":"wms","address":"https://example.com/wms"})), + ("connection.login", json!({"id":"office","password":"hunter2"})), + ("connection.forgetPassword", json!({"id":"office"})), + ("arcgis.signOut", Value::Null), + ("earthdata.login", json!({"token":"abc","remember":true})), + ("copernicus.logout", Value::Null), + ("s3.connect", json!({"name":"mine"})), + ("s3.list", json!({"connection":"mine","bucket":"data"})), + ("pg.connect", json!({"database":"host=localhost dbname=gis"})), + ("extension.disable", json!({"id":"assistant"})), + ("project.logCommands", json!({"on":false})), + ("project.new", Value::Null), + ("project.open", json!({"path":"other.rgis"})), + ]; + let steps = s.undo_depth(); + for (id, params) in calls { + let direct = Call::command(id, params.clone()); + let line = if params.is_null() { id.to_string() } else { format!("{id} {params}") }; + let in_script = Call::command("script.run", json!({ "script": line })); + for call in [direct, Call::script(&line), in_script] { + let asked = pending(&s, &full, &call); + assert!(!asked.review().remember, "{id}"); + let why = if id.starts_with("project.new") || id == "project.open" { "replaces the open project" } else { "sign-ins" }; + assert!(asked.review().why.contains(why), "{id}: {}", asked.review().why); + assert!(s.run_scoped(full.clone(), &call).is_err(), "{id} ran without its approval"); + } + } + s.run("task.new", &json!({"name":"Sign out","steps":[{"title":"Out","command":"arcgis.signOut","params":{}}]})).unwrap(); + pending(&s, &full, &Call::command("task.run", json!({"task":"Sign out"}))); + assert_eq!(s.undo_depth(), steps + 1, "only the task's own creation"); +} + +/// Every `Reserved` command asks under full access unless it is one of these, so a new one asks +/// until someone decides otherwise. External runners nobody reviewed stay refused. +#[test] +fn permission_policy_assistant_full_access_reserved_commands() { + let mut s = world(); + #[cfg(not(target_arch = "wasm32"))] + { + s.leave_downloads = true; + } + let (full, ask) = full_and_ask(35683); + let mut runs = Vec::new(); + for spec in crate::cmd::all() { + if !spec.effects.contains(crate::policy::Effect::Reserved) { + continue; + } + let call = Call::command(spec.id, Value::Null); + assert!(!matches!(s.review(&ask, &call), Outcome::Allowed), "{}", spec.id); + if matches!(s.review(&full, &call), Outcome::Allowed) { + runs.push(spec.id); + } + } + runs.sort_unstable(); + assert_eq!( + runs, + [ + "gpkg.saveEdits", + "layer.addDownload", + "model.new", + "model.save", + "pg.saveEdits", + "plugin.list", + "plugin.panel", + "plugin.registry", + "project.importGeolibre", + "project.importQgis", + ] + ); + s.registry.commands.push(crate::CommandSpec::new("test.unreviewed", "Unreviewed", "Test", |_, _| Ok(Value::Null))); + assert!(matches!(s.review(&full, &Call::command("test.unreviewed", Value::Null)), Outcome::Refused(_))); +} diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 17f896b02f..54ab9a670e 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -16,7 +16,7 @@ //! Requests go out off the frame: on a thread on the desktop, through `Services::http` (the //! browser's fetch) on the web. Their replies are taken in by [`RustGisApp::logic`] each frame. -use rustgis_assistant::{Agent, Config, Entry, HttpRequest, HttpResponse, Step, chatgpt, provider}; +use rustgis_assistant::{Agent, AssistantAccess, Config, Entry, HttpRequest, HttpResponse, Step, chatgpt, provider}; use crate::{RustGisApp, Slot}; @@ -110,6 +110,8 @@ pub struct AssistantState { pub(crate) retry: Option<(u64, web_time::Instant)>, /// The user lets the assistant hand tasks to local agents (Claude Code, Codex). pub(crate) local_agents: bool, + /// What the assistant runs without asking ([`set_access`]). Never saved: a launch asks. + access: AssistantAccess, /// The tokens a message took are left out of the conversation (shown unless the user says). pub(crate) hide_tokens: bool, /// Each call has a line of its own instead of sharing one ([`lines`]). @@ -274,6 +276,43 @@ fn typing(ctx: &egui::Context) -> bool { ctx.memory(|m| FIELDS.iter().any(|f| m.has_focus(egui::Id::unique(f)))) } +/// What the assistant in the pane runs without asking. +pub fn access(app: &RustGisApp) -> AssistantAccess { + app.assistant.access +} + +/// Chooses what the assistant runs without asking, from its next call on. Only the user's own +/// controls call this: it is no command, so nothing the assistant or an agent runs can widen it. +/// It isn't saved, and it leaves connected agents and agent threads as their settings have them. +pub fn set_access(app: &mut RustGisApp, access: AssistantAccess) { + app.assistant.access = access; + if let Some(agent) = app.assistant.agent.as_mut() { + agent.set_access(access); + } +} + +/// The access levels offered, with their names. +pub fn access_choices() -> [(AssistantAccess, &'static str); 2] { + [(AssistantAccess::Ask, tl!("Ask")), (AssistantAccess::Full, tl!("Full access, for this session"))] +} + +/// What a level lets run without asking, for the control's explanation. +pub fn access_explanation(access: AssistantAccess) -> &'static str { + match access { + AssistantAccess::Ask => { + tl!("Project edits run without asking. Files, the internet, SQL, scripts and plugins wait for your approval.") + } + #[cfg(not(target_arch = "wasm32"))] + AssistantAccess::Full => tl!( + "Files, the internet, SQL, scripts and installed plugins run without asking. It still asks before installing plugins, changing connections, sign-ins, saved credentials or app settings, and replacing the project. It lasts until RustGIS closes." + ), + #[cfg(target_arch = "wasm32")] + AssistantAccess::Full => tl!( + "The internet, downloads of exported files, scripts and installed plugins run without asking. It still asks before installing plugins, changing connections, sign-ins, saved credentials or app settings, and replacing the project. It lasts until you close or reload this page." + ), + } +} + /// Reads a nonempty preference, including legacy keys awaiting migration. pub(crate) fn pref(app: &RustGisApp, key: &str) -> Option { app.services.load_pref.as_ref().and_then(|l| l(key)).filter(|v| !v.is_empty()) @@ -416,6 +455,7 @@ pub(crate) fn ensure_loaded(app: &mut RustGisApp, ctx: &egui::Context) { } // The skills switched on (the plugins' too), and the local agents the user allows (desktop). agent.set_skills(rustgis_assistant::skills::installed()); + agent.set_access(app.assistant.access); #[cfg(not(target_arch = "wasm32"))] agent.set_agents_auto(app.assistant.agents_auto); app.assistant.skills_rev = rustgis_engine::plugins::revision(); @@ -877,6 +917,9 @@ pub(crate) fn turned_off(app: &mut RustGisApp) { let signing_in = false; // A message not sent yet stays in the message box. app.assistant.hold(); + // Full access ends with the assistant: turned on again, it asks. + let had_full = app.assistant.access == AssistantAccess::Full; + set_access(app, AssistantAccess::Ask); if let Some(agent) = app.assistant.agent.as_mut() { agent.suspend(); } @@ -887,6 +930,9 @@ pub(crate) fn turned_off(app: &mut RustGisApp) { || !app.assistant.input.trim().is_empty() || app.assistant.pictures.any(); let mut said = Vec::new(); + if had_full { + said.push(tl!("The AI Assistant's full access ended: turned on again, it asks.").to_string()); + } if busy { said.push(tl!("The AI Assistant's running request was stopped; what it had already done stays.").to_string()); } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 644543fa28..e79b385f96 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -3,7 +3,7 @@ //! conversation and what can be done with it are in [`crate::assistant`]. use egui::{Align, Layout, RichText, Ui, vec2}; -use rustgis_assistant::{Config, Entry, PRESETS, chatgpt, provider}; +use rustgis_assistant::{AssistantAccess, Config, Entry, PRESETS, chatgpt, provider}; #[cfg(not(target_arch = "wasm32"))] use crate::assistant::pref; @@ -727,6 +727,48 @@ fn account_row(_app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, _cfg: &mut Config ui.label(RichText::new(tl!("Signing in with ChatGPT works in the desktop app.")).small().color(t.text_dim)); } +/// What the assistant runs without asking, above the message box, and while it has full access, a +/// warning with the way back. +fn access_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { + let held = assistant::access(app); + let mut chosen = held; + let mine = tl!("For the assistant in this pane. Connected agents and agent windows keep their own settings."); + ui.horizontal(|ui| { + let label = ui.label(RichText::new(tl!("Access")).small().color(t.text_dim)).on_hover_text(mine); + let name = assistant::access_choices().into_iter().find(|(a, _)| *a == held).map_or("", |(_, name)| name); + egui::ComboBox::from_id_salt("assistant_access") + .selected_text(RichText::new(name).small()) + .width((ui.available_width() - ui.spacing().button_padding.x * 2.0).clamp(0.0, 200.0)) + .truncate() + .show_ui(ui, |ui| { + for (level, name) in assistant::access_choices() { + let explained = format!("{}\n{mine}", assistant::access_explanation(level)); + ui.selectable_value(&mut chosen, level, name).on_hover_text(explained); + } + }) + .response + .labelled_by(label.id) + .on_hover_text(format!("{}\n{mine}", assistant::access_explanation(held))); + }); + if held == AssistantAccess::Full { + egui::Frame::NONE.fill(t.red.gamma_multiply(0.12)).corner_radius(6).inner_margin(6).stroke(egui::Stroke::new(1.0, t.red)).show( + ui, + |ui| { + ui.horizontal_wrapped(|ui| { + ui.label(RichText::new(tl!("Full access: the assistant acts without asking.")).small().color(t.red)) + .on_hover_text(assistant::access_explanation(held)); + if ui.small_button(tl!("Back to Ask")).clicked() { + chosen = AssistantAccess::Ask; + } + }); + }, + ); + } + if chosen != held { + assistant::set_access(app, chosen); + } +} + /// The input box's least height (two lines), and how tall it grows with text before it scrolls. const INPUT_HEIGHT: f32 = 44.0; const INPUT_GROWS: f32 = 160.0; @@ -775,6 +817,7 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu if app.assistant.config().is_some_and(|c| c.login() && !c.key.is_empty()) { plan_line(ui, t); } + access_row(app, ui, t); let id = egui::Id::unique("assistant_input"); // Enter sends; Shift+Enter starts a new line. let focused = ui.memory(|m| m.has_focus(id)); @@ -2781,6 +2824,61 @@ pub(crate) mod tests { h } + /// Full access is picked by the message box, shown there and in the status bar, left by one + /// click on either, ended with the extension, and neither saved nor restored. + #[test] + fn full_access_is_chosen_shown_and_never_restored() { + use egui_kittest::kittest::Queryable; + use rustgis_assistant::AssistantAccess; + use std::sync::{Arc, Mutex}; + let mut h = chat(Vec::new(), "m"); + let saved = Arc::new(Mutex::new(Vec::new())); + let keep = saved.clone(); + let app = h.state_mut(); + app.services.load_pref = Some(Box::new(|key: &str| key.contains("access").then(|| "full".to_string()))); + app.services.save_pref = Some(Box::new(move |k, v| keep.lock().unwrap().push((k.to_string(), v.to_string())))); + app.assistant.loaded = false; + app.assistant.agent = None; + h.run_steps(4); + let level = |h: &egui_kittest::Harness<'_, RustGisApp>| { + let app = h.state(); + (assistant::access(app), app.assistant.agent.as_ref().unwrap().access()) + }; + assert_eq!(level(&h), (AssistantAccess::Ask, AssistantAccess::Ask), "a launch never restores full access"); + const SAID: &str = "Full access: the assistant acts without asking."; + assert!(h.query_by_label(SAID).is_none() && h.query_by_label("Assistant: full access").is_none()); + let choose = |h: &mut egui_kittest::Harness<'_, RustGisApp>| { + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Access").click(); + h.run_steps(4); + h.get_by_label("Full access, for this session").click(); + h.run_steps(4); + }; + choose(&mut h); + assert_eq!(level(&h), (AssistantAccess::Full, AssistantAccess::Full)); + h.get_by_label(SAID); + h.get_by_label("Back to Ask").click(); + h.run_steps(4); + assert_eq!(level(&h), (AssistantAccess::Ask, AssistantAccess::Ask)); + assert!(h.query_by_label(SAID).is_none()); + // The status bar says it with the pane closed, and ends it. + choose(&mut h); + h.state_mut().run("ui.pane.assistant", serde_json::Value::Null).unwrap(); + h.run_steps(4); + assert!(h.query_by_label(SAID).is_none(), "the pane is closed"); + h.get_by_label("Assistant: full access").click(); + h.run_steps(4); + assert_eq!(level(&h), (AssistantAccess::Ask, AssistantAccess::Ask)); + assert!(h.query_by_label("Assistant: full access").is_none()); + // Turning the extension off ends it, and says so. + assistant::set_access(h.state_mut(), AssistantAccess::Full); + let mark = h.state().session.notice_mark(); + h.state_mut().session.run("extension.disable", &serde_json::json!({"id": "assistant"})).unwrap(); + h.run_steps(4); + assert_eq!(level(&h), (AssistantAccess::Ask, AssistantAccess::Ask)); + assert!(h.state().session.notices_since(mark).iter().any(|n| n.text.contains("full access ended"))); + assert!(!saved.lock().unwrap().iter().any(|(k, _)| k.contains("access")), "never saved"); + } + /// #307: a reply wider than the pane pushed its edge off the window, so the map covered the /// chat and the edge could not be dragged. The pane stays in the window and keeps resizing. #[test] diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index edf3b6f64f..b918fb34a1 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -630,6 +630,18 @@ pub fn status_bar(app: &mut RustGisApp, ui: &mut Ui) { sep(ui, &t); } } + // The assistant's full access, shown with its pane closed too; a click ends it. + if crate::assistant::access(app) == rustgis_assistant::AssistantAccess::Full + && app.session.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id) + { + let text = egui::RichText::new(tl!("Assistant: full access")).size(11.5).color(t.red); + let resp = ui.add(egui::Label::new(text).sense(Sense::click())); + let hover = tl!("The assistant runs files, the internet, scripts and plugins without asking. Click to go back to Ask"); + if resp.on_hover_text(hover).clicked() { + crate::assistant::set_access(app, rustgis_assistant::AssistantAccess::Ask); + } + sep(ui, &t); + } if ui.small_button(tl!("Messages")).on_hover_text(tl!("Review messages and failed network requests")).clicked() { app.ui.open_right(crate::RightPane::DiagnosticLog); } diff --git a/crates/ui-egui/src/connectui.rs b/crates/ui-egui/src/connectui.rs index 7c0fadc723..9bb492ab83 100644 --- a/crates/ui-egui/src/connectui.rs +++ b/crates/ui-egui/src/connectui.rs @@ -271,7 +271,10 @@ fn details(app: &mut RustGisApp, ui: &mut egui::Ui) { .color(Tokens::get(ui.ctx()).red), ); } - ui.label(RichText::new(tl!("This is for agents you connect. It doesn't change what the assistant in this pane asks about.")).small()); + ui.label( + RichText::new(tl!("This is for agents you connect. The assistant in this pane has its own access choice, above its message box.")) + .small(), + ); // Agents that can't use MCP: a script written to a file. if let Some(bridge) = &app.file_bridge { let (command, result) = (bridge.command_path().display().to_string(), bridge.result_path().display().to_string()); diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index 2be3f4fda2..510b4e35be 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -8,7 +8,7 @@ //! until a provider is set up (a row in More sets one up), nor at all with the extension off. use egui::{Align, Layout, RichText, Sense, Stroke, Ui, Vec2}; -use rustgis_ui_egui::rustgis_assistant::{Asking, Entry, PRESETS, provider}; +use rustgis_ui_egui::rustgis_assistant::{Asking, AssistantAccess, Entry, PRESETS, provider}; use rustgis_ui_egui::rustgis_engine::platform::{TextEntry, TextKind, Typed}; use rustgis_ui_egui::theme::Tokens; use rustgis_ui_egui::{RustGisApp, assistant, i18n, tl, tl_raw}; @@ -238,7 +238,11 @@ pub(crate) fn strip(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { assistant::stop(app); } let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), TARGET), Sense::click()); - let mut job = egui::text::LayoutJob::simple_singleline(doing(app), egui::FontId::proportional(14.0), t.text); + let (doing, ink) = match assistant::access(app) { + AssistantAccess::Full => (i18n::fmt("Full access · {step}", &[("step", &doing(app))]), t.red), + AssistantAccess::Ask => (doing(app), t.text), + }; + let mut job = egui::text::LayoutJob::simple_singleline(doing, egui::FontId::proportional(14.0), ink); job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width().max(0.0)); let galley = ui.painter().layout_job(job); ui.painter().galley(egui::pos2(rect.min.x, rect.center().y - galley.size().y / 2.0), galley, t.text); @@ -289,6 +293,10 @@ pub(crate) fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } let settings = state.settings; heading(app, ui, t, &mut state, set_up, settings); + // In sight over the conversation, an approval and the settings alike. + if set_up != Setup::Off && assistant::access(app) == AssistantAccess::Full { + full_access(app, ui, t); + } match set_up { Setup::Off => {} Setup::Reading => { @@ -335,6 +343,40 @@ fn heading(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat, set_ } } +/// While the assistant has full access: saying so, with the way back. +fn full_access(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { + ui.horizontal(|ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if action(ui, t, tl!("Back to Ask"), 120.0, false, true) { + assistant::set_access(app, AssistantAccess::Ask); + } + ui.with_layout(Layout::left_to_right(Align::Center), |ui| { + let said = RichText::new(tl!("Full access: the assistant acts without asking.")).size(13.0).color(t.red); + ui.add(egui::Label::new(said).wrap()); + }); + }); + }); +} + +/// What the assistant runs without asking, as two chips over the message box. +fn access_chips(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { + let held = assistant::access(app); + let choices = assistant::access_choices(); + ui.horizontal(|ui| { + let gaps = ui.spacing().item_spacing.x * (choices.len() - 1) as f32; + let width = (ui.available_width() - gaps) / choices.len() as f32; + for (level, name) in choices { + let on = held == level; + let text = RichText::new(name).size(13.0).color(if on { t.accent_text } else { t.text }); + // Wrapped in its share of the row, so a long name never pushes the sheet wider. + let chip = egui::Button::new(text).fill(if on { t.checked } else { t.input }).wrap(); + if ui.add_sized(Vec2::new(width, TARGET), chip).clicked() && !on { + assistant::set_access(app, level); + } + } + }); +} + /// The conversation, with the approval waiting or the typing bar under it. fn conversation(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { let approval = assistant::pending(app); @@ -351,11 +393,13 @@ fn conversation(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) ui.ctx().request_repaint(); } // The foot first, so the messages take what is left above it. - egui::Panel::bottom("touch_assistant_foot").frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4))).show(ui, |ui| { - match &approval { - Some(approval) => card(app, ui, t, state, approval, room), - None => typing(app, ui, t, state), - } + // Its first frame is already as tall as the typing bar with the access chips over it, so + // Send is in sight at once. + let typing_height = 2.0 * TARGET + ui.spacing().item_spacing.y + 8.0; + let foot = egui::Panel::bottom("touch_assistant_foot").frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4))); + foot.default_size(typing_height).show(ui, |ui| match &approval { + Some(approval) => card(app, ui, t, state, approval, room), + None => typing(app, ui, t, state), }); egui::ScrollArea::vertical().id_salt("touch_assistant_messages").auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); @@ -539,6 +583,7 @@ fn typing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { if app.assistant.sending_when_ready() { ui.label(RichText::new(tl!("It is sent once the key and any picture are read.")).size(13.0).color(t.text_dim)); } + access_chips(app, ui, t); let id = egui::Id::unique("touch_assistant_input"); let mut send = false; ui.horizontal(|ui| { @@ -1461,4 +1506,41 @@ mod tests { held.frame(Vec::new()); assert_eq!((sheet(&held.ctx), height(&held.ctx)), (Sheet::Assistant, Height::Half)); } + + /// The phone's choice of access: two chips over the message box, and while it is full a line + /// under the heading with the way back. An export that would ask runs at full access. + #[test] + fn full_access_is_chosen_in_the_sheet_said_and_left_there() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + let path = std::env::temp_dir().join(format!("rustgis-touch-full-access-{}.png", std::process::id())); + let export = command("c0", "share.exportMap", json!({"path": path})); + answering(&mut held, vec![export, say("Exported.")]); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + const SAID: &str = "Full access: the assistant acts without asking."; + assert_eq!(assistant::access(&held.app), AssistantAccess::Ask); + assert!(held.find(SAID).is_none() && held.find("Back to Ask").is_none()); + let chip = held.find("Full access, for this session").expect("the chip"); + let send = held.find("Send").expect("Send"); + assert!(chip.max.x <= held.screen.x && send.max.x <= held.screen.x, "the chips fit: {chip:?}, {send:?}"); + let full = chip.center(); + held.touch(&[full]); + held.frame(Vec::new()); + assert_eq!(assistant::access(&held.app), AssistantAccess::Full); + assert!(held.find(SAID).is_some()); + held.app.assistant.input = "Export the map".into(); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + held.frame(Vec::new()); + assert!(assistant::pending(&held.app).is_none(), "nothing asks"); + assert!(held.find("Exported.").is_some()); + assert!(path.is_file()); + std::fs::remove_file(&path).unwrap(); + let back = held.find("Back to Ask").expect("the way back").center(); + held.touch(&[back]); + held.frame(Vec::new()); + assert_eq!(assistant::access(&held.app), AssistantAccess::Ask); + assert!(held.find(SAID).is_none()); + } } diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index f04c1dd650..9f91647a4c 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -18,7 +18,8 @@ Each step it takes shows in the conversation (click one to see its parameters an It can run several commands in one step, which one Ctrl+Z takes back together. Project edits use the usual undo history, so Ctrl+Z takes them back; undo does not remove exported files or reverse actions outside the project. Check the tool results and map rather than relying only on the -model's reply. Commands that would read or write files, connect to +model's reply. At **Ask** access (the default, see [below](#access)), commands that would read or +write files, connect to an address on the internet, run a plugin, script, task or model, or replace the project wait for you: **Allow** or **Decline**. SQL queries also ask, because SQL can access files and the network. **Don't ask again for exactly this action** remembers the exact command and all @@ -47,6 +48,33 @@ controls. From the command line, `rustgis-cli ask` sends one request (see [Command Line](../cli.md#asking-the-ai-assistant)). +## Access + +**Access**, above the message box, says what the assistant runs without asking. + +| Level | Runs without asking | Still asks | +| --- | --- | --- | +| **Ask** | Project edits | Files, the internet, SQL, scripts, tasks, notebooks, models, plugins and replacing the project | +| **Full access, for this session** | Also files, the internet, SQL, scripts, tasks, notebooks, models and installed plugins, and saving edits to a GeoPackage or PostGIS | Installing, enabling or removing plugins and the GeoLibre tools; connections, sign-ins and saved credentials; listing S3 buckets with a connection; extensions, the session log and other app settings; replacing the project | + +Full access is never saved: RustGIS always starts at **Ask**, and turning the assistant off also +returns to it. While it is on, a warning above the message box and **Assistant: full access** in +the status bar say so; **Back to Ask**, or a click on the status bar, ends it, from the +assistant's next action on. Subagents work at the same level. + +With full access nothing waits for you, so a layer or web page written to mislead the model can +have it overwrite files you can write to or send data out. Use it with data and models you trust, +and check what the conversation says it ran. What no level allows stays refused: external runners +RustGIS hasn't reviewed, and anything but project edits from a task, notebook or model that came +from a file or was made by an assistant, agent or plugin. + +In the browser there are no files on disk to read or write: exports download, and full access +lasts until you close or reload the page. + +The choice covers only the assistant built into RustGIS. [Connected agents](../mcp.md) keep their +own settings, and so do [agents on this computer](#agents-on-this-computer) that the assistant +hands tasks to; handing one a task still asks unless you turned that off for them. + ## On a phone In the [touch interface](field-work.md#the-touch-interface) nothing of the assistant shows until @@ -57,7 +85,8 @@ dictation), then **Send**. The sheet stands half up, to see the map with the con for reading and typing: the arrow beside its **×** switches, and a swipe up or down on its heading moves it a step. Lowered while the assistant works, a strip over the bar says what it is doing and has **Stop**; tap its words to raise the sheet again. Approvals are a card with **Allow** and -**Decline**. The gear in the sheet's heading opens the settings again. Signing in with ChatGPT is +**Decline**. [Access](#access) is the two buttons over the message box; with full access, the +sheet says so under its heading, with **Back to Ask**. The gear in the sheet's heading opens the settings again. Signing in with ChatGPT is set up in the desktop interface. ## Turning the assistant off @@ -378,8 +407,8 @@ rename phase can leave earlier skills installed; the error names those completed For a self-contained task, the assistant can use `delegate` to start a fresh conversation with the same provider and model, acting on the same project. The subagent receives the task, not the whole conversation, and returns a short report. Its tool calls appear in the main -transcript, and file, network and other gated actions still need approval. It inherits the -conversation's exact-command approvals. This works without installing a local coding agent; +transcript, and what the [access level](#access) asks about still needs approval. It inherits the +level and the conversation's exact-command approvals. This works without installing a local coding agent; it is distinct from the background threads below. ## Agents on this computer From e981ebc66ba6f2880bb2e2200d8881beb7241f02 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 15:22:01 -0600 Subject: [PATCH 2/4] fix(assistant): keep protected files and settings behind approval --- crates/engine/src/cmd/raster.rs | 2 +- crates/engine/src/cmd/sharing.rs | 43 +++++++---- crates/engine/src/policy/decide.rs | 19 ++++- crates/engine/src/policy/dispatch.rs | 1 + crates/engine/src/policy/mod.rs | 2 + crates/engine/src/policy/plan.rs | 9 ++- crates/engine/src/policy/protected_files.rs | 78 ++++++++++++++++++++ crates/engine/src/tests/permission_policy.rs | 72 ++++++++++++++++++ crates/plugins/src/store.rs | 45 ++++++++++- docs/user-guide/assistant.md | 6 +- 10 files changed, 253 insertions(+), 24 deletions(-) create mode 100644 crates/engine/src/policy/protected_files.rs diff --git a/crates/engine/src/cmd/raster.rs b/crates/engine/src/cmd/raster.rs index 1d8aa43466..6c5818cdc6 100644 --- a/crates/engine/src/cmd/raster.rs +++ b/crates/engine/src/cmd/raster.rs @@ -87,7 +87,7 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_raster) .params(r#"{"layer"?, "brightness"?: -100..100, "contrast"?: -100..100, "gamma"?: 0.1..10}"#), - C::new("raster.setDefaultStyle", "Save as Default Raster Style", "Style › Rendering", set_default_style).roles(&[]).effects(crate::policy::Effects::NONE).view().params( + C::new("raster.setDefaultStyle", "Save as Default Raster Style", "Style › Rendering", set_default_style).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)).view().params( r#"{"fromLayer"?: bool (the active or named layer's colour ramp stretch; the settings apply to every raster added later that would be a grey stretch, opened files and analysis results alike), "layer"?, "ramp"?, "invert"?: bool, "stretch"?: "none"|"minMax"|"percentClip"|"standardDeviation"|"histogramEqualize", "low"?, "high"?: %, "n"?: deviations, "resampling"?: "nearest"|"bilinear", "reset"?: bool (back to the black-to-white grey stretch)}"#, ), C::new("raster.info", "Raster Information", "Data › Information", info).view().when(need_raster).roles(&[]).effects(crate::policy::Effects::NONE).params(r#"{"layer"?}"#), diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 2d4c70b9ee..3a6d81cd69 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -17,7 +17,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use super::exports::{Output, Parts}; -use super::ps; +use super::{InputSource, ps}; use crate::{CmdResult, CommandSpec as C, Session}; /// The kinds of share: (kind, extension, label). @@ -171,7 +171,7 @@ pub fn commands() -> Vec { .when(need_items) .params(r#"{"item"?: id|name (default: the last web layer), "layer"?: name|id of the layer replacing it (default: the one it was made from)}"#), C::new("share.dataStore", "Data Stores", "Publish › Manage", data_store).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(r#"{"name"?, "path"?: folder, "remove"?: name (no parameters: list them)}"#), - C::new("share.upload", "Upload File", "Publish › Manage", upload).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(r#"{"path": file, "store"?: name (default: the first data store)}"#), + C::new("share.upload", "Upload File", "Publish › Manage", upload).inputs(upload_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(r#"{"path": file, "store"?: name (default: the first data store)}"#), C::new("share.saveWebScene", "Save Web Scene", "Publish › Manage", |s, p| update_item(s, p, "webScene", ps(p, "map"))).inputs(update_web_scene_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).when(need_items).params(MANAGE), C::new("share.saveWebLinkChart", "Save Web Link Chart", "Publish › Manage", |s, p| update_item(s, p, "linkChart", ps(p, "relationship"))).inputs(update_links_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .when(need_items) @@ -567,24 +567,39 @@ fn data_store(s: &mut Session, p: &Value) -> CmdResult { Ok(json!({"stores": s.project.data_stores})) } -/// `share.upload`: copies a file into a data store, never over a file there. Refused where files -/// are downloaded. -fn upload(s: &mut Session, p: &Value) -> CmdResult { - if s.downloads_files() { +/// Resolves the same destination for approval and the upload itself. +fn upload_target(input: &super::InputContext<'_>, p: &Value) -> Result<(PathBuf, String), String> { + if input.downloads_files() { return Err("the web app can't copy files into a folder; upload files to a data store in the desktop app".into()); } let src = ps(p, "path").ok_or("path is required")?; - let file = Path::new(src).file_name().map(|n| n.to_string_lossy().into_owned()).ok_or("path must name a file")?; + let file = Path::new(src).file_name().ok_or("path must name a file")?; let store = match ps(p, "store") { - Some(n) => s.project.data_stores.iter().find(|d| d.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no data store '{n}'"))?, - None => s.project.data_stores.first().ok_or("register a data store first (Publish › Manage › Data Stores)")?, - } - .clone(); - usable(&store)?; - let dest = PathBuf::from(&store.path).join(&file); + Some(n) => { + input.project.data_stores.iter().find(|d| d.name.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no data store '{n}'"))? + } + None => input.project.data_stores.first().ok_or("register a data store first (Publish › Manage › Data Stores)")?, + }; + usable(store)?; + Ok((Path::new(&store.path).join(file.to_string_lossy().as_ref()), store.name.clone())) +} + +fn upload_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { + let (dest, name) = upload_target(input, p)?; + let mut inputs = super::Inputs::layers(std::iter::empty()); + inputs.review_places.push(dest.display().to_string()); + inputs.state = json!({"path": dest, "store": name}); + Ok(inputs) +} + +/// `share.upload`: copies a file into a data store, never over a file there. +fn upload(s: &mut Session, p: &Value) -> CmdResult { + let (dest, store) = upload_target(&s.input_context(), p)?; + let src = ps(p, "path").ok_or("path is required")?; + let file = dest.file_name().ok_or("path must name a file")?.to_string_lossy().into_owned(); // A file of that name in the store (another upload, or a share) is never overwritten. if dest.exists() { - return Err(format!("{} already has a file named {file}", store.name)); + return Err(format!("{store} already has a file named {file}")); } // create_new is the real guard (the check above only gives a clearer message): the file is // created new, never through an existing file or link. A copy that fails part way is removed, diff --git a/crates/engine/src/policy/decide.rs b/crates/engine/src/policy/decide.rs index 66f82d2617..eb13abe48d 100644 --- a/crates/engine/src/policy/decide.rs +++ b/crates/engine/src/policy/decide.rs @@ -39,11 +39,23 @@ fn kind(s: &Session, k: &Kind, node: &Node) -> Decision { } Kind::Assistant(access) => { let full = *access == AssistantAccess::Full; + if full && node.id().starts_with("connection.") && !node.effects.contains(Unreviewed) { + return Ask; + } + #[cfg(not(target_arch = "wasm32"))] + if full + && node.effects.contains(Files) + && !node.effects.contains(Unreviewed) + && super::protected_files::uses_protected_files(node) + { + return Ask; + } node.effects .iter() .map(|e| match e { Edits | History => Allow, - Files | Network | Plugin | Automation if full => Allow, + Files | Network | Plugin | Automation if full && !full_access_asks(node.id()) => Allow, + Files | Network if full => Ask, Reserved if full && full_access_runs(node.id()) => Allow, Files | Network => Remember, Plugin | Automation | Reserved | Replaces => Ask, @@ -197,6 +209,11 @@ fn refusal(s: &Session, k: &Kind, n: &Node) -> String { } } +/// Commands with file effects whose target is the session log or application settings. +fn full_access_asks(id: &str) -> bool { + matches!(id, "project.log" | "project.exportLog" | "sources.save" | "sources.favourite" | "sources.remove") +} + /// The `Reserved` commands the assistant's Full access runs without asking: they work with data, /// models and plugins already there. Every other one asks: installing, enabling or removing /// plugins and the GeoLibre runner, sign-ins, connections and their saved credentials, S3 listings diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 73d1aa6dd7..82996214c0 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -1203,6 +1203,7 @@ impl Session { effects, targets: Vec::new(), places: Vec::new(), + file_places: Vec::new(), display: Default::default(), children: Vec::new(), item: None, diff --git a/crates/engine/src/policy/mod.rs b/crates/engine/src/policy/mod.rs index 08836918a2..e8adefe5e9 100644 --- a/crates/engine/src/policy/mod.rs +++ b/crates/engine/src/policy/mod.rs @@ -9,6 +9,8 @@ pub use downloads::WINDOW_KEYS; mod effects; pub mod handler; mod plan; +#[cfg(not(target_arch = "wasm32"))] +mod protected_files; mod provenance; mod scope; diff --git a/crates/engine/src/policy/plan.rs b/crates/engine/src/policy/plan.rs index 3f85745a50..e957845f48 100644 --- a/crates/engine/src/policy/plan.rs +++ b/crates/engine/src/policy/plan.rs @@ -309,6 +309,7 @@ pub(crate) struct Node { pub(super) effects: Effects, pub(super) targets: Vec, pub(super) places: Vec, + pub(super) file_places: Vec, pub(super) display: ReviewDetail, pub(super) children: Vec, pub(super) item: Option<(&'static str, String, bool, Value)>, @@ -614,6 +615,7 @@ impl<'a> Builder<'a> { effects, targets: Vec::new(), places: Vec::new(), + file_places: Vec::new(), display: ReviewDetail { operation: String::new(), targets: Vec::new(), places: Vec::new() }, children: Vec::new(), item: None, @@ -878,7 +880,7 @@ impl<'a> Builder<'a> { self.charge(&(&inputs.layers, &inputs.maps, &inputs.tables, &inputs.future_layers))?; self.charge(&inputs.state)?; n.places.push(inputs.state); - n.display.places.extend(inputs.review_places); + n.file_places.extend(inputs.review_places); let uses_default = inputs.uses_default; for name in inputs.future_layers { if let Some(target) = self.symbol(&name) { @@ -1058,6 +1060,7 @@ impl<'a> Builder<'a> { _ => {} } } + n.display.places.splice(0..0, n.file_places.iter().cloned()); for value in n.display.targets.iter_mut().chain(n.display.places.iter_mut()) { *value = rustgis_data::diagnostics::Redacted::new(value).into_string(); } @@ -1410,7 +1413,9 @@ impl Plan { // Files, the internet, scripts and plugins don't ask at full access, so they aren't why. let explanation = match full_access { true if all.contains(Effect::Replaces) => (decide::reason(Effects::NONE.with(Effect::Replaces)), vec![]), - true => ("it changes plugins, connections, sign-ins, saved credentials or app settings", vec![]), + true => { + ("it uses a protected file or needs approval for plugins, connections, sign-ins, saved credentials or app settings", vec![]) + } false => self.root.explanation(all), }; let mut why = explanation.0.to_string(); diff --git a/crates/engine/src/policy/protected_files.rs b/crates/engine/src/policy/protected_files.rs new file mode 100644 index 0000000000..c84cdb35ec --- /dev/null +++ b/crates/engine/src/policy/protected_files.rs @@ -0,0 +1,78 @@ +//! Full access still asks before accessing app-managed files or files used to load a plugin. + +use super::{effects::PLACE_KEYS, plan::Node}; +use serde_json::Value; +use std::io::ErrorKind; +use std::path::{Component, Path, PathBuf}; + +pub(super) fn uses_protected_files(node: &Node) -> bool { + let mut paths = node.file_places.iter().map(String::as_str).collect::>(); + if !parameters(&node.params, &mut paths, 0) { + return true; + } + if paths.is_empty() { + return false; + } + + let Some(startup_paths) = rustgis_plugins::store::startup_paths() else { return true }; + let roots: Vec<_> = [rustgis_data::dirs::config_dir(), rustgis_data::dirs::app_data_dir(), rustgis_plugins::store::dir()] + .into_iter() + .flatten() + .chain(startup_paths) + .chain(rustgis_plugins::list().iter().filter_map(|plugin| plugin.dir().map(Path::to_path_buf))) + .collect(); + let Some(roots) = roots.iter().map(|path| resolved(path)).collect::>>() else { return true }; + + let needs_review = |path: &str| !path.is_empty() && touches_root(Path::new(path), &roots); + paths.into_iter().any(|path| needs_review(path) || (path.trim() != path && needs_review(path.trim()))) +} + +/// Check the location being opened and the directory holding its name. A link inside a +/// protected folder might point outside it, where its target can still affect the app. +fn touches_root(path: &Path, roots: &[PathBuf]) -> bool { + let Some(place) = resolved(path) else { return true }; + let parent = path.parent().and_then(resolved); + roots.iter().any(|root| place.starts_with(root) || parent.as_ref().is_some_and(|parent| parent.starts_with(root))) +} + +fn parameters<'a>(params: &'a Value, paths: &mut Vec<&'a str>, depth: usize) -> bool { + match params { + Value::Object(object) if depth < 16 => object.iter().all(|(key, value)| { + if !matches!(key.as_str(), "url" | "uri" | "connection") + && PLACE_KEYS.contains(&key.as_str()) + && let Some(path) = value.as_str() + { + paths.push(path); + } + parameters(value, paths, depth + 1) + }), + Value::Array(array) if depth < 16 => array.iter().all(|value| parameters(value, paths, depth + 1)), + Value::Object(_) | Value::Array(_) => false, + _ => true, + } +} + +/// Resolves existing ancestors and links. A dangling link, an unreadable path, or a missing +/// component followed by `..` needs a review. +fn resolved(path: &Path) -> Option { + let absolute = std::path::absolute(path).ok()?; + let mut path = absolute.as_path(); + let mut absent = Vec::new(); + loop { + match path.canonicalize() { + Ok(mut known) => { + known.extend(absent.into_iter().rev()); + return Some(known); + } + Err(error) if error.kind() == ErrorKind::NotFound => { + if std::fs::symlink_metadata(path).is_ok() { + return None; + } + let Component::Normal(name) = path.components().next_back()? else { return None }; + absent.push(name); + path = path.parent()?; + } + Err(_) => return None, + } + } +} diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index 7e07ee5c8d..d880ccbeed 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -2274,6 +2274,8 @@ fn permission_policy_assistant_full_access_still_asks() { ("plugin.prepare", json!({"id":"somebody/plugin"})), ("gp.installGeolibre", Value::Null), ("gp.setGeolibre", json!({"path":"geolibre"})), + ("connection.list", Value::Null), + ("connection.readSde", json!({"path":"office.sde"})), ("connection.new", json!({"kind":"wms","address":"https://example.com/wms"})), ("connection.login", json!({"id":"office","password":"hunter2"})), ("connection.forgetPassword", json!({"id":"office"})), @@ -2284,7 +2286,11 @@ fn permission_policy_assistant_full_access_still_asks() { ("s3.list", json!({"connection":"mine","bucket":"data"})), ("pg.connect", json!({"database":"host=localhost dbname=gis"})), ("extension.disable", json!({"id":"assistant"})), + ("project.log", Value::Null), + ("project.exportLog", json!({"path":"session.csv"})), ("project.logCommands", json!({"on":false})), + ("raster.setDefaultStyle", json!({"reset":true})), + ("sources.save", json!({"kind":"file","address":"cities.csv"})), ("project.new", Value::Null), ("project.open", json!({"path":"other.rgis"})), ]; @@ -2346,3 +2352,69 @@ fn permission_policy_assistant_full_access_reserved_commands() { s.registry.commands.push(crate::CommandSpec::new("test.unreviewed", "Unreviewed", "Test", |_, _| Ok(Value::Null))); assert!(matches!(s.review(&full, &Call::command("test.unreviewed", Value::Null)), Outcome::Refused(_))); } + +/// The upload destination is the data store, not the caller's source path. Full access must still +/// ask before a copy can put a file in the directory RustGIS loads plugins from. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn permission_policy_assistant_full_access_protects_plugin_files() { + if isolate_process_test("tests::permission_policy::permission_policy_assistant_full_access_protects_plugin_files") { + return; + } + let mut s = world(); + let dir = rustgis_plugins::store::dir().unwrap(); + let source_dir = dir.parent().unwrap().join(format!("rustgis-policy-copy-{}", std::process::id())); + let ordinary = source_dir.join("outputs"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&ordinary).unwrap(); + let source = source_dir.join("fixture.rgplugin"); + std::fs::write(&source, b"fixture").unwrap(); + s.run("share.dataStore", &json!({"name":"ordinary","path":ordinary})).unwrap(); + s.run("share.dataStore", &json!({"name":"protected","path":dir})).unwrap(); + let (full, _) = full_and_ask(35684); + let allowed = Call::command("share.upload", json!({"path":source,"store":"ordinary"})); + assert!(matches!(s.review(&full, &allowed), Outcome::Allowed)); + s.run_scoped(full.clone(), &allowed).unwrap(); + assert_eq!(std::fs::read(ordinary.join("fixture.rgplugin")).unwrap(), b"fixture"); + + let dest = dir.join("fixture.rgplugin"); + let protected = Call::command("share.upload", json!({"path":source,"store":"protected"})); + let approval = pending(&s, &full, &protected); + assert!(!approval.review().remember); + assert!(s.run_scoped(full.clone(), &protected).is_err()); + assert!(!dest.exists()); + s.run_permitted(full.clone(), approval.allow(), &protected).unwrap(); + assert_eq!(std::fs::read(dest).unwrap(), b"fixture"); + + let development = source_dir.join("development"); + std::fs::create_dir(&development).unwrap(); + std::fs::write(dir.join("state.json"), json!({"folders":[development]}).to_string()).unwrap(); + let development_export = Call::command("share.exportLayer", json!({"layer":"Cities","path":development.join("map.geojson")})); + pending(&s, &full, &development_export); + assert!(s.run_scoped(full.clone(), &development_export).is_err()); + + let path = dir.join("map.geojson"); + let protected_export = Call::command("share.exportLayer", json!({"layer":"Cities","path":path})); + pending(&s, &full, &protected_export); + assert!(s.run_scoped(full.clone(), &protected_export).is_err()); + + #[cfg(unix)] + { + let external = ordinary.join("external.geojson"); + std::fs::write(&external, b"fixture").unwrap(); + std::os::unix::fs::symlink(&external, dir.join("external.rgplugin")).unwrap(); + let linked_package = Call::command("share.exportLayer", json!({"layer":"Cities","path":external})); + pending(&s, &full, &linked_package); + assert!(s.run_scoped(full.clone(), &linked_package).is_err()); + assert_eq!(std::fs::read(&external).unwrap(), b"fixture"); + + let alias = ordinary.join("alias"); + std::os::unix::fs::symlink(&dir, &alias).unwrap(); + let alias_export = Call::command("share.exportLayer", json!({"layer":"Cities","path":alias.join("map.geojson")})); + pending(&s, &full, &alias_export); + assert!(s.run_scoped(full, &alias_export).is_err()); + } + assert!(!path.exists()); + std::fs::remove_dir_all(source_dir).unwrap(); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/plugins/src/store.rs b/crates/plugins/src/store.rs index 20660a85dc..769cddc39b 100644 --- a/crates/plugins/src/store.rs +++ b/crates/plugins/src/store.rs @@ -103,6 +103,46 @@ fn write_state(st: &State) -> Result<(), String> { rustgis_data::io::replace_atomic(&path, text.as_bytes()).map_err(|e| format!("{}: {e}", path.display())) } +fn package_path(path: &Path) -> bool { + path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("rgplugin")) +} + +/// Files and development folders used at startup. Permission checks use these paths even if +/// a package is a link or a development folder couldn't be loaded. `None` means the caller +/// should ask the user because the store could not be inspected within the inline budget. +pub fn startup_paths() -> Option> { + const MAX_INLINE_STATE_BYTES: u64 = 1 << 20; + const MAX_INLINE_ENTRIES: usize = 4096; + let Some(dir) = dir() else { return Some(Vec::new()) }; + let state_path = dir.join("state.json"); + let state = match std::fs::metadata(&state_path) { + Ok(metadata) if metadata.is_file() && metadata.len() <= MAX_INLINE_STATE_BYTES => read_state(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => State::default(), + _ => return None, + }; + if state.unreadable.is_some() { + return None; + } + let mut paths = vec![state_path, dir.join("blocklist.json"), dir.join("unpacked")]; + paths.extend(state.folders.into_iter().map(PathBuf::from)); + match std::fs::read_dir(&dir) { + Ok(entries) => { + for (index, entry) in entries.enumerate() { + if index >= MAX_INLINE_ENTRIES { + return None; + } + let path = entry.ok()?.path(); + if package_path(&path) { + paths.push(path); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, + } + Some(paths) +} + /// Loads every installed package and plugin folder (and the cached blocklist); returns what /// couldn't be loaded. pub fn load_installed() -> Vec { @@ -135,9 +175,8 @@ pub fn load_installed() -> Vec { )); return errors; } - let mut paths: Vec = std::fs::read_dir(&dir) - .map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("rgplugin"))).collect()) - .unwrap_or_default(); + let mut paths: Vec = + std::fs::read_dir(&dir).map(|rd| rd.flatten().map(|e| e.path()).filter(|p| package_path(p)).collect()).unwrap_or_default(); paths.sort(); // Folders after packages: a development copy wins over an installed one. paths.extend(st.folders.iter().map(PathBuf::from)); diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 9f91647a4c..163fe6918e 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -55,15 +55,15 @@ From the command line, `rustgis-cli ask` sends one request (see | Level | Runs without asking | Still asks | | --- | --- | --- | | **Ask** | Project edits | Files, the internet, SQL, scripts, tasks, notebooks, models, plugins and replacing the project | -| **Full access, for this session** | Also files, the internet, SQL, scripts, tasks, notebooks, models and installed plugins, and saving edits to a GeoPackage or PostGIS | Installing, enabling or removing plugins and the GeoLibre tools; connections, sign-ins and saved credentials; listing S3 buckets with a connection; extensions, the session log and other app settings; replacing the project | +| **Full access, for this session** | Also files, the internet, SQL, scripts, tasks, notebooks, models and installed plugins, and saving edits to a GeoPackage or PostGIS | Installing, enabling or removing plugins and the GeoLibre tools; connections, sign-ins and saved credentials; listing S3 buckets with a connection; extensions, the session log and other app settings; access to the app’s or installed plugins’ files; replacing the project | Full access is never saved: RustGIS always starts at **Ask**, and turning the assistant off also returns to it. While it is on, a warning above the message box and **Assistant: full access** in the status bar say so; **Back to Ask**, or a click on the status bar, ends it, from the assistant's next action on. Subagents work at the same level. -With full access nothing waits for you, so a layer or web page written to mislead the model can -have it overwrite files you can write to or send data out. Use it with data and models you trust, +With full access, a layer or web page written to mislead the model can have it overwrite data files +or send data out without asking. Use it with data and models you trust, and check what the conversation says it ran. What no level allows stays refused: external runners RustGIS hasn't reviewed, and anything but project edits from a task, notebook or model that came from a file or was made by an assistant, agent or plugin. From 80cfa8d2d1c55d478e4a585754f242154c8ba419 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 16:23:16 -0600 Subject: [PATCH 3/4] fix(assistant): enforce full access review boundaries --- crates/engine/src/cmd/gpkg.rs | 35 +++-- crates/engine/src/policy/decide.rs | 51 ++++--- crates/engine/src/policy/dispatch.rs | 66 +++++++-- crates/engine/src/policy/plan.rs | 113 ++++++++++----- crates/engine/src/policy/protected_files.rs | 71 +++++---- crates/engine/src/policy/scope.rs | 4 +- crates/engine/src/tests/permission_policy.rs | 143 +++++++++++++++++-- crates/ui-egui/src/assistant.rs | 2 +- crates/ui-egui/src/assistantpane.rs | 6 +- crates/ui-touch/src/assistant.rs | 110 ++++++++++---- crates/ui-touch/src/lib.rs | 9 +- docs/mcp.md | 2 + docs/user-guide/assistant.md | 41 +++--- 13 files changed, 487 insertions(+), 166 deletions(-) diff --git a/crates/engine/src/cmd/gpkg.rs b/crates/engine/src/cmd/gpkg.rs index a4f4236734..7eee067684 100644 --- a/crates/engine/src/cmd/gpkg.rs +++ b/crates/engine/src/cmd/gpkg.rs @@ -16,21 +16,38 @@ pub fn commands() -> Vec { ), C::new("gpkg.pendingEdits", "GeoPackage Edits", "Edit › Manage Edits", pending_edits).roles(&[]).effects(crate::policy::Effects::NONE).view() .params(r#"{"layer"?: "a layer added with gpkg.addLayer (default: the active one)"}"#), - C::new("gpkg.saveEdits", "Save to GeoPackage", "Edit › Manage Edits", save_edits).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)) + C::new("gpkg.saveEdits", "Save to GeoPackage", "Edit › Manage Edits", save_edits).inputs(edit_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)) .params(r#"{"layer"?: "a layer added with gpkg.addLayer (default: the active one)"}"#), - C::new("gpkg.discardEdits", "Discard GeoPackage Edits", "Edit › Manage Edits", discard_edits).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("gpkg.discardEdits", "Discard GeoPackage Edits", "Edit › Manage Edits", discard_edits).inputs(edit_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"layer"?: "a layer added with gpkg.addLayer (default: the active one)"}"#), ] } -fn gpkg_layer(s: &Session, p: &Value) -> Result<(u32, String, rustgis_map::source::GpkgEdit), String> { - let id = s.layer_id(p)?; - let l = s.map().layer(id).ok_or("no such layer")?; - let edit = l +fn selected_edit<'a>( + input: &super::InputContext<'a>, + p: &Value, +) -> Result<(&'a rustgis_map::Layer, &'a rustgis_map::source::GpkgEdit), String> { + let id = input.layer_id(p)?; + let layer = input.map().layer(id).ok_or("no such layer")?; + let edit = layer .gpkg - .clone() - .ok_or_else(|| format!("{}: not a GeoPackage layer loaded for editing (Home › Add Data › Edit GeoPackage Table…)", l.name))?; - Ok((id, l.name.clone(), edit)) + .as_ref() + .ok_or_else(|| format!("{}: not a GeoPackage layer loaded for editing (Home › Add Data › Edit GeoPackage Table…)", layer.name))?; + Ok((layer, edit)) +} + +/// Binds the stored file and table that save and discard actually open. +fn edit_inputs(input: &super::InputContext<'_>, p: &Value) -> Result { + let (layer, edit) = selected_edit(input, p)?; + let mut inputs = super::Inputs::layers([(input.map(), layer)]); + inputs.review_places.push(edit.path.clone()); + inputs.state = json!({"path": edit.path, "table": edit.table}); + Ok(inputs) +} + +fn gpkg_layer(s: &Session, p: &Value) -> Result<(u32, String, rustgis_map::source::GpkgEdit), String> { + let (layer, edit) = selected_edit(&super::InputSource::input_context(s), p)?; + Ok((layer.id, layer.name.clone(), edit.clone())) } fn pending_edits(s: &mut Session, p: &Value) -> CmdResult { diff --git a/crates/engine/src/policy/decide.rs b/crates/engine/src/policy/decide.rs index eb13abe48d..d81fc28519 100644 --- a/crates/engine/src/policy/decide.rs +++ b/crates/engine/src/policy/decide.rs @@ -12,11 +12,29 @@ pub(super) enum Decision { Ask, Deny, } +/// Lazily resolves protected roots once for all nodes checked in this decision. +#[derive(Default)] +pub(super) struct DecisionContext { + #[cfg(not(target_arch = "wasm32"))] + protected_roots: std::cell::OnceCell>>, +} + +impl DecisionContext { + fn file_access_needs_approval(&self, _node: &Node) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + super::protected_files::uses_protected_files(_node, &self.protected_roots) + } + #[cfg(target_arch = "wasm32")] + false + } +} + /// The one permission table. A new effect requires an explicit disposition here. -pub(super) fn decide(s: &Session, scope: &Scope, node: &Node) -> Result { +pub(super) fn decide(s: &Session, scope: &Scope, node: &Node, context: &DecisionContext) -> Result { // Base access refusal supplies actionable guidance even for an attached read-only caller. // An admitted operation still checks live settings and its captured load before any work. - let d = kind(s, &scope.kind, node); + let d = kind(s, &scope.kind, node, context); if d == Decision::Deny { return Err(refusal(s, &scope.kind, node)); } @@ -25,7 +43,7 @@ pub(super) fn decide(s: &Session, scope: &Scope, node: &Node) -> Result Decision { +fn kind(s: &Session, k: &Kind, node: &Node, context: &DecisionContext) -> Decision { use Decision::*; use Effect::*; match k { @@ -42,12 +60,7 @@ fn kind(s: &Session, k: &Kind, node: &Node) -> Decision { if full && node.id().starts_with("connection.") && !node.effects.contains(Unreviewed) { return Ask; } - #[cfg(not(target_arch = "wasm32"))] - if full - && node.effects.contains(Files) - && !node.effects.contains(Unreviewed) - && super::protected_files::uses_protected_files(node) - { + if full && node.effects.contains(Files) && !node.effects.contains(Unreviewed) && context.file_access_needs_approval(node) { return Ask; } node.effects @@ -103,7 +116,7 @@ fn kind(s: &Session, k: &Kind, node: &Node) -> Decision { Op::Tool(pin) => super::effects::imported("gp.run", &serde_json::json!({"tool":pin.spec().id,"params":node.params})), _ => super::effects::imported(node.id(), &node.params), }; - if own { Deny } else { kind(s, within, node) } + if own { Deny } else { kind(s, within, node, context) } } Kind::Plugin { pin, within } => { if is_plugin_blocked_database_command(node.id()) { @@ -126,14 +139,14 @@ fn kind(s: &Session, k: &Kind, node: &Node) -> Decision { // Approval of this plugin admits its manifest's host requests. Item restrictions // remain an intersection; the outer caller cannot grant an imported item authority. /// Retains imported-item restrictions inside an approved plugin manifest. - fn item(s: &Session, k: &Kind, n: &Node) -> Decision { + fn item(s: &Session, k: &Kind, n: &Node, context: &DecisionContext) -> Decision { match k { - Kind::Item { .. } => kind(s, k, n), - Kind::Plugin { within, .. } => item(s, within, n), + Kind::Item { .. } => kind(s, k, n, context), + Kind::Plugin { within, .. } => item(s, within, n, context), _ => Allow, } } - item(s, within, node) + item(s, within, node, context) } } } @@ -209,9 +222,13 @@ fn refusal(s: &Session, k: &Kind, n: &Node) -> String { } } -/// Commands with file effects whose target is the session log or application settings. +/// File effects targeting the log or settings, or SQL whose sources cannot be inferred from +/// a database parameter. fn full_access_asks(id: &str) -> bool { - matches!(id, "project.log" | "project.exportLog" | "sources.save" | "sources.favourite" | "sources.remove") + matches!( + id, + "project.log" | "project.exportLog" | "sources.save" | "sources.favourite" | "sources.remove" | "sql.query" | "layer.addSql" + ) } /// The `Reserved` commands the assistant's Full access runs without asking: they work with data, @@ -227,8 +244,6 @@ fn full_access_runs(id: &str) -> bool { | "layer.addDownload" | "model.new" | "model.save" - | "project.importGeolibre" - | "project.importQgis" | "plugin.list" | "plugin.registry" | "plugin.panel" diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 82996214c0..37c8bc3d03 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -1,7 +1,7 @@ use super::plan::OutputRef; use super::{ AssistantAccess, Call, Node, Outcome, Pending, Permit, PluginPin, Remembered, Scope, ToolPin, - decide::{self, Decision}, + decide::{Decision, DecisionContext}, plan::{CallKind, LayerKey, Op, Plan, Target}, scope::{Continuation, Kind, Narrow}, }; @@ -69,6 +69,11 @@ struct Cursor { made_layers: Vec, made_tables: Vec, } +/// Workflows the planner can expand before any of their steps run. +fn preflights_automation(node: &Node) -> bool { + matches!(node.id(), "script" | "script.run" | "task.run" | "notebook.run" | "model.run") +} + impl Session { /// Holds a plugin command at the pre-handler UI queue boundary, inheriting the current scope. /// A handler or approved composite must run its children synchronously through normal dispatch. @@ -439,19 +444,22 @@ impl Session { pub fn review(&self, scope: &Scope, call: &Call) -> Outcome { let result = (|| { let node = self.call_node(scope, call)?; - if node.decision(self, scope)? == Decision::Allow { - // A script, task, notebook or model that runs as a whole may hold a step that still - // asks: planned to find it, so it's shown now rather than refused partway. One too - // large to plan runs, and each of its steps is checked as it comes. - let step_asks = matches!(scope.kind, Kind::Assistant(_)) - && node.effects.contains(super::Effect::Automation) - && self.plan(scope, call).and_then(|p| p.decision(self, scope)).is_ok_and(|d| d != Decision::Allow); - if !step_asks { + let context = DecisionContext::default(); + let full_access = matches!(scope.kind, Kind::Assistant(AssistantAccess::Full)); + let (plan, decision) = if node.decision_with(self, scope, &context)? == Decision::Allow { + if !full_access || !preflights_automation(&node) { return Ok(Outcome::Allowed); } - } - let plan = self.plan(scope, call)?; - let decision = plan.decision(self, scope)?; + let Some((plan, decision)) = self.plan_full_access(scope, call, &context)? else { return Ok(Outcome::Allowed) }; + if decision == Decision::Allow { + return Ok(Outcome::Allowed); + } + (plan, decision) + } else { + let plan = self.plan(scope, call)?; + let decision = plan.root.decision_with(self, scope, &context)?; + (plan, decision) + }; /// Finds imports whose operations cannot be enumerated before external content is read. fn generated(n: &Node) -> Option<&str> { if n.generated { @@ -469,12 +477,22 @@ impl Session { } )); } - let full_access = matches!(scope.kind, Kind::Assistant(AssistantAccess::Full)); let review = plan.review(decision == Decision::Remember, full_access)?; Ok(Outcome::NeedsApproval(Pending { plan: Arc::new(plan), review: Box::new(review), request: call.request.clone() })) })(); result.unwrap_or_else(Outcome::Refused) } + /// Only the byte limit permits an otherwise allowed workflow to fall back to stage checks. + fn plan_full_access(&self, scope: &Scope, call: &Call, context: &DecisionContext) -> Result, String> { + match self.plan(scope, call) { + Ok(plan) => { + let decision = plan.root.decision_with(self, scope, context)?; + Ok(Some((plan, decision))) + } + Err(super::plan::PlanError::TooLarge) => Ok(None), + Err(error) => Err(error.into()), + } + } /// Consumes one displayed approval after checking its queued request identity. pub fn run_permitted(&mut self, scope: Scope, permit: Permit, call: &Call) -> CmdResult { if permit.request != call.request { @@ -484,6 +502,9 @@ impl Session { } /// Reuses consent only when the entire current operation equals the remembered plan. pub fn run_remembered(&mut self, scope: Scope, remembered: &Remembered, call: &Call) -> CmdResult { + if remembered.plan.decision(self, &scope)? != Decision::Remember { + return Err("this operation needs a new approval".into()); + } self.run_plan(scope, remembered.plan.clone(), call) } /// Replans before any effect and consumes ordered frozen nodes during execution. @@ -599,7 +620,22 @@ impl Session { /// Checks live authority, ordered operation, effective params and bound targets at each stage. fn admit(&mut self, mut node: Node) -> Result, String> { let scope = self.scope(); - let decision = node.decision(self, &scope)?; + let context = DecisionContext::default(); + let decision = node.decision_with(self, &scope, &context)?; + if self.policy.cursor.is_none() + && decision == Decision::Allow + && matches!(scope.kind, Kind::Assistant(AssistantAccess::Full)) + && preflights_automation(&node) + { + let call = match &node.op { + Op::Command(spec) => Call::command(spec.id, node.params.clone()), + Op::Adapter("script") => Call::script(node.params.get("script").and_then(Value::as_str).ok_or("script is required")?), + _ => return Err("this operation's steps cannot be planned".into()), + }; + if self.plan_full_access(&scope, &call, &context)?.is_some_and(|(_, decision)| decision != Decision::Allow) { + return Err("this operation needs your approval".into()); + } + } let current_sources = self .project .maps @@ -1214,7 +1250,7 @@ impl Session { fixed_tool: None, auth: None, }; - if decide::decide(self, &self.scope(), &node)? != Decision::Allow { + if node.decision(self, &self.scope())? != Decision::Allow { return Err("this host request needs approval".into()); } Ok(()) diff --git a/crates/engine/src/policy/plan.rs b/crates/engine/src/policy/plan.rs index e957845f48..3101b0faf6 100644 --- a/crates/engine/src/policy/plan.rs +++ b/crates/engine/src/policy/plan.rs @@ -1,6 +1,6 @@ use super::{ Effect, Effects, - decide::{self, Decision}, + decide::{self, Decision, DecisionContext}, scope::{Owner, Scope}, }; use crate::{CommandSpec, Session}; @@ -86,8 +86,34 @@ const MAX_DEPTH: usize = 4; const MAX_REVIEW: usize = 4_096; const MAX_PLAN_BYTES: usize = 64 * 1024; +pub(super) enum PlanError { + TooLarge, + Refused(String), +} + +impl From for PlanError { + fn from(why: String) -> Self { + Self::Refused(why) + } +} + +impl From<&str> for PlanError { + fn from(why: &str) -> Self { + Self::Refused(why.into()) + } +} + +impl From for String { + fn from(error: PlanError) -> Self { + match error { + PlanError::TooLarge => "this operation is too large to freeze for review; run it yourself or request fewer steps".into(), + PlanError::Refused(why) => why, + } + } +} + /// Measures serialized shape without allocating a second unbounded copy of hostile content. -fn bounded_size(value: &impl serde::Serialize, limit: usize) -> Result { +fn bounded_size(value: &impl serde::Serialize, limit: usize) -> Result { struct Size { bytes: usize, limit: usize, @@ -106,8 +132,12 @@ fn bounded_size(value: &impl serde::Serialize, limit: usize) -> Result {} + // Size is the writer's only I/O failure. + Err(error) if error.is_io() => return Err(PlanError::TooLarge), + Err(error) => return Err(PlanError::Refused(error.to_string())), + } Ok(size.bytes) } #[derive(Clone, PartialEq)] @@ -400,7 +430,7 @@ struct Builder<'a> { } impl Session { /// Expands a bounded ordered plan and binds project/defaults, namespaces and private identities. - pub(super) fn plan(&self, scope: &Scope, call: &Call) -> Result { + pub(super) fn plan(&self, scope: &Scope, call: &Call) -> Result { let mut b = Builder { s: self, selection: crate::cmd::InputSource::input_context(self).selection(), @@ -474,6 +504,7 @@ impl Session { dataset_outputs: Default::default(), } .call(scope, call) + .map_err(String::from) } /// Resolves one dispatch stage; only explicit approval planning expands automation recursively. pub(super) fn command_node(&self, id: &str, params: &Value) -> Result { @@ -494,6 +525,7 @@ impl Session { dataset_outputs: Default::default(), } .command(id, params, 0) + .map_err(String::from) } /// Resolves a single checked tool stage from its immutable runtime schema. pub(super) fn tool_node(&self, name: &str, params: &Value) -> Result { @@ -514,6 +546,7 @@ impl Session { dataset_outputs: Default::default(), } .tool(name, params) + .map_err(String::from) } } impl<'a> Builder<'a> { @@ -522,7 +555,7 @@ impl<'a> Builder<'a> { crate::cmd::InputContext::at(self.s, self.selection) } /// Records only actual targets/defaults as possible later default sources, never a namespace. - fn capture_source(&mut self, key: LayerKey) -> Result<(), String> { + fn capture_source(&mut self, key: LayerKey) -> Result<(), PlanError> { if !self.sources.iter().any(|(k, _)| *k == key) && let Some(layer) = key.get(self.s) { @@ -533,7 +566,7 @@ impl<'a> Builder<'a> { Ok(()) } /// The same raw layer selection as the executor, qualified by map and incarnation. - fn default_target(&mut self) -> Result { + fn default_target(&mut self) -> Result { let s = self.context(); let active = s.active_layer.and_then(|id| s.map().layer(id)).map(|l| LayerKey::of(s.map(), l)); let selected = @@ -547,7 +580,7 @@ impl<'a> Builder<'a> { Ok(Target::Default { active, selected }) } /// Shares execution parsing and whole-script refusal preflight with the approval planner. - fn call(&mut self, scope: &Scope, call: &Call) -> Result { + fn call(&mut self, scope: &Scope, call: &Call) -> Result { Ok(match &call.kind { CallKind::Command { id, params } => self.command(id, params, 0)?, CallKind::Script(script) => { @@ -588,14 +621,14 @@ impl<'a> Builder<'a> { }) } /// Charges borrowed content before freezing copies, including repeatedly expanded items. - fn charge(&mut self, value: &impl serde::Serialize) -> Result<(), String> { + fn charge(&mut self, value: &impl serde::Serialize) -> Result<(), PlanError> { if self.strict { self.bytes += bounded_size(value, MAX_PLAN_BYTES.saturating_sub(self.bytes))?; } Ok(()) } /// Bounds expanded operations and nesting before traversing another composite. - fn count(&mut self, depth: usize) -> Result<(), String> { + fn count(&mut self, depth: usize) -> Result<(), PlanError> { if self.strict && self.unresolved_transition { return Err("a later step follows a map change whose targets cannot be frozen; split the request or run it yourself".into()); } @@ -628,18 +661,21 @@ impl<'a> Builder<'a> { } } /// Parses each line through the execution parser and preserves its order in the plan. - fn script(&mut self, text: &str, depth: usize) -> Result, String> { + fn script(&mut self, text: &str, depth: usize) -> Result, PlanError> { crate::cmd::workflows::script_commands(text)? .into_iter() .map(|(line, id, p)| { - let mut node = self.command(&id, &p, depth + 1).map_err(|e| format!("line {line} ({id}): {e}"))?; + let mut node = self.command(&id, &p, depth + 1).map_err(|error| match error { + PlanError::Refused(why) => PlanError::Refused(format!("line {line} ({id}): {why}")), + PlanError::TooLarge => error, + })?; node.line = Some(line); Ok(node) }) .collect() } /// Captures a registration or plugin command, then expands only reviewed composite vehicles. - fn command(&mut self, id: &str, params: &Value, depth: usize) -> Result { + fn command(&mut self, id: &str, params: &Value, depth: usize) -> Result { self.count(depth)?; self.charge(params)?; if id.starts_with(rustgis_plugins::PREFIX) { @@ -735,11 +771,11 @@ impl<'a> Builder<'a> { Ok(n) } /// Captures a tool without symbolic wiring. - fn tool(&mut self, name: &str, params: &Value) -> Result { + fn tool(&mut self, name: &str, params: &Value) -> Result { self.tool_wired(name, params, Vec::new()) } /// Freezes effective defaults and explicit in-run output references before binding inputs. - fn tool_wired(&mut self, name: &str, params: &Value, wires: Vec) -> Result { + fn tool_wired(&mut self, name: &str, params: &Value, wires: Vec) -> Result { self.count(0)?; let pin = ToolPin::resolve(name)?; let params = pin.resolved.resolve_params(params)?; @@ -781,7 +817,7 @@ impl<'a> Builder<'a> { Ok(n) } /// Binds dataset identities through executor resolvers and keeps private places separate from review. - fn bind(&mut self, n: &mut Node, params: &Value, tool: Option<&rustgis_analysis::ToolSpec>) -> Result<(), String> { + fn bind(&mut self, n: &mut Node, params: &Value, tool: Option<&rustgis_analysis::ToolSpec>) -> Result<(), PlanError> { let reads = n.effects.iter().any(|e| matches!(e, Effect::Files | Effect::Network | Effect::Plugin)); let session = self.s; if reads { @@ -848,7 +884,7 @@ impl<'a> Builder<'a> { } else if let Some(&(producer, map)) = self.dataset_outputs.get(&name.to_ascii_lowercase()) { n.targets.push(Target::ProducedDataset { producer, map, name: name.into() }); } else if self.strict && !self.outputs.contains(&(self.context().map().instance_id(), name.to_ascii_lowercase())) { - return Err(format!("no layer or table named '{name}' and no earlier output")); + return Err(format!("no layer or table named '{name}' and no earlier output").into()); } else { n.targets.push(Target::MadeLayer { map: self.context().map().instance_id(), name: name.into() }); } @@ -872,7 +908,7 @@ impl<'a> Builder<'a> { let inputs = match inputs { Ok(inputs) => inputs, Err(_) if !self.strict => crate::cmd::Inputs::unresolved(), - Err(e) => return Err(e), + Err(e) => return Err(e.into()), }; if self.strict && inputs.unresolved { return Err("this operation's targets cannot be resolved before reading its file; run it yourself".into()); @@ -894,7 +930,7 @@ impl<'a> Builder<'a> { } else if self.outputs.contains(&(self.context().map().instance_id(), name.to_ascii_lowercase())) { n.targets.push(Target::MadeLayer { map: self.context().map().instance_id(), name }); } else if self.strict { - return Err(format!("no layer '{name}' and no earlier output")); + return Err(format!("no layer '{name}' and no earlier output").into()); } } for id in inputs.tables { @@ -962,7 +998,7 @@ impl<'a> Builder<'a> { .and_then(Value::as_str) .is_some_and(|n| self.table_outputs.contains(&n.to_ascii_lowercase())) => { - return Err(e); + return Err(e.into()); } Err(_) => { if let Some(name) = params.get("table").and_then(Value::as_str) { @@ -1105,7 +1141,7 @@ impl<'a> Builder<'a> { self.context().layer_id(params).ok().and_then(|id| self.context().map().layer(id)) } /// Uses Session's real name-before-id and numeric/default selector semantics. - fn layer_target_value(&self, value: &Value, reads: bool) -> Result { + fn layer_target_value(&self, value: &Value, reads: bool) -> Result { if let Some(t) = value.as_str().and_then(|name| self.symbol(name)) { return Ok(self.bound_symbol(t, reads)); } @@ -1117,12 +1153,13 @@ impl<'a> Builder<'a> { .as_str() .is_some_and(|n| self.outputs.contains(&(self.context().map().instance_id(), n.to_ascii_lowercase()))) => { - Err(error) + Err(error.into()) } // An id names a layer already there: its error is the resolver's (#3509). - Err(error) => { - value.as_str().map(|n| Target::MadeLayer { map: self.context().map().instance_id(), name: n.into() }).ok_or(error) - } + Err(error) => value + .as_str() + .map(|n| Target::MadeLayer { map: self.context().map().instance_id(), name: n.into() }) + .ok_or_else(|| error.into()), } } /// An approved rename retains the original incarnation and adds its source when later read. @@ -1141,7 +1178,7 @@ impl<'a> Builder<'a> { } } /// Freezes selected task/cell/model content and provenance with bounded cycle-aware expansion. - fn item(&mut self, n: &mut Node, id: &str, params: &Value, depth: usize) -> Result<(), String> { + fn item(&mut self, n: &mut Node, id: &str, params: &Value, depth: usize) -> Result<(), PlanError> { let kind = id.split('.').next().unwrap_or(""); let kind: &'static str = match kind { "task" => "task", @@ -1186,7 +1223,7 @@ impl<'a> Builder<'a> { .filter(|(i, _)| params.get("step").filter(|v| !v.is_null()).is_none_or(|v| v.as_u64() == Some(*i as u64))) { if st.command.starts_with("task.") { - return Err(format!("step {} would run another task", i + 1)); + return Err(format!("step {} would run another task", i + 1).into()); } n.children.push(self.command(&st.command, &st.params, depth + 1)?); } @@ -1254,7 +1291,7 @@ impl<'a> Builder<'a> { { OutputRef::ExistingTable(t.id) } else { - return Err(format!("no model input layer or table '{name}'")); + return Err(format!("no model input layer or table '{name}'").into()); }; outputs.insert(node.id.clone(), from); } @@ -1306,9 +1343,13 @@ impl<'a> Builder<'a> { impl Node { /// Checks every known child before a script's first irreversible operation, using one engine table. pub(super) fn decision(&self, s: &Session, scope: &Scope) -> Result { + self.decision_with(s, scope, &DecisionContext::default()) + } + + pub(super) fn decision_with(&self, s: &Session, scope: &Scope, context: &DecisionContext) -> Result { /// Visits ordered children under their content-bound item restriction. - fn visit(s: &Session, scope: &Scope, n: &Node) -> Result { - let own = decide::decide(s, scope, n); + fn visit(s: &Session, scope: &Scope, n: &Node, context: &DecisionContext) -> Result { + let own = decide::decide(s, scope, n, context); let mut d = Decision::Allow; let scope = if let Some((kind, name, false, _)) = &n.item { let mut scope = scope.clone(); @@ -1320,13 +1361,13 @@ impl Node { // Report the actual pinned child operation before its vehicle's broad effects. // Both decisions still finish before the vehicle's first effect. for c in &n.children { - let child = - visit(s, &scope, c).map_err(|e| c.line.map_or_else(|| e.clone(), |line| format!("line {line} ({}): {e}", c.id())))?; + let child = visit(s, &scope, c, context) + .map_err(|e| c.line.map_or_else(|| e.clone(), |line| format!("line {line} ({}): {e}", c.id())))?; d = d.max(child); } Ok(d.max(own?)) } - visit(s, scope, self) + visit(s, scope, self, context) } } impl Plan { @@ -1410,12 +1451,10 @@ impl Plan { n.children.iter().fold(n.effects, |e, c| e.union(all_effects(c))) } let all = all_effects(&self.root); - // Files, the internet, scripts and plugins don't ask at full access, so they aren't why. + // At full access, an effect alone may not explain why approval is needed. let explanation = match full_access { true if all.contains(Effect::Replaces) => (decide::reason(Effects::NONE.with(Effect::Replaces)), vec![]), - true => { - ("it uses a protected file or needs approval for plugins, connections, sign-ins, saved credentials or app settings", vec![]) - } + true => ("this operation needs approval at Full access", vec![]), false => self.root.explanation(all), }; let mut why = explanation.0.to_string(); diff --git a/crates/engine/src/policy/protected_files.rs b/crates/engine/src/policy/protected_files.rs index c84cdb35ec..322195765a 100644 --- a/crates/engine/src/policy/protected_files.rs +++ b/crates/engine/src/policy/protected_files.rs @@ -5,49 +5,66 @@ use serde_json::Value; use std::io::ErrorKind; use std::path::{Component, Path, PathBuf}; -pub(super) fn uses_protected_files(node: &Node) -> bool { - let mut paths = node.file_places.iter().map(String::as_str).collect::>(); - if !parameters(&node.params, &mut paths, 0) { +pub(super) fn uses_protected_files(node: &Node, roots: &std::cell::OnceCell>>) -> bool { + let mut paths = node.file_places.iter().map(String::as_str).filter(|path| !path.trim().is_empty()).collect::>(); + if !parameters(&node.params, &mut paths, false, 0) || !paths.iter().any(|path| !path.contains("://")) { return true; } - if paths.is_empty() { - return false; - } - let Some(startup_paths) = rustgis_plugins::store::startup_paths() else { return true }; - let roots: Vec<_> = [rustgis_data::dirs::config_dir(), rustgis_data::dirs::app_data_dir(), rustgis_plugins::store::dir()] + let Some(roots) = roots.get_or_init(protected_roots) else { return true }; + paths.into_iter().any(|path| { + let trimmed = path.trim(); + touches_root(Path::new(path), roots) + || (trimmed != path && touches_root(Path::new(trimmed), roots)) + || trimmed.strip_prefix("file://").is_some_and(|path| touches_root(Path::new(path), roots)) + }) +} + +fn protected_roots() -> Option> { + let startup_paths = rustgis_plugins::store::startup_paths()?; + [rustgis_data::dirs::config_dir(), rustgis_data::dirs::app_data_dir(), rustgis_plugins::store::dir()] .into_iter() .flatten() .chain(startup_paths) .chain(rustgis_plugins::list().iter().filter_map(|plugin| plugin.dir().map(Path::to_path_buf))) - .collect(); - let Some(roots) = roots.iter().map(|path| resolved(path)).collect::>>() else { return true }; - - let needs_review = |path: &str| !path.is_empty() && touches_root(Path::new(path), &roots); - paths.into_iter().any(|path| needs_review(path) || (path.trim() != path && needs_review(path.trim()))) + .try_fold(Vec::new(), |mut roots, path| { + let absolute = std::path::absolute(&path).ok()?; + let resolved = resolved(&absolute)?; + if absolute != resolved { + roots.push(absolute); + } + roots.push(resolved); + Some(roots) + }) } -/// Check the location being opened and the directory holding its name. A link inside a -/// protected folder might point outside it, where its target can still affect the app. +/// A path can enter a protected folder and leave again through a link. Check its spelling +/// as well as the resolved location and its existing ancestors. fn touches_root(path: &Path, roots: &[PathBuf]) -> bool { - let Some(place) = resolved(path) else { return true }; - let parent = path.parent().and_then(resolved); - roots.iter().any(|root| place.starts_with(root) || parent.as_ref().is_some_and(|parent| parent.starts_with(root))) + let Ok(absolute) = std::path::absolute(path) else { return true }; + let under_root = |place: &Path| roots.iter().any(|root| place.starts_with(root)); + if under_root(&absolute) { + return true; + } + let Some(place) = resolved(&absolute) else { return true }; + under_root(&place) || absolute.ancestors().skip(1).filter_map(|parent| parent.canonicalize().ok()).any(|parent| under_root(&parent)) } -fn parameters<'a>(params: &'a Value, paths: &mut Vec<&'a str>, depth: usize) -> bool { +fn parameters<'a>(params: &'a Value, paths: &mut Vec<&'a str>, named: bool, depth: usize) -> bool { match params { Value::Object(object) if depth < 16 => object.iter().all(|(key, value)| { - if !matches!(key.as_str(), "url" | "uri" | "connection") - && PLACE_KEYS.contains(&key.as_str()) - && let Some(path) = value.as_str() - { - paths.push(path); - } - parameters(value, paths, depth + 1) + let named = PLACE_KEYS.iter().any(|place| place.eq_ignore_ascii_case(key)) + && !["url", "uri", "connection"].iter().any(|remote| remote.eq_ignore_ascii_case(key)); + parameters(value, paths, named, depth + 1) }), - Value::Array(array) if depth < 16 => array.iter().all(|value| parameters(value, paths, depth + 1)), + Value::Array(array) if depth < 16 => array.iter().all(|value| parameters(value, paths, named, depth + 1)), Value::Object(_) | Value::Array(_) => false, + Value::String(path) => { + if !path.trim().is_empty() && (named || crate::cmd::items::looks_like_path(path)) { + paths.push(path); + } + true + } _ => true, } } diff --git a/crates/engine/src/policy/scope.rs b/crates/engine/src/policy/scope.rs index fa8628a46b..83e28276ac 100644 --- a/crates/engine/src/policy/scope.rs +++ b/crates/engine/src/policy/scope.rs @@ -206,9 +206,9 @@ impl Pending { pub fn remember(&self) -> Option { self.review.remember.then(|| Remembered { plan: self.plan.clone() }) } - /// Compares the complete raw plan, independently of the queued request id. + /// Reuses an exact remembered plan only when this review still offers remembered consent. pub fn covered_by(&self, remembered: &Remembered) -> bool { - self.plan == remembered.plan + self.review.remember && self.plan == remembered.plan } } /// Engine-owned authority for an already authorized operation. Never reconstructed from JSON. diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index d880ccbeed..91ceee5aaf 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -2211,7 +2211,7 @@ fn full_and_ask(id: u64) -> (Scope, Scope) { (ask.clone().with_access(AssistantAccess::Full), ask) } -/// Full access runs files, the internet, SQL, scripts, tasks and installed plugins without a +/// Full access runs ordinary file and web operations, scripts, tasks and installed plugins without a /// review; the default still asks for each, and remembers only files and the internet. #[cfg(not(target_arch = "wasm32"))] #[test] @@ -2231,7 +2231,6 @@ fn permission_policy_assistant_full_access_runs_what_ask_waits_for() { let calls = [ (Call::command("share.exportLayer", json!({"layer":"Cities","path":path})), true), (Call::command("map.addTiles", json!({"url":"https://example.com/{z}/{x}/{y}.png"})), true), - (Call::command("sql.query", json!({"sql":"SELECT 1"})), true), (Call::command("script.run", json!({"script":"select.clear"})), false), (Call::command("task.run", json!({"task":"Export cities"})), false), (Call::command("plugin:policy-full-plugin/h", Value::Null), false), @@ -2245,7 +2244,7 @@ fn permission_policy_assistant_full_access_runs_what_ask_waits_for() { s.run_scoped(full.clone(), &calls[0].0).unwrap(); assert!(std::fs::metadata(&path).unwrap().len() > 0); std::fs::remove_file(&path).unwrap(); - s.run_scoped(full.clone(), &calls[4].0).unwrap(); + s.run_scoped(full.clone(), &calls[3].0).unwrap(); assert!(std::fs::metadata(&path).unwrap().len() > 0, "a task of the user's own runs through"); // A task from a file keeps to project edits at any level. s.run("task.new", &json!({"name":"From a file","imported":true,"steps":[step]})).unwrap(); @@ -2260,6 +2259,65 @@ fn permission_policy_assistant_full_access_runs_what_ask_waits_for() { rustgis_plugins::unload("policy-full-plugin"); } +#[test] +fn permission_policy_assistant_full_access_refuses_unplannable_task_before_its_first_step() { + let mut s = world(); + s.run( + "task.new", + &json!({"name":"Two steps","steps":[ + {"title":"Rename","command":"layer.rename","params":{"layer":"Cities","name":"Renamed"}}, + {"title":"Run task","command":"task.run","params":{}} + ]}), + ) + .unwrap(); + let (full, ask) = full_and_ask(35685); + let call = Call::command("task.run", json!({"task":"Two steps"})); + for scope in [full.clone(), ask] { + let Outcome::Refused(why) = s.review(&scope, &call) else { panic!("the task must be refused before execution") }; + assert!(why.contains("step 2 would run another task"), "{why}"); + } + assert!(s.run_scoped(full, &call).unwrap_err().contains("step 2 would run another task")); + assert!(s.map().layer_by_name("Cities").is_some()); + assert!(s.map().layer_by_name("Renamed").is_none()); +} + +#[test] +fn permission_policy_assistant_full_access_can_run_an_oversized_plan_step_by_step() { + let mut s = world(); + let (full, ask) = full_and_ask(35690); + let script = format!("# {}\nlayer.rename {{\"layer\":\"Cities\",\"name\":\"Renamed\"}}", "a".repeat(70 * 1024)); + let call = Call::command("script.run", json!({"script":script})); + assert!(matches!(s.review(&ask, &call), Outcome::Refused(why) if why.contains("too large to freeze"))); + assert!(matches!(s.review(&full, &call), Outcome::Allowed)); + s.run_scoped(full, &call).unwrap(); + assert!(s.map().layer_by_name("Renamed").is_some()); +} + +#[test] +fn permission_policy_assistant_full_access_refuses_generated_imports() { + let mut s = world(); + let (full, ask) = full_and_ask(35686); + for (id, params) in [("project.importQgis", json!({"text":""})), ("project.importGeolibre", json!({"text":"{}"}))] { + let call = Call::command(id, params); + for scope in [&full, &ask] { + let Outcome::Refused(why) = s.review(scope, &call) else { panic!("{id} must be imported by the user") }; + assert!(why.contains("import it yourself"), "{why}"); + } + assert!(s.run_scoped(full.clone(), &call).unwrap_err().contains("approval"), "{id}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn permission_policy_assistant_full_access_asks_about_unidentified_file_paths() { + let mut s = world(); + let (full, _) = full_and_ask(35687); + let call = Call::command("layout.publication", json!({"coverage":"coverage.png"})); + let approval = pending(&s, &full, &call); + assert!(!approval.review().remember); + assert!(s.run_scoped(full, &call).unwrap_err().contains("approval")); +} + /// What full access still asks about, never remembered: installs, sign-ins and saved credentials, /// app settings and replacing the project, also as a line of a script or a step of a task. #[test] @@ -2286,6 +2344,8 @@ fn permission_policy_assistant_full_access_still_asks() { ("s3.list", json!({"connection":"mine","bucket":"data"})), ("pg.connect", json!({"database":"host=localhost dbname=gis"})), ("extension.disable", json!({"id":"assistant"})), + ("sql.query", json!({"sql":"SELECT 1"})), + ("layer.addSql", json!({"sql":"SELECT 1", "database":"ordinary.duckdb"})), ("project.log", Value::Null), ("project.exportLog", json!({"path":"session.csv"})), ("project.logCommands", json!({"on":false})), @@ -2302,7 +2362,11 @@ fn permission_policy_assistant_full_access_still_asks() { for call in [direct, Call::script(&line), in_script] { let asked = pending(&s, &full, &call); assert!(!asked.review().remember, "{id}"); - let why = if id.starts_with("project.new") || id == "project.open" { "replaces the open project" } else { "sign-ins" }; + let why = if id.starts_with("project.new") || id == "project.open" { + "replaces the open project" + } else { + "needs approval at Full access" + }; assert!(asked.review().why.contains(why), "{id}: {}", asked.review().why); assert!(s.run_scoped(full.clone(), &call).is_err(), "{id} ran without its approval"); } @@ -2337,22 +2401,69 @@ fn permission_policy_assistant_full_access_reserved_commands() { assert_eq!( runs, [ + #[cfg(target_arch = "wasm32")] "gpkg.saveEdits", + #[cfg(target_arch = "wasm32")] "layer.addDownload", + #[cfg(target_arch = "wasm32")] "model.new", "model.save", + #[cfg(target_arch = "wasm32")] "pg.saveEdits", "plugin.list", "plugin.panel", + #[cfg(target_arch = "wasm32")] "plugin.registry", - "project.importGeolibre", - "project.importQgis", ] ); s.registry.commands.push(crate::CommandSpec::new("test.unreviewed", "Unreviewed", "Test", |_, _| Ok(Value::Null))); assert!(matches!(s.review(&full, &Call::command("test.unreviewed", Value::Null)), Outcome::Refused(_))); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn permission_policy_assistant_full_access_checks_path_leaves() { + let mut s = world(); + s.registry.commands.push( + crate::CommandSpec::new("test.fileLeaves", "File leaves", "Test", |_, _| Ok(Value::Null)) + .effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + .view(), + ); + let (full, _) = full_and_ask(35688); + let ordinary = std::env::temp_dir().join("rustgis-policy-fixture.png"); + let protected = rustgis_plugins::store::dir().unwrap().join("rustgis-policy-fixture.png"); + for params in [json!({"coverage":protected}), json!({"paths":[ordinary, protected]})] { + let call = Call::command("test.fileLeaves", params); + assert!(!pending(&s, &full, &call).review().remember); + assert!(s.run_scoped(full.clone(), &call).is_err()); + } + assert!(matches!(s.review(&full, &Call::command("test.fileLeaves", json!({"paths":[ordinary]}))), Outcome::Allowed)); +} + +#[cfg(unix)] +#[test] +fn permission_policy_assistant_full_access_checks_protected_path_ancestors() { + if isolate_process_test("tests::permission_policy::permission_policy_assistant_full_access_checks_protected_path_ancestors") { + return; + } + let s = world(); + let protected = rustgis_plugins::store::dir().unwrap(); + let ordinary = std::env::temp_dir().join(format!("rustgis-policy-ordinary-{}", std::process::id())); + std::fs::create_dir_all(&protected).unwrap(); + std::fs::create_dir_all(ordinary.join("maps")).unwrap(); + std::os::unix::fs::symlink(&ordinary, protected.join("assets")).unwrap(); + let (full, _) = full_and_ask(35689); + let export = |path| Call::command("share.exportLayer", json!({"layer":"Cities","path":path})); + let inside = export(protected.join("assets/maps/output.geojson")); + let outside = export(ordinary.join("maps/output.geojson")); + let decision = s.review(&full, &inside); + let ordinary_decision = s.review(&full, &outside); + std::fs::remove_dir_all(protected).unwrap(); + std::fs::remove_dir_all(ordinary).unwrap(); + assert!(matches!(decision, Outcome::NeedsApproval(_))); + assert!(matches!(ordinary_decision, Outcome::Allowed)); +} + /// The upload destination is the data store, not the caller's source path. Full access must still /// ask before a copy can put a file in the directory RustGIS loads plugins from. #[cfg(not(target_arch = "wasm32"))] @@ -2371,7 +2482,7 @@ fn permission_policy_assistant_full_access_protects_plugin_files() { std::fs::write(&source, b"fixture").unwrap(); s.run("share.dataStore", &json!({"name":"ordinary","path":ordinary})).unwrap(); s.run("share.dataStore", &json!({"name":"protected","path":dir})).unwrap(); - let (full, _) = full_and_ask(35684); + let (full, ask) = full_and_ask(35684); let allowed = Call::command("share.upload", json!({"path":source,"store":"ordinary"})); assert!(matches!(s.review(&full, &allowed), Outcome::Allowed)); s.run_scoped(full.clone(), &allowed).unwrap(); @@ -2386,6 +2497,19 @@ fn permission_policy_assistant_full_access_protects_plugin_files() { s.run_permitted(full.clone(), approval.allow(), &protected).unwrap(); assert_eq!(std::fs::read(dest).unwrap(), b"fixture"); + for (folder, name) in [(&ordinary, "Ordinary"), (&dir, "Protected")] { + let path = folder.join("cities.gpkg"); + s.run("share.exportLayer", &json!({"layer":"Cities","path":path})).unwrap(); + s.run("gpkg.addLayer", &json!({"path":path,"name":name})).unwrap(); + } + for id in ["gpkg.saveEdits", "gpkg.discardEdits"] { + let ordinary = Call::command(id, json!({"layer":"Ordinary"})); + assert!(matches!(s.review(&full, &ordinary), Outcome::Allowed), "{id}"); + let protected = Call::command(id, json!({"layer":"Protected"})); + pending(&s, &full, &protected); + assert!(s.run_scoped(full.clone(), &protected).is_err(), "{id}"); + } + let development = source_dir.join("development"); std::fs::create_dir(&development).unwrap(); std::fs::write(dir.join("state.json"), json!({"folders":[development]}).to_string()).unwrap(); @@ -2395,7 +2519,10 @@ fn permission_policy_assistant_full_access_protects_plugin_files() { let path = dir.join("map.geojson"); let protected_export = Call::command("share.exportLayer", json!({"layer":"Cities","path":path})); - pending(&s, &full, &protected_export); + let remembered = pending(&s, &ask, &protected_export).remember().unwrap(); + assert!(pending(&s, &ask, &protected_export).covered_by(&remembered)); + assert!(!pending(&s, &full, &protected_export).covered_by(&remembered)); + assert!(s.run_remembered(full.clone(), &remembered, &protected_export).is_err()); assert!(s.run_scoped(full.clone(), &protected_export).is_err()); #[cfg(unix)] diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 54ab9a670e..46d10dd619 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -304,7 +304,7 @@ pub fn access_explanation(access: AssistantAccess) -> &'static str { } #[cfg(not(target_arch = "wasm32"))] AssistantAccess::Full => tl!( - "Files, the internet, SQL, scripts and installed plugins run without asking. It still asks before installing plugins, changing connections, sign-ins, saved credentials or app settings, and replacing the project. It lasts until RustGIS closes." + "The assistant can use files, the internet, scripts and installed plugins without asking. It still asks about protected or unidentified file paths, SQL queries, plugin installs, connections, sign-ins, saved credentials, app settings and replacing the project. It lasts until RustGIS closes." ), #[cfg(target_arch = "wasm32")] AssistantAccess::Full => tl!( diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index e79b385f96..3d68231a5e 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -733,6 +733,7 @@ fn access_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { let held = assistant::access(app); let mut chosen = held; let mine = tl!("For the assistant in this pane. Connected agents and agent windows keep their own settings."); + let explain = |level| crate::i18n::fmt("{access}\n{scope}", &[("access", assistant::access_explanation(level)), ("scope", mine)]); ui.horizontal(|ui| { let label = ui.label(RichText::new(tl!("Access")).small().color(t.text_dim)).on_hover_text(mine); let name = assistant::access_choices().into_iter().find(|(a, _)| *a == held).map_or("", |(_, name)| name); @@ -742,13 +743,12 @@ fn access_row(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .truncate() .show_ui(ui, |ui| { for (level, name) in assistant::access_choices() { - let explained = format!("{}\n{mine}", assistant::access_explanation(level)); - ui.selectable_value(&mut chosen, level, name).on_hover_text(explained); + ui.selectable_value(&mut chosen, level, name).on_hover_text(explain(level)); } }) .response .labelled_by(label.id) - .on_hover_text(format!("{}\n{mine}", assistant::access_explanation(held))); + .on_hover_text(explain(held)); }); if held == AssistantAccess::Full { egui::Frame::NONE.fill(t.red.gamma_multiply(0.12)).corner_radius(6).inner_margin(6).stroke(egui::Stroke::new(1.0, t.red)).show( diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index 510b4e35be..ae8a9a08a1 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -147,10 +147,13 @@ pub(crate) fn prepare(app: &mut RustGisApp, ctx: &egui::Context) { } } -/// Whether the strip shows: the Assistant works (or a message waits for its key) and its sheet -/// isn't up. +/// Shows activity or the Full access warning while the Assistant's sheet is closed. pub(crate) fn strip_shown(app: &RustGisApp, ctx: &egui::Context) -> bool { - on(app) && sheet(ctx) != Sheet::Assistant && (app.assistant.busy() || app.assistant.waiting_to_send()) + on(app) && sheet(ctx) != Sheet::Assistant && (working(app) || assistant::access(app) == AssistantAccess::Full) +} + +fn working(app: &RustGisApp) -> bool { + app.assistant.busy() || app.assistant.waiting_to_send() } /// The message `input` with the system's text field's part of it, `was`, now `text`. The field @@ -228,9 +231,12 @@ pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec {} Setup::Reading => { @@ -306,7 +308,12 @@ pub(crate) fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { ui.label(RichText::new(tl!("Reading the Assistant's settings…")).size(15.0).color(t.text_dim)); }); } - _ if settings => settings_form(app, ui, t, &mut state), + _ if settings => { + if assistant::access(app) == AssistantAccess::Full { + full_access(app, ui, t); + } + settings_form(app, ui, t, &mut state); + } _ => conversation(app, ui, t, &mut state), } set_chat(&ctx, state); @@ -377,6 +384,17 @@ fn access_chips(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); } +const COMPOSER_MARGIN: egui::Margin = egui::Margin::symmetric(0, 4); + +fn composer_height(spacing: f32) -> f32 { + 2.0 * TARGET + spacing + COMPOSER_MARGIN.sum().y +} + +/// Leaves room for the heading, a scrollable conversation row and both composer rows. +pub(crate) fn minimum_sheet_height(spacing: f32) -> f32 { + 2.0 * (TARGET + spacing) + composer_height(spacing) + 2.0 * super::SHEET_MARGIN +} + /// The conversation, with the approval waiting or the typing bar under it. fn conversation(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { let approval = assistant::pending(app); @@ -395,26 +413,40 @@ fn conversation(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) // The foot first, so the messages take what is left above it. // Its first frame is already as tall as the typing bar with the access chips over it, so // Send is in sight at once. - let typing_height = 2.0 * TARGET + ui.spacing().item_spacing.y + 8.0; - let foot = egui::Panel::bottom("touch_assistant_foot").frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4))); - foot.default_size(typing_height).show(ui, |ui| match &approval { + let foot = egui::Panel::bottom("touch_assistant_foot").frame(egui::Frame::NONE.inner_margin(COMPOSER_MARGIN)); + foot.default_size(composer_height(ui.spacing().item_spacing.y)).show(ui, |ui| match &approval { Some(approval) => card(app, ui, t, state, approval, room), None => typing(app, ui, t, state), }); - egui::ScrollArea::vertical().id_salt("touch_assistant_messages").auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); - messages(app, ui, t); - if assistant::can_continue(app) { - let ctx = ui.ctx().clone(); - if action(ui, t, tl!("Continue"), ui.available_width(), true, true) { - assistant::resume(app, false, &ctx); + // Keep the warning in view when there is room. In a short sheet it scrolls with the + // conversation, leaving both rows of the composer reachable. + let full = assistant::access(app) == AssistantAccess::Full; + let show_warning_here = full && ui.available_height() >= 2.0 * TARGET; + if show_warning_here { + full_access(app, ui, t); + } + egui::ScrollArea::vertical() + .id_salt("touch_assistant_messages") + .min_scrolled_height(0.0) + .auto_shrink([false, false]) + .stick_to_bottom(true) + .show(ui, |ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); + messages(app, ui, t); + if assistant::can_continue(app) { + let ctx = ui.ctx().clone(); + if action(ui, t, tl!("Continue"), ui.available_width(), true, true) { + assistant::resume(app, false, &ctx); + } + let limited = app.assistant.config().is_some_and(|c| c.pause_after().is_some()); + if limited && action(ui, t, tl!("Continue and don't pause again"), ui.available_width(), false, true) { + assistant::resume(app, true, &ctx); + } } - let limited = app.assistant.config().is_some_and(|c| c.pause_after().is_some()); - if limited && action(ui, t, tl!("Continue and don't pause again"), ui.available_width(), false, true) { - assistant::resume(app, true, &ctx); + if full && !show_warning_here { + full_access(app, ui, t); } - } - }); + }); } /// The conversation's messages, oldest first; the reply arriving, as it streams in. @@ -1507,6 +1539,34 @@ mod tests { assert_eq!((sheet(&held.ctx), height(&held.ctx)), (Sheet::Assistant, Height::Half)); } + #[test] + fn a_short_full_access_sheet_keeps_send_reachable() { + let mut held = Held::new(); + held.screen = Vec2::new(800.0, 360.0); + provider(&mut held, "custom", "test"); + let requests = answering(&mut held, vec![say("Sent.")]); + raise(&held.ctx, Height::Half); + assistant::set_access(&mut held.app, AssistantAccess::Full); + held.app.assistant.input = "Describe the map".into(); + let send = held.find("Send").expect("Send in sight").center(); + held.touch(&[send]); + assert_eq!(*requests.lock().unwrap(), 1); + } + + #[test] + fn the_idle_closed_sheet_warns_about_full_access() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + assistant::set_access(&mut held.app, AssistantAccess::Full); + set_sheet(&held.ctx, Sheet::None); + const WARNING: &str = "Full access: the assistant acts without asking."; + assert!(held.find(WARNING).is_some()); + let back = held.find("Back to Ask").expect("the way back").center(); + held.touch(&[back]); + assert_eq!(assistant::access(&held.app), AssistantAccess::Ask); + assert!(held.find(WARNING).is_none()); + } + /// The phone's choice of access: two chips over the message box, and while it is full a line /// under the heading with the way back. An export that would ask runs at full access. #[test] diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 5f0dab846b..b44ff85b0d 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -181,7 +181,7 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { egui::ScrollArea::horizontal().show(ui, |ui| ui.horizontal_centered(|ui| app.background_status(ui))); }); } - // The Assistant working with its sheet lowered: what it is doing, and Stop. + // The Assistant’s activity or Full access warning with its sheet closed. if assistant::strip_shown(app, &ctx) { let margin = egui::Margin::symmetric(12, 0); egui::Panel::bottom("touch_assistant_strip") @@ -219,9 +219,12 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { let groups = if shown == Sheet::More { MORE_GROUPS } else { 0 }; let wanted = (rows + 1) as f32 * (TARGET + spacing) + groups as f32 * (GROUP + spacing) + 2.0 * SHEET_MARGIN; let share = if ctx.egui_wants_keyboard_input() { TYPING_SHARE } else { SHEET_SHARE }; + let available = ui.available_height(); let height = match shown { - Sheet::Assistant => ui.available_height() * assistant::height(&ctx).share().max(share), - _ => wanted.min(ui.available_height() * share), + Sheet::Assistant => { + (available * assistant::height(&ctx).share().max(share)).max(assistant::minimum_sheet_height(spacing)).min(available) + } + _ => wanted.min(available * share), }; let margin = egui::Margin::symmetric(8, SHEET_MARGIN as i8); egui::Panel::bottom("touch_sheet").resizable(false).exact_size(height).frame(frame.inner_margin(margin)).show( diff --git a/docs/mcp.md b/docs/mcp.md index 8d387ebf92..36da20dcc1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -142,6 +142,8 @@ existing synchronous execution contract; this does not move their child commands Notebook cells, task steps and Script pane scripts validate reload and repair inline on the window thread, without reload status or cancellation during validation. File and network commands need `--yes`, unless **Let your Agents Control RustGIS** is ticked. +The default raster style (`raster.setDefaultStyle`) is an app-wide setting. Changing it requires +the attached agent to use the relay's own token with **Full access** enabled. Without **Full access**, an attached agent cannot replace the open project: `project.new`, `project.open`, `project.openText`, `project.sample` and `project.fromTemplate` diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 163fe6918e..8ebf12132f 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -18,11 +18,10 @@ Each step it takes shows in the conversation (click one to see its parameters an It can run several commands in one step, which one Ctrl+Z takes back together. Project edits use the usual undo history, so Ctrl+Z takes them back; undo does not remove exported files or reverse actions outside the project. Check the tool results and map rather than relying only on the -model's reply. At **Ask** access (the default, see [below](#access)), commands that would read or -write files, connect to -an address on the internet, run a plugin, script, task or model, or replace the project wait -for you: **Allow** or **Decline**. SQL queries also ask, because SQL can access files and the -network. **Don't ask again for exactly this action** remembers the exact command and all +model's reply. At the default [**Ask** access level](#access), choose **Allow** or **Decline** +when a command would read or write files, connect to an address on the internet, run a plugin, +script, task or model, or replace the project. SQL queries also ask because SQL can access files +and the network. **Don't ask again for exactly this action** remembers the exact command and all its parameters, not general access to a file or server. Plugin commands and tools, user automation and project replacement ask every time. @@ -54,19 +53,25 @@ From the command line, `rustgis-cli ask` sends one request (see | Level | Runs without asking | Still asks | | --- | --- | --- | -| **Ask** | Project edits | Files, the internet, SQL, scripts, tasks, notebooks, models, plugins and replacing the project | -| **Full access, for this session** | Also files, the internet, SQL, scripts, tasks, notebooks, models and installed plugins, and saving edits to a GeoPackage or PostGIS | Installing, enabling or removing plugins and the GeoLibre tools; connections, sign-ins and saved credentials; listing S3 buckets with a connection; extensions, the session log and other app settings; access to the app’s or installed plugins’ files; replacing the project | +| **Ask** | Project edits | Files, the internet, SQL, scripts, tasks, notebooks, models, plugins, app settings and replacing the project | +| **Full access, for this session** | Also ordinary files, the internet, scripts, tasks, notebooks, models, installed plugins and saving edits to ordinary GeoPackage files | Protected or unidentified file paths, SQL queries, and changes to plugins, the GeoLibre tools, connections, sign-ins, saved credentials or app settings. The session log, S3 bucket listings that use a connection, and replacing the project also require approval. | Full access is never saved: RustGIS always starts at **Ask**, and turning the assistant off also returns to it. While it is on, a warning above the message box and **Assistant: full access** in the status bar say so; **Back to Ask**, or a click on the status bar, ends it, from the -assistant's next action on. Subagents work at the same level. +assistant's next action on. On a phone, a warning and **Back to Ask** also appear above the bar +when the assistant is idle and its sheet is closed. Subagents work at the same level. -With full access, a layer or web page written to mislead the model can have it overwrite data files -or send data out without asking. Use it with data and models you trust, -and check what the conversation says it ran. What no level allows stays refused: external runners -RustGIS hasn't reviewed, and anything but project edits from a task, notebook or model that came -from a file or was made by an assistant, agent or plugin. +Both levels ask before changing the default raster style (`raster.setDefaultStyle`), which is an +app setting. When an operation still asks at Full access, it needs fresh approval even if you +previously approved it in Ask. Import QGIS and GeoLibre projects yourself because the files and +web addresses they name cannot be reviewed before opening them. + +With full access, a layer or web page written to mislead the model can have it overwrite data +files or send data out without asking. Use it with data and models you trust, and check what the +conversation says it ran. RustGIS refuses external runners it hasn't reviewed. A task, notebook +or model that came from a file or was made by an assistant, agent or plugin can only edit the +project. In the browser there are no files on disk to read or write: exports download, and full access lasts until you close or reload the page. @@ -85,9 +90,9 @@ dictation), then **Send**. The sheet stands half up, to see the map with the con for reading and typing: the arrow beside its **×** switches, and a swipe up or down on its heading moves it a step. Lowered while the assistant works, a strip over the bar says what it is doing and has **Stop**; tap its words to raise the sheet again. Approvals are a card with **Allow** and -**Decline**. [Access](#access) is the two buttons over the message box; with full access, the -sheet says so under its heading, with **Back to Ask**. The gear in the sheet's heading opens the settings again. Signing in with ChatGPT is -set up in the desktop interface. +**Decline**. The two [Access](#access) buttons are above the message box. With Full access, the +sheet shows a warning and **Back to Ask**. The gear in the heading opens settings. Set up ChatGPT +sign-in in the desktop interface. ## Turning the assistant off @@ -408,8 +413,8 @@ For a self-contained task, the assistant can use `delegate` to start a fresh con with the same provider and model, acting on the same project. The subagent receives the task, not the whole conversation, and returns a short report. Its tool calls appear in the main transcript, and what the [access level](#access) asks about still needs approval. It inherits the -level and the conversation's exact-command approvals. This works without installing a local coding agent; -it is distinct from the background threads below. +level and the conversation's exact-command approvals. The assistant can delegate this way +without a local coding agent. Background threads use the agents described below. ## Agents on this computer From 869b64c107a581d48e6ab9366cea903191acd04e Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 17:21:20 -0600 Subject: [PATCH 4/4] fix(assistant): require complete file bindings at full access --- crates/engine/src/cmd/gpkg.rs | 15 ++++ crates/engine/src/cmd/layer.rs | 15 +++- crates/engine/src/cmd/layout/inputs.rs | 17 +++- .../engine/src/cmd/layout/publication/mod.rs | 10 +-- crates/engine/src/cmd/mod.rs | 8 ++ crates/engine/src/cmd/share.rs | 28 ++++++- crates/engine/src/cmd/sharing.rs | 2 + crates/engine/src/cmd/whole.rs | 37 ++++++++- crates/engine/src/policy/dispatch.rs | 2 +- crates/engine/src/policy/plan.rs | 13 ++- crates/engine/src/policy/protected_files.rs | 35 +------- crates/engine/src/tests/permission_policy.rs | 81 ++++++++++++++++--- docs/user-guide/assistant.md | 2 +- 13 files changed, 202 insertions(+), 63 deletions(-) diff --git a/crates/engine/src/cmd/gpkg.rs b/crates/engine/src/cmd/gpkg.rs index 7eee067684..1a8d552c47 100644 --- a/crates/engine/src/cmd/gpkg.rs +++ b/crates/engine/src/cmd/gpkg.rs @@ -42,9 +42,24 @@ fn edit_inputs(input: &super::InputContext<'_>, p: &Value) -> Result Vec { + let mut paths = vec![path.to_path_buf()]; + let resolved = path.canonicalize().ok().filter(|resolved| resolved != path); + for database in std::iter::once(path).chain(resolved.as_deref()) { + for suffix in ["-journal", "-wal", "-shm"] { + let mut file = database.as_os_str().to_os_string(); + file.push(suffix); + paths.push(file.into()); + } + } + paths +} + fn gpkg_layer(s: &Session, p: &Value) -> Result<(u32, String, rustgis_map::source::GpkgEdit), String> { let (layer, edit) = selected_edit(&super::InputSource::input_context(s), p)?; Ok((layer.id, layer.name.clone(), edit.clone())) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index ed16461bea..d914a44008 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -20,7 +20,7 @@ pub const MAX_LAYER_NAME: usize = 200; /// Registers layer commands shared by the UI, CLI and command search. pub fn commands() -> Vec { vec![ - C::new("layer.addData", "Add Data", "Home › Add", add_data).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("layer.addData", "Add Data", "Home › Add", add_data).inputs(add_data_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"path": string, "name"?: "string; for a PDF opened as its layers, the group's (its layers keep the PDF's names)", "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "pdfLayers"?: "bool: a PDF page with layers (optional content groups) as a group of them, one raster each, true by default; false opens the page as one picture", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: "bool: true links the file instead of copying it (read in place, a view at a time; the project keeps its path, not its features), false copies it into the project; left out, decided by its size or feature count", "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV or workbook x/longitude column (in a zip, for each CSV and workbook member that has it)", "y"?: "CSV or workbook y/latitude column (as x)", "wkt"?: "CSV or workbook WKT geometry column (as x)", "delimiter"?: ","|";"|"\\t"|"|"}"#), C::new("layer.addPhotos", "Add Photos", "Home › Add", add_photos).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params( r#"{"paths"?: [JPEG photo files], "folder"?: "a folder of photos (every JPEG in it)", "name"?: "the layer (default Photos; photos join it when it exists)"}"#, @@ -49,7 +49,7 @@ pub fn commands() -> Vec { C::new("layer.defineProjection", "Define Projection", "Layers", define_projection).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_feature_layer) .params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#), - C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), + C::new("layer.loadAll", "Load All Features", "Layers", load_all).inputs(super::whole::read_inputs).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#), C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MiB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG: (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#, ), @@ -2047,6 +2047,17 @@ fn add_geodatabase(s: &mut Session, p: &Value, path: &str) -> CmdResult { Ok(out) } +/// Binds readers whose paths are fixed once the input file is known. Folder-based readers can +/// discover additional files, even when the folder's name ends in a data file's extension. +fn add_data_inputs(_: &super::InputContext<'_>, p: &Value) -> Result { + let mut inputs = super::Inputs::layers(std::iter::empty()); + let path = Path::new(s_req(p, "path")?); + if !cfg!(target_arch = "wasm32") && path.is_file() { + inputs.file_places = super::whole::direct_file_places(path); + } + Ok(inputs) +} + /// Opens a file through its format's reader. A Shapefile CRS override is applied before any /// conversion in both whole-file and streamed paths; the source file is never rewritten. /// DBF picks with geometry follow the full Shapefile import path. diff --git a/crates/engine/src/cmd/layout/inputs.rs b/crates/engine/src/cmd/layout/inputs.rs index 5fc2bf9a58..502de24bfa 100644 --- a/crates/engine/src/cmd/layout/inputs.rs +++ b/crates/engine/src/cmd/layout/inputs.rs @@ -183,7 +183,16 @@ pub(in crate::cmd::layout) fn locator_orphan(input: &impl crate::cmd::InputSourc s.project.maps.iter().position(|x| x.projection.is_globe() && ours(&x.name) && !shown(&x.name) && x.name != src.name && made_here(x)) } -/// Binds the active shown inputs and the optional generated map replacement. +/// Where the publication writes the coverage grid its placement searched. +pub(in crate::cmd::layout) fn publication_coverage_path(p: &Value) -> Result, String> { + match p.get("coverage") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) if path.trim().to_ascii_lowercase().ends_with(".png") => Ok(Some(path.trim())), + Some(_) => Err("coverage is the path of a .png file to write the coverage grid to".into()), + } +} + +/// Binds the active shown inputs, the optional output file and the generated map replacement. pub(in crate::cmd::layout) fn publication_inputs(input: &crate::cmd::InputContext<'_>, p: &Value) -> Result { let s = input; let (_, profile) = publication_profile(p)?; @@ -191,6 +200,12 @@ pub(in crate::cmd::layout) fn publication_inputs(input: &crate::cmd::InputContex let map = s.map(); let mut inputs = crate::cmd::Inputs::layers(map.layers.iter().filter(|l| map.shows(l)).map(|l| (map, l))); inputs.maps.push(map.instance_id()); + if let Some(path) = publication_coverage_path(p)? { + inputs.review_places.push(path.into()); + if map.view.terrain.is_none() && !map.layers.iter().any(|l| map.shows(l) && (l.is_streamed() || l.is_raster())) { + inputs.file_places = Some(vec![path.into()]); + } + } if locators.contains(&Locator::Globe) { if let Some(old) = locator_orphan(input).and_then(|i| s.project.maps.get(i)) { inputs.maps.push(old.instance_id()); diff --git a/crates/engine/src/cmd/layout/publication/mod.rs b/crates/engine/src/cmd/layout/publication/mod.rs index 8d5dd4f22e..95590dfb7d 100644 --- a/crates/engine/src/cmd/layout/publication/mod.rs +++ b/crates/engine/src/cmd/layout/publication/mod.rs @@ -196,12 +196,8 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu let kicker = one("kicker")?; let headlines = headline_figures(p)?; // Where the coverage grid the placement searches is written as an image (#1379). - let coverage_path = match p.get("coverage") { - None | Some(Value::Null) => None, - Some(Value::String(path)) if path.trim().to_ascii_lowercase().ends_with(".png") => Some(path.trim().to_string()), - Some(_) => return Err("coverage is the path of a .png file to write the coverage grid to".into()), - }; - if let Some(path) = coverage_path.as_deref().filter(|_| s.downloads_files()) { + let coverage_path = publication_coverage_path(p)?; + if let Some(path) = coverage_path.filter(|_| s.downloads_files()) { return Err(format!("{path}: the web app can't write the coverage image to a path; leave out coverage, or use the desktop app")); } // No orientation asked: the one the area's map comes out larger on, from its extents east to @@ -2241,7 +2237,7 @@ pub(in crate::cmd::layout) fn publication(s: &mut Session, p: &Value) -> CmdResu // why a surround moved (#1379). The layout is made by then (nothing below refuses it): a file // that can't be written is said, and the layout kept. let mut coverage_written = Value::Null; - if let Some(path) = &coverage_path { + if let Some(path) = coverage_path { let rects: Vec = placed.iter().map(|(_, r)| *r).collect(); let png = coverage .as_ref() diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 23403bf02c..81abe6252e 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -666,6 +666,8 @@ pub(crate) struct Inputs { pub unresolved: bool, /// Public destination data, separately sanitized for review; never private selector state. pub review_places: Vec, + /// Complete local file inputs and outputs for Full access. Unknown or partial bindings are `None`. + pub file_places: Option>, /// This owner actually selected the ordinary active/default layer. pub uses_default: bool, } @@ -680,6 +682,7 @@ impl Inputs { state: serde_json::Value::Null, unresolved: false, review_places: Vec::new(), + file_places: None, uses_default: false, } } @@ -733,6 +736,7 @@ impl Inputs { state: serde_json::Value::Null, unresolved: false, review_places: Vec::new(), + file_places: None, uses_default: !matches!(p.get("layer"), Some(serde_json::Value::String(_) | serde_json::Value::Number(_))), }) } @@ -753,6 +757,10 @@ impl Inputs { self.future_layers.extend(other.future_layers); self.unresolved |= other.unresolved; self.review_places.extend(other.review_places); + self.file_places = self.file_places.take().zip(other.file_places).map(|(mut ours, theirs)| { + ours.extend(theirs); + ours + }); self.uses_default |= other.uses_default; if !other.state.is_null() { self.state = if self.state.is_null() { other.state } else { serde_json::json!([self.state, other.state]) }; diff --git a/crates/engine/src/cmd/share.rs b/crates/engine/src/cmd/share.rs index 809df5c65a..d4c70d1e60 100644 --- a/crates/engine/src/cmd/share.rs +++ b/crates/engine/src/cmd/share.rs @@ -18,8 +18,30 @@ use super::{f, need_layer, ps}; use crate::{CommandSpec as C, Session, notice_text::NoticeText}; /// The map export binds exactly the map and tile routes the worker will copy. -fn map_inputs(s: &super::InputContext<'_>, _: &Value) -> Result { - Ok(super::tiles::render_inputs(s.map())) +fn map_inputs(s: &super::InputContext<'_>, p: &Value) -> Result { + let map = s.map(); + let mut inputs = super::tiles::render_inputs(map); + if map.tiles.is_empty() && map.view.terrain.is_none() && !map.layers.iter().any(|l| l.is_streamed() || l.is_raster()) { + inputs.file_places = ps(p, "path").map(|path| vec![path.into()]); + } + Ok(inputs) +} + +/// Binds the streamed input and the output files used by the feature export. +fn layer_inputs(s: &super::InputContext<'_>, p: &Value) -> Result { + let mut inputs = super::whole::read_inputs(s, p)?; + let path = Path::new(ps(p, "path").ok_or("path is required")?); + inputs.file_places = inputs.file_places.and_then(|mut places| { + let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase(); + match ext.as_str() { + "gpkg" => places.extend(super::gpkg::file_places(path)), + // The declaration comparison also reads existing sidecars with case variants. + "shp" => return None, + _ => places.push(path.to_path_buf()), + } + Some(places) + }); + Ok(inputs) } pub fn commands() -> Vec { @@ -32,7 +54,7 @@ pub fn commands() -> Vec { }).inputs(map_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .params(r#"{"path": "*.png|*.tif|*.tiff", "width"?: "points (pixels at 96 dpi), the view fitted in it", "height"?: points, "dpi"?: "48..600 (default 96)", "fit"?: "true to lower the dpi until a side fits 8192 pixels, saying so", "cog"?: "true for a cloud-optimised GeoTIFF"}"#), - C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) + C::new("share.exportLayer", "Export Features", "Publish › Output", |s, p| super::exports::write_here(s, p, "share.exportLayer")).inputs(layer_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() .when(need_layer) .params(r#"{"layer"?, "path": "*.geojson|*.csv|*.fgb|*.gpkg|*.parquet|*.shp|*.zip|*.kml|*.kmz|*.gpx", "crs"?: "EPSG:… (or WKT) for a GeoPackage, Shapefile or FlatGeobuf, EPSG:… for a GeoParquet (default: the system the layer was read in, else EPSG:4326), or for a CSV's coordinate columns, x and y in a projected one (default: EPSG:4326)", "mode"?: "newFile (default: refuses an existing file) | addTable | replaceTable, for a GeoPackage", "tableName"?: "the GeoPackage table (default: the layer's name)"} Applies the layer's definition query and reports how many features it leaves out."#), diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 3a6d81cd69..9b94801409 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -589,6 +589,8 @@ fn upload_inputs(input: &super::InputContext<'_>, p: &Value) -> Result Result { Ok(Unread::of(name, unread)) } +/// Local files a whole read can open. Only bound readers can run without asking under Full access. +/// An in-memory layer can retain an original filename as provenance without reading it again. +pub(super) fn file_places(l: &Layer) -> Option> { + let Some(source) = &l.source else { return Some(Vec::new()) }; + if source.gdal.is_some() || source.duckdb.is_some() { + return None; + } + if let Some(path) = source.path.as_deref() { + if rustgis_data::source::is_remote_name(path) { + return Some(Vec::new()); + } + return direct_file_places(std::path::Path::new(path)); + } + source.embedded.as_ref().map(|_| Vec::new()) +} + +/// Readers with a single file or a fixed set of companion paths. +pub(super) fn direct_file_places(path: &std::path::Path) -> Option> { + let ext = path.extension()?.to_str()?.to_ascii_lowercase(); + match ext.as_str() { + "geojson" | "json" | "fgb" | "parquet" | "geoparquet" | "las" | "laz" => Some(vec![path.to_path_buf()]), + "gpkg" => Some(super::gpkg::file_places(path)), + _ => None, + } +} + +/// Like the executor, a whole read selects the given layer or the session default. +pub(super) fn read_inputs(s: &super::InputContext<'_>, p: &serde_json::Value) -> Result { + let mut inputs = super::Inputs::single_layer(s, p)?; + if let Some(layer) = s.layer_id(p).ok().and_then(|id| s.map().layer(id)) { + inputs.file_places = file_places(layer); + } + Ok(inputs) +} + /// The notice, with its code, that `unread` rows of `layer`'s source couldn't be read and are left /// out. [`unread_notice`] gives the same text for an error that names it. pub fn unread_note(layer: &str, unread: usize) -> rustgis_data::loss::Note { @@ -184,7 +219,7 @@ pub(crate) fn layers_read_whole<'a>(s: &super::InputContext<'a>, command: &str, "dl.train" | "dl.classify" | "raster.classifySupervised" => { super::ps(params, "training").and_then(|n| s.map().layer_by_name(n)).into_iter().collect() } - "labels.convert" => s.layer_id(params).ok().and_then(|id| s.map().layer(id)).into_iter().collect(), + "labels.convert" | "share.exportLayer" => s.layer_id(params).ok().and_then(|id| s.map().layer(id)).into_iter().collect(), "report.export" => super::report::index(s, params) .map(|i| super::report::reported_layers(s, i)) .unwrap_or_default() diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 37c8bc3d03..22443f2389 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -1239,7 +1239,7 @@ impl Session { effects, targets: Vec::new(), places: Vec::new(), - file_places: Vec::new(), + file_places: None, display: Default::default(), children: Vec::new(), item: None, diff --git a/crates/engine/src/policy/plan.rs b/crates/engine/src/policy/plan.rs index 3101b0faf6..83033775a8 100644 --- a/crates/engine/src/policy/plan.rs +++ b/crates/engine/src/policy/plan.rs @@ -339,7 +339,7 @@ pub(crate) struct Node { pub(super) effects: Effects, pub(super) targets: Vec, pub(super) places: Vec, - pub(super) file_places: Vec, + pub(super) file_places: Option>, pub(super) display: ReviewDetail, pub(super) children: Vec, pub(super) item: Option<(&'static str, String, bool, Value)>, @@ -648,7 +648,7 @@ impl<'a> Builder<'a> { effects, targets: Vec::new(), places: Vec::new(), - file_places: Vec::new(), + file_places: None, display: ReviewDetail { operation: String::new(), targets: Vec::new(), places: Vec::new() }, children: Vec::new(), item: None, @@ -916,7 +916,13 @@ impl<'a> Builder<'a> { self.charge(&(&inputs.layers, &inputs.maps, &inputs.tables, &inputs.future_layers))?; self.charge(&inputs.state)?; n.places.push(inputs.state); - n.file_places.extend(inputs.review_places); + n.display.places.extend(inputs.review_places); + if !inputs.unresolved && n.wires.is_empty() { + for path in inputs.file_places.iter().flatten() { + self.charge(&path.to_string_lossy())?; + } + n.file_places = inputs.file_places; + } let uses_default = inputs.uses_default; for name in inputs.future_layers { if let Some(target) = self.symbol(&name) { @@ -1096,7 +1102,6 @@ impl<'a> Builder<'a> { _ => {} } } - n.display.places.splice(0..0, n.file_places.iter().cloned()); for value in n.display.targets.iter_mut().chain(n.display.places.iter_mut()) { *value = rustgis_data::diagnostics::Redacted::new(value).into_string(); } diff --git a/crates/engine/src/policy/protected_files.rs b/crates/engine/src/policy/protected_files.rs index 322195765a..e457ec5cf9 100644 --- a/crates/engine/src/policy/protected_files.rs +++ b/crates/engine/src/policy/protected_files.rs @@ -1,23 +1,13 @@ //! Full access still asks before accessing app-managed files or files used to load a plugin. -use super::{effects::PLACE_KEYS, plan::Node}; -use serde_json::Value; +use super::plan::Node; use std::io::ErrorKind; use std::path::{Component, Path, PathBuf}; pub(super) fn uses_protected_files(node: &Node, roots: &std::cell::OnceCell>>) -> bool { - let mut paths = node.file_places.iter().map(String::as_str).filter(|path| !path.trim().is_empty()).collect::>(); - if !parameters(&node.params, &mut paths, false, 0) || !paths.iter().any(|path| !path.contains("://")) { - return true; - } - + let Some(paths) = &node.file_places else { return true }; let Some(roots) = roots.get_or_init(protected_roots) else { return true }; - paths.into_iter().any(|path| { - let trimmed = path.trim(); - touches_root(Path::new(path), roots) - || (trimmed != path && touches_root(Path::new(trimmed), roots)) - || trimmed.strip_prefix("file://").is_some_and(|path| touches_root(Path::new(path), roots)) - }) + paths.iter().any(|path| path.as_os_str().is_empty() || touches_root(path, roots)) } fn protected_roots() -> Option> { @@ -50,25 +40,6 @@ fn touches_root(path: &Path, roots: &[PathBuf]) -> bool { under_root(&place) || absolute.ancestors().skip(1).filter_map(|parent| parent.canonicalize().ok()).any(|parent| under_root(&parent)) } -fn parameters<'a>(params: &'a Value, paths: &mut Vec<&'a str>, named: bool, depth: usize) -> bool { - match params { - Value::Object(object) if depth < 16 => object.iter().all(|(key, value)| { - let named = PLACE_KEYS.iter().any(|place| place.eq_ignore_ascii_case(key)) - && !["url", "uri", "connection"].iter().any(|remote| remote.eq_ignore_ascii_case(key)); - parameters(value, paths, named, depth + 1) - }), - Value::Array(array) if depth < 16 => array.iter().all(|value| parameters(value, paths, named, depth + 1)), - Value::Object(_) | Value::Array(_) => false, - Value::String(path) => { - if !path.trim().is_empty() && (named || crate::cmd::items::looks_like_path(path)) { - paths.push(path); - } - true - } - _ => true, - } -} - /// Resolves existing ancestors and links. A dangling link, an unreadable path, or a missing /// component followed by `..` needs a review. fn resolved(path: &Path) -> Option { diff --git a/crates/engine/src/tests/permission_policy.rs b/crates/engine/src/tests/permission_policy.rs index 91ceee5aaf..5fc5404eaf 100644 --- a/crates/engine/src/tests/permission_policy.rs +++ b/crates/engine/src/tests/permission_policy.rs @@ -2309,13 +2309,74 @@ fn permission_policy_assistant_full_access_refuses_generated_imports() { #[cfg(not(target_arch = "wasm32"))] #[test] -fn permission_policy_assistant_full_access_asks_about_unidentified_file_paths() { - let mut s = world(); - let (full, _) = full_and_ask(35687); - let call = Call::command("layout.publication", json!({"coverage":"coverage.png"})); - let approval = pending(&s, &full, &call); - assert!(!approval.review().remember); - assert!(s.run_scoped(full, &call).unwrap_err().contains("approval")); +fn permission_policy_full_access_binds_relative_publication_coverage() { + if isolate_process_test("tests::permission_policy::permission_policy_full_access_binds_relative_publication_coverage") { + return; + } + let root = std::env::temp_dir().join(format!("rustgis-policy-coverage-{}", std::process::id())); + std::fs::create_dir_all(root.join("plugins")).unwrap(); + let s = world(); + rustgis_plugins::store::set_dir(Some(root.join("plugins"))); + let cwd = std::env::current_dir().unwrap(); + std::env::set_current_dir(&root).unwrap(); + let (full, _) = full_and_ask(36281); + let publication = |coverage| Call::command("layout.publication", json!({"coverage": coverage, "title": "/tmp/report"})); + let protected = s.review(&full, &publication("plugins/coverage.png")); + let ordinary = s.review(&full, &publication("coverage.png")); + std::env::set_current_dir(cwd).unwrap(); + std::fs::remove_dir_all(root).unwrap(); + match protected { + Outcome::NeedsApproval(approval) => { + assert!(!approval.review().remember); + assert!(approval.review().details.iter().any(|step| step.places.iter().any(|path| path == "plugins/coverage.png"))); + } + Outcome::Allowed => panic!("the relative coverage destination needs approval"), + Outcome::Refused(error) => panic!("refused instead of approving the relative coverage destination: {error}"), + } + assert!(matches!(ordinary, Outcome::Allowed)); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn permission_policy_full_access_checks_reopened_export_sources() { + if isolate_process_test("tests::permission_policy::permission_policy_full_access_checks_reopened_export_sources") { + return; + } + let root = std::env::temp_dir().join(format!("rustgis-policy-reopened-{}", std::process::id())); + let plugins = root.join("plugins"); + std::fs::create_dir_all(&plugins).unwrap(); + rustgis_plugins::store::set_dir(Some(plugins.clone())); + let mut s = Session::new(Project::default()); + let ordinary = grid_fgb("policy-reopened", 2); + let protected = plugins.join("sites.fgb"); + std::fs::copy(&ordinary, &protected).unwrap(); + for (name, path) in [("Ordinary", &ordinary), ("Protected", &protected)] { + s.run("layer.addData", &json!({"path":path,"name":name,"stream":true})).unwrap(); + assert!(s.map().layer_by_name(name).unwrap().is_streamed()); + } + let (full, _) = full_and_ask(36282); + let dest = root.join("out.geojson"); + let export = |layer| Call::command("share.exportLayer", json!({"layer": layer, "path": dest})); + let protected_call = export("Protected"); + assert!(!pending(&s, &full, &protected_call).review().remember); + assert!(s.run_scoped(full.clone(), &protected_call).is_err()); + assert!(!dest.exists()); + let allowed = export("Ordinary"); + assert!(matches!(s.review(&full, &allowed), Outcome::Allowed)); + s.run_scoped(full.clone(), &allowed).unwrap(); + assert!(std::fs::metadata(&dest).unwrap().len() > 0); + std::fs::remove_file(&dest).unwrap(); + + // Loading all retains file provenance as a record, but a later export uses resident rows. + s.run("layer.loadAll", &json!({"layer":"Protected"})).unwrap(); + let held = s.map().layer_by_name("Protected").unwrap(); + assert!(!held.is_streamed()); + assert!(held.dataset.source.is_some()); + std::fs::remove_file(protected).unwrap(); + assert!(matches!(s.review(&full, &protected_call), Outcome::Allowed)); + s.run_scoped(full, &protected_call).unwrap(); + std::fs::remove_file(ordinary).unwrap(); + std::fs::remove_dir_all(root).unwrap(); } /// What full access still asks about, never remembered: installs, sign-ins and saved credentials, @@ -2422,7 +2483,7 @@ fn permission_policy_assistant_full_access_reserved_commands() { #[cfg(not(target_arch = "wasm32"))] #[test] -fn permission_policy_assistant_full_access_checks_path_leaves() { +fn permission_policy_assistant_full_access_asks_about_unbound_file_operations() { let mut s = world(); s.registry.commands.push( crate::CommandSpec::new("test.fileLeaves", "File leaves", "Test", |_, _| Ok(Value::Null)) @@ -2431,13 +2492,11 @@ fn permission_policy_assistant_full_access_checks_path_leaves() { ); let (full, _) = full_and_ask(35688); let ordinary = std::env::temp_dir().join("rustgis-policy-fixture.png"); - let protected = rustgis_plugins::store::dir().unwrap().join("rustgis-policy-fixture.png"); - for params in [json!({"coverage":protected}), json!({"paths":[ordinary, protected]})] { + for params in [Value::Null, json!({"path":ordinary,"title":"/tmp/report"})] { let call = Call::command("test.fileLeaves", params); assert!(!pending(&s, &full, &call).review().remember); assert!(s.run_scoped(full.clone(), &call).is_err()); } - assert!(matches!(s.review(&full, &Call::command("test.fileLeaves", json!({"paths":[ordinary]}))), Outcome::Allowed)); } #[cfg(unix)] diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 8ebf12132f..55739cb7e8 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -54,7 +54,7 @@ From the command line, `rustgis-cli ask` sends one request (see | Level | Runs without asking | Still asks | | --- | --- | --- | | **Ask** | Project edits | Files, the internet, SQL, scripts, tasks, notebooks, models, plugins, app settings and replacing the project | -| **Full access, for this session** | Also ordinary files, the internet, scripts, tasks, notebooks, models, installed plugins and saving edits to ordinary GeoPackage files | Protected or unidentified file paths, SQL queries, and changes to plugins, the GeoLibre tools, connections, sign-ins, saved credentials or app settings. The session log, S3 bucket listings that use a connection, and replacing the project also require approval. | +| **Full access, for this session** | Also file operations with known, ordinary inputs and destinations, the internet, scripts, tasks, notebooks, models and installed plugins | Protected file paths, operations whose file inputs or destinations RustGIS cannot fully identify in advance, SQL queries, and changes to plugins, the GeoLibre tools, connections, sign-ins, saved credentials or app settings. The session log, S3 bucket listings that use a connection, and replacing the project also require approval. | Full access is never saved: RustGIS always starts at **Ask**, and turning the assistant off also returns to it. While it is on, a warning above the message box and **Assistant: full access** in