F1: settings.set refuses quoted, padded and control-character paths

Path settings get Kind::Path, checked by check_path in the engine: the one
validator for settings.set from agents, the CLI and the dialog. settings.list
marks them with path: true; the dialog uses that flag for Browse and shows
the engine's reason (userMessage drops the invalid-params prefix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-11-02 19:02:08 +01:00
parent 750ecf5e51
commit 8a05f508c8
8 changed files with 150 additions and 51 deletions

View file

@ -36,11 +36,46 @@ pub enum Kind {
}, },
/// `true` or `false`. /// `true` or `false`.
Bool, Bool,
/// Any string of at most `max_len` bytes, such as a file path. /// Any string of at most `max_len` bytes without NUL.
Str { Str {
/// Longest accepted value in bytes. /// Longest accepted value in bytes.
max_len: usize, max_len: usize,
}, },
/// A file path, or empty for "detect it": a string checked by
/// [`check_path`], the one validator for `settings.set` and the
/// settings dialog (which shows its message).
Path {
/// Longest accepted value in bytes.
max_len: usize,
},
}
/// Checks a path setting's text: at most `max_len` bytes, no control
/// characters (U+0000–U+001F, U+007F), not wrapped in quotes (as copied
/// from a shell or the file manager) and no spaces at either end. Values
/// are refused, never trimmed, so what is stored is what was typed.
///
/// # Errors
/// What to change, as a sentence the dialog shows under the field.
pub fn check_path(text: &str, max_len: usize) -> Result<(), String> {
if text.len() > max_len {
return Err(format!("Enter at most {max_len} bytes"));
}
if text.chars().any(|c| c < ' ' || c == '\u{7f}') {
return Err("Remove tabs, line breaks and other control characters".into());
}
let trimmed = text.trim();
let quoted = trimmed.len() >= 2
&& ['"', '\'']
.iter()
.any(|q| trimmed.starts_with(*q) && trimmed.ends_with(*q));
if quoted {
return Err("Remove the quotes around the path".into());
}
if trimmed != text {
return Err("Remove the spaces at the start or end of the path".into());
}
Ok(())
} }
/// The default value of a setting. /// The default value of a setting.
@ -121,6 +156,12 @@ impl Def {
self.key self.key
)), )),
}, },
Kind::Path { max_len } => match value.as_str() {
Some(s) => {
check_path(s, max_len).map_err(|reason| format!("{}: {reason}", self.key))
}
None => Err(format!("{} must be a path string, got {value}", self.key)),
},
} }
} }
@ -130,7 +171,7 @@ impl Def {
Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None), Kind::Enum(values) => ("enum", Some(values.to_vec()), None, None),
Kind::Int { min, max } => ("int", None, Some(min), Some(max)), Kind::Int { min, max } => ("int", None, Some(min), Some(max)),
Kind::Bool => ("bool", None, None, None), Kind::Bool => ("bool", None, None, None),
Kind::Str { .. } => ("string", None, None, None), Kind::Str { .. } | Kind::Path { .. } => ("string", None, None, None),
}; };
SettingInfo { SettingInfo {
key: self.key, key: self.key,
@ -139,6 +180,7 @@ impl Def {
enum_values, enum_values,
min, min,
max, max,
path: matches!(self.kind, Kind::Path { .. }),
label_key: self.label_key, label_key: self.label_key,
description_key: self.description_key, description_key: self.description_key,
section: self.section, section: self.section,
@ -166,6 +208,10 @@ pub struct SettingInfo {
/// Largest value of an int. /// Largest value of an int.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub max: Option<i64>, pub max: Option<i64>,
/// Whether a string is a file path ([`Kind::Path`]): the dialog adds
/// "Browse…" and shows [`check_path`]'s refusals.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub path: bool,
/// Catalog key of the label. /// Catalog key of the label.
pub label_key: &'static str, pub label_key: &'static str,
/// Catalog key of the description. /// Catalog key of the description.
@ -202,7 +248,7 @@ pub const DEFS: &[Def] = &[
}, },
Def { Def {
key: "php.executable", key: "php.executable",
kind: Kind::Str { max_len: 4096 }, kind: Kind::Path { max_len: 4096 },
default: DefaultValue::Str(""), default: DefaultValue::Str(""),
label_key: "settings.php.executable.label", label_key: "settings.php.executable.label",
description_key: "settings.php.executable.description", description_key: "settings.php.executable.description",
@ -210,7 +256,7 @@ pub const DEFS: &[Def] = &[
}, },
Def { Def {
key: "phpactor.path", key: "phpactor.path",
kind: Kind::Str { max_len: 4096 }, kind: Kind::Path { max_len: 4096 },
default: DefaultValue::Str(""), default: DefaultValue::Str(""),
label_key: "settings.phpactor.path.label", label_key: "settings.phpactor.path.label",
description_key: "settings.phpactor.path.description", description_key: "settings.phpactor.path.description",
@ -277,7 +323,7 @@ pub const DEFS: &[Def] = &[
}, },
Def { Def {
key: "git.executable", key: "git.executable",
kind: Kind::Str { max_len: 4096 }, kind: Kind::Path { max_len: 4096 },
default: DefaultValue::Str(""), default: DefaultValue::Str(""),
label_key: "settings.git.executable.label", label_key: "settings.git.executable.label",
description_key: "settings.git.executable.description", description_key: "settings.git.executable.description",
@ -651,6 +697,44 @@ mod tests {
assert_eq!(s.get("editor.fontSize"), Some(json!(14))); assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
} }
#[test]
fn path_settings_refuse_quotes_padding_and_control_characters() {
let mut s = Settings::in_memory();
for key in ["php.executable", "phpactor.path", "git.executable"] {
for good in ["", r"C:\php\php.exe", "/opt/my php/php", "'"] {
assert!(s.set(key, json!(good)).is_ok(), "{key} {good:?}");
}
for (bad, reason) in [
(" php", "spaces"),
("php ", "spaces"),
(r#""C:\Program Files\php\php.exe""#, "quotes"),
("'/opt/php'", "quotes"),
(r#" "/opt/php" "#, "quotes"),
("/opt/php\t", "control"),
("/opt/\u{7f}php", "control"),
] {
let Err(SetError::Invalid(message)) = s.set(key, json!(bad)) else {
panic!("{key} accepted {bad:?}");
};
assert!(message.starts_with(&format!("{key}: ")), "{message}");
assert!(message.contains(reason), "{message}");
}
assert!(s.set(key, json!("x".repeat(4097))).is_err());
assert!(s.set(key, json!(1)).is_err());
assert!(DEFS.iter().any(|d| d.key == key && d.info().path));
}
assert!(!DEFS.iter().any(|d| d.key == "editor.fontSize" && d.info().path));
}
#[test]
fn a_stored_padded_path_counts_as_unset() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join(FILE_NAME), r#"{"php.executable": " php"}"#).unwrap();
let (s, problem) = Settings::load(dir.path());
assert!(problem.is_none());
assert_eq!(s.get("php.executable"), Some(json!("")));
}
#[test] #[test]
fn autosave_defaults_and_validation() { fn autosave_defaults_and_validation() {
let mut s = Settings::in_memory(); let mut s = Settings::in_memory();

View file

@ -5,8 +5,9 @@
* *
* The rules work on any string setting `settings.list` reports, so a new * The rules work on any string setting `settings.list` reports, so a new
* one (such as `git.executable`) gets the control without changes here. * one (such as `git.executable`) gets the control without changes here.
* The engine still validates every value; these checks only catch mistakes * Path settings are checked only by the engine (`check_path` in
* early and say how to fix them. * `crates/engine/src/settings.rs`), the one validator shared with
* `settings.set` from agents and the CLI; the dialog shows its reason.
*/ */
import { t } from "../../i18n"; import { t } from "../../i18n";
import type { SettingDef } from "../../stores/settings"; import type { SettingDef } from "../../stores/settings";
@ -14,9 +15,6 @@ import type { SettingDef } from "../../stores/settings";
/** Longest value in UTF-8 bytes; the engine's limit for string settings. */ /** Longest value in UTF-8 bytes; the engine's limit for string settings. */
export const MAX_STRING_BYTES = 4096; export const MAX_STRING_BYTES = 4096;
/** Endings of a key's last segment that mark a path setting. */
const PATH_ENDINGS = ["path", "executable"];
/** /**
* Whether a text has control characters (U+0000–U+001F, U+007F), which no * Whether a text has control characters (U+0000–U+001F, U+007F), which no
* single-line setting needs. * single-line setting needs.
@ -34,18 +32,13 @@ function hasControlChars(text: string): boolean {
} }
/** /**
* Whether a setting holds a file path: a string setting whose key ends in * Whether a setting holds a file path: a string setting the engine marks
* `path` or `executable` (`phpactor.path`, `php.executable`, * with `path` (`php.executable`, `phpactor.path`, `git.executable`).
* `git.executable`, `x.pharPath`).
* *
* @param def - the setting. * @param def - the setting.
*/ */
export function isPathSetting(def: SettingDef): boolean { export function isPathSetting(def: SettingDef): boolean {
if (def.type !== "string") { return def.type === "string" && def.path;
return false;
}
const last = (def.key.split(".").at(-1) ?? "").toLowerCase();
return PATH_ENDINGS.some((ending) => last.endsWith(ending));
} }
/** /**
@ -60,32 +53,24 @@ export function placeholderOf(def: SettingDef): string {
} }
/** /**
* Checks a typed value before it goes to `settings.set`. * Checks a typed value before it goes to `settings.set`: longer than
* * {@link MAX_STRING_BYTES} UTF-8 bytes, or with control characters, is
* - Longer than {@link MAX_STRING_BYTES} UTF-8 bytes, or with control * refused. Paths are left to the engine, which refuses the same and
* characters: refused for every string setting. * quoted or padded paths too.
* - Paths: refused when wrapped in quotes (as copied from a shell or the
* file manager) or with spaces at either end.
* *
* @param def - the setting. * @param def - the setting.
* @param text - the typed value. * @param text - the typed value.
* @returns the error text from the catalog, or null when the value may be sent. * @returns the error text from the catalog, or null when the value may be sent.
*/ */
export function checkString(def: SettingDef, text: string): string | null { export function checkString(def: SettingDef, text: string): string | null {
if (isPathSetting(def)) {
return null;
}
if (new TextEncoder().encode(text).length > MAX_STRING_BYTES) { if (new TextEncoder().encode(text).length > MAX_STRING_BYTES) {
return t("settings.error.stringTooLong", { max: MAX_STRING_BYTES }); return t("settings.error.stringTooLong", { max: MAX_STRING_BYTES });
} }
if (hasControlChars(text)) { if (hasControlChars(text)) {
return t("settings.error.stringControl"); return t("settings.error.stringControl");
} }
if (!isPathSetting(def)) {
return null;
}
if (/^\s*(["']).*\1\s*$/.test(text) && text.trim().length >= 2) {
return t("settings.error.pathQuoted");
}
if (text !== text.trim()) {
return t("settings.error.pathSpaces");
}
return null; return null;
} }

View file

@ -301,8 +301,6 @@
"settings.error.browseFailed": "The file picker could not open: {message}", "settings.error.browseFailed": "The file picker could not open: {message}",
"settings.error.int": "Enter a whole number", "settings.error.int": "Enter a whole number",
"settings.error.intRange": "Enter a whole number from {min} to {max}", "settings.error.intRange": "Enter a whole number from {min} to {max}",
"settings.error.pathQuoted": "Remove the quotes around the path",
"settings.error.pathSpaces": "Remove the spaces at the start or end of the path",
"settings.error.stringControl": "Remove tabs, line breaks and other control characters", "settings.error.stringControl": "Remove tabs, line breaks and other control characters",
"settings.error.stringTooLong": "Enter at most {max} bytes", "settings.error.stringTooLong": "Enter at most {max} bytes",
"settings.git.executable.description": "Path to the git program (2.30 or newer) that Lutra runs for version control. Leave empty to use git from PATH.", "settings.git.executable.description": "Path to the git program (2.30 or newer) that Lutra runs for version control. Leave empty to use git from PATH.",

View file

@ -254,6 +254,17 @@ export interface EngineError {
message: string; message: string;
} }
/**
* The part of an engine error's message meant for a person: the reason
* without the engine's `invalid params for <command>: ` prefix, which
* only repeats the command the caller just ran.
*
* @param error - the error.
*/
export function userMessage(error: EngineError): string {
return error.code === "invalid_params" ? error.message.replace(/^invalid params for [^:\s]+: /, "") : error.message;
}
/** Outcome of an engine call. */ /** Outcome of an engine call. */
export type RunResult<T> = { ok: true; value: T } | { ok: false; error: EngineError }; export type RunResult<T> = { ok: true; value: T } | { ok: false; error: EngineError };

View file

@ -19,7 +19,7 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { reactive, ref } from "vue"; import { reactive, ref } from "vue";
import { hasMessage, t } from "../i18n"; import { hasMessage, t } from "../i18n";
import { onEngineEvent, run, type EngineEventPayload } from "../ipc"; import { onEngineEvent, run, userMessage, type EngineError, type EngineEventPayload } from "../ipc";
import { setTokenOverride } from "../theme"; import { setTokenOverride } from "../theme";
/** A setting value: settings are scalars. Values from the engine are unchecked. */ /** A setting value: settings are scalars. Values from the engine are unchecked. */
@ -48,6 +48,8 @@ export interface SettingDef {
descriptionKey: string; descriptionKey: string;
/** Section id; shown with `settings.section.<id>`. */ /** Section id; shown with `settings.section.<id>`. */
section: string; section: string;
/** Whether a string setting holds a file path (the engine's `path` flag). */
path: boolean;
} }
/** A section of the dialog with its settings, in engine order. */ /** A section of the dialog with its settings, in engine order. */
@ -118,6 +120,7 @@ function toSettingDef(raw: unknown): SettingDef | null {
labelKey, labelKey,
descriptionKey, descriptionKey,
section, section,
path: type === "string" && entry.path === true,
}; };
} }
@ -330,7 +333,8 @@ export const useSettingsStore = defineStore("settings", () => {
} }
/** /**
* Stores the outcome of `settings.set` or `settings.reset`. * Stores the outcome of `settings.set` or `settings.reset`. A refusal is
* kept as its reason, without the engine's command and key prefixes.
* *
* @param key - the setting. * @param key - the setting.
* @param result - the command's outcome. * @param result - the command's outcome.
@ -338,10 +342,11 @@ export const useSettingsStore = defineStore("settings", () => {
*/ */
function settle( function settle(
key: string, key: string,
result: { ok: true; value: unknown } | { ok: false; error: { message: string } }, result: { ok: true; value: unknown } | { ok: false; error: EngineError },
): boolean { ): boolean {
if (!result.ok) { if (!result.ok) {
errors[key] = clip(result.error.message); const message = userMessage(result.error);
errors[key] = clip(message.startsWith(`${key}: `) ? message.slice(key.length + 2) : message);
return false; return false;
} }
Reflect.deleteProperty(errors, key); Reflect.deleteProperty(errors, key);

View file

@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn()); const invoke = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke })); vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { listCommands, run, runWaiting, toEngineError } from "../src/ipc"; import { listCommands, run, runWaiting, toEngineError, userMessage } from "../src/ipc";
describe("run", () => { describe("run", () => {
beforeEach(() => { beforeEach(() => {
@ -66,3 +66,13 @@ describe("toEngineError", () => {
expect(toEngineError({ code: 1, message: "x" }).code).toBe("ipc"); expect(toEngineError({ code: 1, message: "x" }).code).toBe("ipc");
}); });
}); });
describe("userMessage", () => {
it("drops the engine's invalid params prefix and keeps other messages", () => {
expect(userMessage({ code: "invalid_params", message: "invalid params for search.find: unclosed group" })).toBe(
"unclosed group",
);
expect(userMessage({ code: "failed", message: "invalid params for x.y: z" })).toBe("invalid params for x.y: z");
expect(userMessage({ code: "invalid_params", message: "missing path" })).toBe("missing path");
});
});

View file

@ -361,13 +361,13 @@ describe("settings dialog", () => {
expect((input().element as HTMLInputElement).value).toBe("20"); expect((input().element as HTMLInputElement).value).toBe("20");
}); });
it("shows the engine's error for a value it refuses", async () => { it("shows the engine's error for a value it refuses, without the key the row already names", async () => {
const wrapper = await mountDialog(); const wrapper = await mountDialog();
await open(wrapper); await open(wrapper);
await useSettingsStore(pinia).set("editor.fontSize", 2); await useSettingsStore(pinia).set("editor.fontSize", 2);
await wrapper.find("[data-section=editor]").trigger("click"); await wrapper.find("[data-section=editor]").trigger("click");
expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe( expect(row(wrapper, "editor.fontSize").find("[data-test=settings-error]").text()).toBe(
"editor.fontSize: expected an integer from 8 to 48", "expected an integer from 8 to 48",
); );
}); });

View file

@ -40,6 +40,7 @@ function stringEntry(key: string, section: string): Record<string, unknown> {
labelKey: `settings.${key}.label`, labelKey: `settings.${key}.label`,
descriptionKey: `settings.${key}.description`, descriptionKey: `settings.${key}.description`,
section, section,
path: /(path|executable)$/i.test(key),
}; };
} }
@ -159,6 +160,10 @@ beforeEach(() => {
return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) }); return Promise.resolve({ values: Object.fromEntries(keys.map((k) => [k, values[k]])) });
} }
case "settings.set": case "settings.set":
if (typeof params.value === "string" && params.value.startsWith('"')) {
const message = `invalid params for settings.set: ${String(params.key)}: Remove the quotes around the path`;
return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message }));
}
if (params.value === "/does/not/exist") { if (params.value === "/does/not/exist") {
return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" })); return Promise.reject(Object.assign(new Error("x"), { code: "invalid_params", message: "no such file" }));
} }
@ -182,12 +187,13 @@ afterEach(() => {
}); });
describe("string setting rules", () => { describe("string setting rules", () => {
it("treats keys ending in path or executable as paths", () => { it("treats the settings the engine marks as paths as paths", () => {
expect(isPathSetting(defOf("php.executable"))).toBe(true); expect(isPathSetting(defOf("php.executable"))).toBe(true);
expect(isPathSetting(defOf("phpactor.path"))).toBe(true); expect(isPathSetting(defOf("phpactor.path"))).toBe(true);
expect(isPathSetting(defOf("git.executable"))).toBe(true); expect(isPathSetting(defOf("git.executable"))).toBe(true);
expect(isPathSetting(defOf("x.pharPath"))).toBe(true); expect(isPathSetting(defOf("x.pharPath"))).toBe(true);
expect(isPathSetting(defOf("editor.name"))).toBe(false); expect(isPathSetting(defOf("editor.name"))).toBe(false);
expect(isPathSetting({ ...defOf("php.executable"), path: false })).toBe(false);
expect(isPathSetting({ ...defOf("php.executable"), type: "int" })).toBe(false); expect(isPathSetting({ ...defOf("php.executable"), type: "int" })).toBe(false);
}); });
@ -197,16 +203,16 @@ describe("string setting rules", () => {
expect(placeholderOf(defOf("editor.name"))).toBe(""); expect(placeholderOf(defOf("editor.name"))).toBe("");
}); });
it("refuses long texts, control characters, quoted and padded paths", () => { it("refuses long texts and control characters, and leaves paths to the engine", () => {
const php = defOf("php.executable"); const php = defOf("php.executable");
const name = defOf("editor.name"); const name = defOf("editor.name");
expect(checkString(php, "C:\\php\\php.exe")).toBeNull(); expect(checkString(php, "C:\\php\\php.exe")).toBeNull();
expect(checkString(php, "")).toBeNull(); expect(checkString(php, "")).toBeNull();
expect(checkString(php, "/opt/my php/php")).toBeNull(); expect(checkString(php, "/opt/my php/php")).toBeNull();
expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBe("Remove the quotes around the path"); expect(checkString(php, '"C:\\Program Files\\php\\php.exe"')).toBeNull();
expect(checkString(php, "'/opt/php'")).toBe("Remove the quotes around the path"); expect(checkString(php, "'/opt/php'")).toBeNull();
expect(checkString(php, " /opt/php")).toBe("Remove the spaces at the start or end of the path"); expect(checkString(php, " /opt/php")).toBeNull();
expect(checkString(php, "/opt/php\t")).toBe("Remove tabs, line breaks and other control characters"); expect(checkString(php, "/opt/php\t")).toBeNull();
expect(checkString(name, " padded is fine ")).toBeNull(); expect(checkString(name, " padded is fine ")).toBeNull();
expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2))).toBeNull(); expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2))).toBeNull();
expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2 + 1))).toBe(`Enter at most ${String(MAX_STRING_BYTES)} bytes`); expect(checkString(name, "ä".repeat(MAX_STRING_BYTES / 2 + 1))).toBe(`Enter at most ${String(MAX_STRING_BYTES)} bytes`);
@ -238,16 +244,16 @@ describe("string and path controls", () => {
expect(row(wrapper, "php.executable").find("[data-test=settings-error]").exists()).toBe(false); expect(row(wrapper, "php.executable").find("[data-test=settings-error]").exists()).toBe(false);
}); });
it("refuses a quoted path in place and keeps the typed text", async () => { it("shows the engine's refusal of a quoted path in place and keeps the typed text", async () => {
const wrapper = await openDialog(); const wrapper = await openDialog();
await commit(wrapper, "php.executable", '"C:\\php\\php.exe"'); await commit(wrapper, "php.executable", '"C:\\php\\php.exe"');
expect(sets()).toEqual([]); expect(sets()).toEqual([{ key: "php.executable", value: '"C:\\php\\php.exe"' }]);
const php = row(wrapper, "php.executable"); const php = row(wrapper, "php.executable");
expect(php.find("[data-test=settings-error]").text()).toBe("Remove the quotes around the path"); expect(php.find("[data-test=settings-error]").text()).toBe("Remove the quotes around the path");
expect(php.find("input").attributes("aria-invalid")).toBe("true"); expect(php.find("input").attributes("aria-invalid")).toBe("true");
expect((php.find("input").element as HTMLInputElement).value).toBe('"C:\\php\\php.exe"'); expect((php.find("input").element as HTMLInputElement).value).toBe('"C:\\php\\php.exe"');
await commit(wrapper, "php.executable", "C:\\php\\php.exe"); await commit(wrapper, "php.executable", "C:\\php\\php.exe");
expect(sets()).toEqual([{ key: "php.executable", value: "C:\\php\\php.exe" }]); expect(sets().at(-1)).toEqual({ key: "php.executable", value: "C:\\php\\php.exe" });
expect(php.find("[data-test=settings-error]").exists()).toBe(false); expect(php.find("[data-test=settings-error]").exists()).toBe(false);
}); });