Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions crates/assistant/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,6 +993,23 @@ fn steps_are_bounded_and_stop_works() {
assert!(!a.transcript.iter().any(|e| matches!(e, Entry::Assistant(t) if t == "late")));
}

/// An approval says when the SQL it shows has secrets taken out, which a marker in the text
/// doesn't always show (a secret setting is emptied to ''), and doesn't when it hasn't.
#[test]
fn an_sql_approval_says_when_its_text_has_secrets_taken_out() {
let mut s = sample();
let mut hidden = |sql: &str| {
let mut a = Agent::new(cfg("openai"), &s);
a.ask("query", &s);
let query = call("q", "run_command", json!({"command": "sql.query", "params": {"sql": sql}}));
assert_eq!(a.receive(a.generation(), ok(query), &mut s), Step::Confirm, "{sql}");
a.pending_review().map(|r| r.sql_hidden)
};
assert_eq!(hidden("SET s3_secret_access_key = 'hunter2-secret'"), Some(true));
assert_eq!(hidden("CREATE SECRET s (TYPE s3, KEY_ID 'a', SECRET 'b')"), Some(true));
assert_eq!(hidden("SELECT name FROM 'cities.parquet' WHERE name = ''"), Some(false));
}

#[test]
fn missing_settings_are_reported() {
let s = sample();
Expand Down
22 changes: 17 additions & 5 deletions crates/engine/src/policy/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,9 @@ pub struct Review {
pub explanation: (&'static str, Vec<(&'static str, String)>),
/// Script line numbers and command ids needing review, for translated reason prefixes.
pub lines: Vec<(usize, String)>,
/// The SQL shown has secrets taken out (a key, a `CREATE SECRET`'s options), which the query
/// still runs with: a card shows it, so the text isn't taken for all of it.
pub sql_hidden: bool,
}
pub(super) const MAX_NODES: usize = 1_000;
const MAX_DEPTH: usize = 4;
Expand Down Expand Up @@ -1338,12 +1341,20 @@ impl Plan {
return Err("too long to show in full; run it yourself or ask for a smaller request".into());
}
/// Lists every asking node and counts project-only edits without exposing private bindings.
fn shown(n: &Node, steps: &mut Vec<String>, edits: &mut usize, details: &mut Vec<ReviewDetail>) -> Result<(), String> {
fn shown(
n: &Node,
steps: &mut Vec<String>,
edits: &mut usize,
details: &mut Vec<ReviewDetail>,
sql_hidden: &mut bool,
) -> Result<(), String> {
if !n.display.targets.is_empty() || !n.display.places.is_empty() {
details.push(n.display.clone());
}
if n.effects.iter().any(|e| !matches!(e, Effect::Edits | Effect::History)) {
let mut line = format!("{} {}", n.id(), crate::project_log::review_params(&n.params)?);
let reviewed = crate::project_log::review_params(&n.params)?;
*sql_hidden |= ["sql", "query"].iter().any(|k| n.params.get(k).is_some_and(|raw| reviewed.get(k) != Some(raw)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sql_hidden is documented as "secrets taken out", but it is set whenever review_params returns a different value, and review_value changes text for reasons that aren't secrets. Two cases I traced in project_log.rs:

  • A JSON object or array inside the SQL text is parsed and re-serialised compactly (review_value, the String arm, out.push_str(&value.to_string())). So SELECT json_extract('{"a": 1}', '$.a') comes out as {"a":1}. The flag goes true, the card says "Secret values in this query are hidden here, but the query runs with them", and the card shows SQL that differs from what runs, though nothing was secret.
  • The same happens through redacted_parameter (schemeless_query_cut) for any text the sanitiser shortens.

Result: a false statement on the consent card, and the card's text is altered without the note saying what changed. Not run here. I traced the mechanism by reading the code; confidence high on the JSON case.

Suggested direction: have the sanitiser report that it removed a secret (as sql_secrets_removed does for its own cases) and set the flag from that, not from inequality. Add a test that SELECT '{"a": 1}' gives sql_hidden == false (the existing "clean SELECT" assertion doesn't cover a {/[ literal).

Category: bug

let mut line = format!("{} {}", n.id(), reviewed);
if let Op::Plugin(_, p) = &n.op {
line.push_str(&format!(
" — {} {:?}, SHA-256 {}, permissions {:?}",
Expand All @@ -1369,14 +1380,15 @@ impl Plan {
*edits += 1;
}
for c in &n.children {
shown(c, steps, edits, details)?;
shown(c, steps, edits, details, sql_hidden)?;
}
Ok(())
}
let mut steps = Vec::new();
let mut edits = 0;
let mut details = Vec::new();
shown(&self.root, &mut steps, &mut edits, &mut details)?;
let mut sql_hidden = false;
shown(&self.root, &mut steps, &mut edits, &mut details, &mut sql_hidden)?;
let defaults = self.picked.as_ref().map(|(active, selection)| {
let name = |id: &u32| {
rustgis_data::diagnostics::Redacted::new(
Expand Down Expand Up @@ -1414,7 +1426,7 @@ impl Plan {
if bounded_size(&(&what, &why, &steps, &details, &defaults, &explanation, &lines), MAX_REVIEW).is_err() {
return Err("too long to show in full; run it yourself or ask for a smaller request".into());
}
Ok(Review { what, why, steps, remember, edits, defaults, explanation, details, lines })
Ok(Review { what, why, steps, remember, edits, defaults, explanation, details, lines, sql_hidden })
}
}

Expand Down
27 changes: 24 additions & 3 deletions crates/ui-egui/src/approvalcard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
use egui::{RichText, Ui};
use rustgis_engine::{Registry, policy::Review};

/// The SQL a request runs, with the command that runs it, from the sanitized steps it asks about.
fn sql(review: &Review) -> Vec<(String, String)> {
let query = |step: &String| {
let (id, params) = step.split_once(' ').filter(|(id, _)| matches!(*id, "sql.query" | "layer.addSql"))?;
let params: serde_json::Value = serde_json::from_str(params).ok()?;
Some((id.to_string(), params.get("sql")?.as_str()?.to_string()))
};
review.steps.iter().filter_map(query).collect()
}

/// Registry labels name operations without interpreting the request's script or parameters.
fn operation(registry: &Registry, id: &str) -> String {
registry.get(id).map_or_else(|| id.to_string(), |spec| tl_raw!(spec.label).to_string())
Expand All @@ -12,10 +22,12 @@ fn operation(registry: &Registry, id: &str) -> String {
/// Callers bound the scroll area and keep their existing approval controls outside it.
pub(crate) fn show(ui: &mut Ui, registry: &Registry, review: &Review) {
ui.push_id((&review.what, &review.steps, &review.defaults, &review.lines), |ui| {
let queries = sql(review);
let mut operations = Vec::new();
for id in review.details.iter().map(|d| &d.operation).chain(review.lines.iter().map(|(_, id)| id)) {
if !id.is_empty() && !operations.contains(id) {
operations.push(id.clone());
let asked = review.details.iter().map(|d| &d.operation).chain(review.lines.iter().map(|(_, id)| id)).cloned();
for id in asked.chain(queries.iter().map(|(id, _)| id.clone())) {
if !id.is_empty() && !operations.contains(&id) {
operations.push(id);
}
}
let actions = if operations.is_empty() {
Expand All @@ -40,6 +52,15 @@ pub(crate) fn show(ui: &mut Ui, registry: &Registry, review: &Review) {
);
}
ui.add(egui::Label::new(RichText::new(reason(review)).small()).wrap());
// What a query does is its text, so it isn't left under Details.
for (_, query) in &queries {
ui.add(egui::Label::new(RichText::new(query).monospace().small()).wrap().selectable(true));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This card now shows the query as what the request does, but the text is the sanitized review. sql_secrets_removed (crates/engine/src/project_log.rs:459-486) replaces the body of a CREATE SECRET (...) statement with (…) before the card sees it, and nothing on the card says that text was left out. So the user approves a query that differs from the one that runs, and whatever the elided body holds (a key, an endpoint) is not visible at the point of consent. Before this PR the same text was only under Details; the card makes it look like the full query. Suggest a visible note when the sanitizer changed the text, e.g. "some secret text is left out of this view". Confidence: medium. I did not check whether the elided part is ever a destination the user would need to see.

Category: security

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6e7fee4: when a query's secret values are left out of the card, a note under it says they're hidden and that the query runs with them.

}
// Secrets are left out of what is shown (a CREATE SECRET's options, a key): said, so the
// text isn't taken for the whole query.
if !queries.is_empty() && review.sql_hidden {
ui.label(RichText::new(tl!("Secret values in this query are hidden here, but the query runs with them.")).small().italics());
}
for detail in &review.details {
let name = operation(registry, &detail.operation);
if !detail.targets.is_empty() {
Expand Down
75 changes: 75 additions & 0 deletions crates/ui-egui/src/assistant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ pub struct AssistantState {
pub(crate) history_pos: Option<usize>,
/// "Allow for this conversation" in the approval card.
pub(crate) always: bool,
/// The approval [`Self::always`] was ticked for.
pub(crate) always_for: Option<rustgis_assistant::Asking>,
pub(crate) loaded: bool,
/// Settings changed and not yet saved: they are saved once no settings field is being typed in.
pub(crate) unsaved: bool,
Expand Down Expand Up @@ -1076,6 +1078,78 @@ fn send_from(app: &mut RustGisApp, text: String, from_box: bool, ctx: &egui::Con
follow(app, step, ctx);
}

/// A tool call in plain words: the command's name and the layer it is given, or what the tool does.
/// In logical order: the caller puts the line it goes into in display form once.
pub fn plain_call(app: &RustGisApp, name: &str, summary: &str) -> String {
use crate::i18n::fmt_raw;
use serde_json::Value;
const LONGEST: usize = 60;
// A subagent's calls are marked as its.
let (mark, summary) = match summary.strip_prefix("↳ ") {
Some(rest) => ("↳ ", rest),
None => ("", summary),
};
let first = summary.split_whitespace().next().unwrap_or_default();
// The summary's parameters, unless they were too long for it.
let args: Value = summary.split_once(' ').and_then(|(_, json)| serde_json::from_str(json).ok()).unwrap_or_default();
let arg = |path: &str| {
let text = args.pointer(path).and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty());
text.map(|t| rustgis_assistant::tools::clip(t, LONGEST))
};
let words = match name {
"run_command" => {
let label = match app.session.registry.get(first) {
// Without the dots of a label that opens a dialog: here it ran.
Some(spec) => tl_raw!(spec.label).trim_end_matches('…').to_string(),
None => first.to_string(),
};
match arg("/layer") {
Some(layer) => format!("{label} · {layer}"),
None => label,
}
}
"run_tool" => match arg("/tool") {
Some(tool) => fmt_raw("Ran the tool {tool}", &[("tool", &tool)]),
None => tl_raw!("Ran a tool").to_string(),
},
"run" => {
// The commands of each line, by name, as far as the summary goes.
let script = arg("/script").unwrap_or_default();
let named: Vec<String> = script
.lines()
.filter_map(|l| l.split_whitespace().next().filter(|w| !w.starts_with('#')))
.map(|id| app.session.registry.get(id).map_or(id.to_string(), |s| tl_raw!(s.label).trim_end_matches('…').to_string()))
.collect();
match named.as_slice() {
[] => tl_raw!("Ran several commands").to_string(),
names => fmt_raw("Ran {commands}", &[("commands", &rustgis_assistant::tools::clip(&names.join(", "), LONGEST))]),
}
}
"list_layers" => tl_raw!("Looked at the layers").to_string(),
"view_map" => tl_raw!("Looked at the map").to_string(),
"search_commands" => tl_raw!("Looked for a command").to_string(),
"search_tools" => tl_raw!("Looked for a tool").to_string(),
"describe_tool" => tl_raw!("Read about a tool").to_string(),
"read_features" => match arg("/layer").or_else(|| arg("/table")) {
Some(layer) => fmt_raw("Read features of {layer}", &[("layer", &layer)]),
None => tl_raw!("Read features").to_string(),
},
"search_docs" | "read_doc" => tl_raw!("Read the user guide").to_string(),
"load_skill" => tl_raw!("Loaded a skill").to_string(),
"delegate" => tl_raw!("Handed a task to a subagent").to_string(),
_ => rustgis_assistant::tools::clip(summary, LONGEST),
};
let query = if matches!(name, "search_commands" | "search_tools" | "search_docs") {
arg("/query")
} else {
arg("/tool").filter(|_| name == "describe_tool")
};
match query {
Some(query) => format!("{mark}{words}: {query}"),
None => format!("{mark}{words}"),
}
}

/// An action waiting for the user's approval.
#[derive(Clone)]
pub struct Approval {
Expand Down Expand Up @@ -1117,6 +1191,7 @@ pub fn stop(app: &mut RustGisApp) {
if let Some(a) = app.assistant.agent.as_mut() {
a.stop();
}
app.assistant.always = false;
drop_request(&mut app.assistant);
app.assistant.hold();
}
Expand Down
Loading
Loading