From 045235d30d53bb3ae408812fe8974b2583c42fb1 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 07:20:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(toolchain):=20=E5=8F=AF=E4=BF=A1=E4=BD=8D?= =?UTF-8?q?=E7=BD=AE=E5=8F=AF=E4=BB=A5=E5=8D=95=E7=8B=AC=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=92=8C=E5=88=A0=E9=99=A4=EF=BC=8C=E6=8B=92=E7=BB=9D=E6=8A=8A?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E7=B3=BB=E7=BB=9F=E6=A0=B9=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E8=AE=BE=E4=B8=BA=E5=8F=AF=E4=BF=A1=E4=BD=8D=E7=BD=AE=EF=BC=88?= =?UTF-8?q?#2207=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit toolchains.editCatalog 新增 trustedLocations: {add?, remove?},供没有打开工作区的设置页增删可信位置:按平台大小写身份匹配,删除不存在的位置不算修改,已存在的位置保留原有写法,工作区上的明确决定不受影响。添加文件系统根目录(/、盘符、UNC 共享)返回 plugin.toolchain.rootLocation;手写进文档的根目录位置在读取时被拒绝,工作区保持安全模式。信任列表超过 256 项改为返回 plugin.toolchain.trustListFull(含原来 workspaceTrust 的超限),宿主可以提示“列表已满”而不是“文档无效”。offered_location 改用 paths::is_root 判断根目录。schema 补上 #118 漏掉的 distrustedWorkspaces 和 trustedLocations。 --- rust/contracts/rust-core-api.md | 26 +- .../contracts/toolchain-global-v1.schema.json | 20 ++ rust/crates/toolchain/src/catalog.rs | 304 ++++++++++++++++-- rust/crates/toolchain/src/paths.rs | 7 + rust/fixtures/toolchain-global-catalog.json | 84 +++++ 5 files changed, 414 insertions(+), 27 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5c023c65..c7043843 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -535,7 +535,7 @@ or removing a command fails until the table changes in the same commit. | `toolchains.resolvePins` | Validate a captured local document and find the nearest ancestor directory pin, retaining dormant and legacy entries without probing or writing | | `toolchains.editPins` | Apply one bounded batch of directory pin edits to a captured local document without writing native files | | `toolchains.catalogState` | Validate machine-wide SDK registrations and optional workspace project-code trust without a project | -| `toolchains.editCatalog` | Merge confirmed machine-wide SDK registrations, defaults and explicit workspace project-code trust | +| `toolchains.editCatalog` | Merge confirmed machine-wide SDK registrations, defaults, explicit workspace project-code trust and trusted location changes | | `toolchains.pinStoragePlan` | Declare bounded workspace-native pin and ignore sources | | `toolchains.decodePinDocument` | Validate a complete native source or supply the absent-source default | | `toolchains.editPinSources` | Plan deterministic pin and Git ignore source edits without native I/O | @@ -7758,27 +7758,41 @@ applies first, then a trusted location containing it: `state` is `trusted`, `dis `unknown` when the user has not been asked. `location` is the trusted location that trusts the workspace, else `null`. `offeredLocation` is the parent folder a trust prompt may offer to trust with the workspace, or `null` when that parent is a filesystem root (`/`, a drive, a UNC share). +A filesystem root is never a trusted location: a document listing one (no edit writes it) is +rejected at `trustedLocations`, so its workspaces stay in safe mode rather than every project +on the volume being trusted. The two newer lists are written only once used, so a document without them stays readable by hosts that predate them. Native clients resolve the relative path below their platform user-preference directory, never below a workspace, SDK, installed package or application bundle. Reading an absent source returns `{version:1,tools:{}}` and must not create a directory or file. -`toolchains.editCatalog` accepts `{document:string|null,platform,filesystemCaseSensitive?,edits?,workspaceTrust?}`, -where at least one of a nonempty `edits` array of `{tool,homes:[absoluteHome],defaultHome:string|null}` -or `workspaceTrust:{workspace,trusted,location?}` is required. Each tool edit replaces only that tool's +`toolchains.editCatalog` accepts `{document:string|null,platform,filesystemCaseSensitive?,edits?,workspaceTrust?,trustedLocations?}`, +where at least one of a nonempty `edits` array of `{tool,homes:[absoluteHome],defaultHome:string|null}`, +`workspaceTrust:{workspace,trusted,location?}` or `trustedLocations:{add?:[absolutePath],remove?:[absolutePath]}` +is required. Each tool edit replaces only that tool's registrations and default; other tools, dormant plugins and the trust lists remain intact. `workspaceTrust` records one decision on one normalized workspace root, preserving `tools` and other decisions: `trusted: true` moves it to `trustedWorkspaces`, `trusted: false` to `distrustedWorkspaces` (safe mode), and `location: true` also adds its `offeredLocation` to `trustedLocations`; `location` with `trusted: false`, or without an offered location, rejects at -`workspaceTrust.location`. At most +`workspaceTrust.location`. +`trustedLocations` changes the trusted folders on their own, for a settings page without an +open workspace, and applies after `workspaceTrust` when both are present. Paths are normalized +and matched by platform case identity: `remove` drops each named folder, a folder that is not +trusted changes nothing, and `add` keeps the recorded spelling of a folder already trusted. +`add` and `remove` cannot both be empty or name one folder. Adding a filesystem root (`/`, a +drive, a UNC share) rejects with `plugin.toolchain.rootLocation` at `trustedLocations.add`. +Workspace decisions are untouched: a workspace kept in safe mode stays there inside a newly +trusted location. +An edit that would leave `trustedWorkspaces`, `distrustedWorkspaces` or `trustedLocations` +longer than 256 entries rejects with `plugin.toolchain.trustListFull` at that list's name. At most 64 tools and 32 distinct homes per tool are accepted. Native platform path normalization and case identity apply before deduplication. A selected default is registered if needed; null clears only the default. Empty registrations plus null remove the tool entry. The result is `{status:"ok",edit:{changed,document:string|null,catalog}}`; unchanged edits return a null replacement and must not create a source. Invalid shapes, duplicate JSON keys, -unknown fields, relative homes, aliases and oversized documents reject with +unknown fields, relative homes or paths, aliases and oversized documents reject with `plugin.toolchain.invalidDocument`. The schema is [`toolchain-global-v1.schema.json`](toolchain-global-v1.schema.json); cross-client vectors are in `rust/fixtures/toolchain-global-catalog.json`. diff --git a/rust/contracts/toolchain-global-v1.schema.json b/rust/contracts/toolchain-global-v1.schema.json index 629112ba..d78bb2a5 100644 --- a/rust/contracts/toolchain-global-v1.schema.json +++ b/rust/contracts/toolchain-global-v1.schema.json @@ -46,6 +46,26 @@ "type": "string", "minLength": 1 } + }, + "distrustedWorkspaces": { + "description": "Workspaces the user chose to keep in safe mode; an explicit decision wins over a trusted location containing it.", + "type": "array", + "maxItems": 256, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1 + } + }, + "trustedLocations": { + "description": "Folders whose every workspace, at any depth, is trusted unless distrusted itself. Never a filesystem root.", + "type": "array", + "maxItems": 256, + "uniqueItems": true, + "items": { + "type": "string", + "minLength": 1 + } } } } diff --git a/rust/crates/toolchain/src/catalog.rs b/rust/crates/toolchain/src/catalog.rs index 4c992d47..f652ca0d 100644 --- a/rust/crates/toolchain/src/catalog.rs +++ b/rust/crates/toolchain/src/catalog.rs @@ -84,6 +84,17 @@ struct WorkspaceTrustEdit { location: bool, } +/// Folders added to or removed from `trustedLocations` on their own, as on a +/// trusted locations settings page. Removing an absent folder changes nothing. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TrustedLocationsEdit { + #[serde(default)] + add: Vec, + #[serde(default)] + remove: Vec, +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct EditRequest { @@ -95,6 +106,8 @@ struct EditRequest { edits: Vec, #[serde(default)] workspace_trust: Option, + #[serde(default)] + trusted_locations: Option, } fn invalid(field: &str) -> PluginRejection { @@ -105,6 +118,25 @@ fn invalid(field: &str) -> PluginRejection { ) } +/// A filesystem root as a trusted location would trust every project on the volume. +fn root_location(field: &str) -> PluginRejection { + PluginRejection::at( + "plugin.toolchain.rootLocation", + field, + "A filesystem root cannot be a trusted location.", + ) +} + +/// An edit that would leave a trust list longer than [`MAX_TRUST_ENTRIES`]. Not +/// `plugin.toolchain.limitExceeded`, which is a provider reply budget. +fn trust_list_full(field: &str) -> PluginRejection { + PluginRejection::at( + "plugin.toolchain.trustListFull", + field, + "A trust list holds at most 256 paths.", + ) +} + impl Request { fn case_sensitive(&self) -> Validation { if !matches!(self.platform.as_str(), "macos" | "windows" | "linux") { @@ -211,6 +243,15 @@ impl Request { self.trust_list(&catalog.distrusted_workspaces, "distrustedWorkspaces")?; catalog.trusted_locations = self.trust_list(&catalog.trusted_locations, "trustedLocations")?; + // No edit writes a root, so a root here was written by hand; refusing the + // document keeps every workspace in safe mode instead of trusting the volume. + if catalog + .trusted_locations + .iter() + .any(|location| paths::is_root(location)) + { + return Err(invalid("trustedLocations")); + } Ok(catalog) } @@ -252,14 +293,9 @@ impl Request { fn offered_location(&self, workspace: &str) -> Option { let path = paths::normalize(workspace, &self.platform, true)?; let (parent, _) = path.rsplit_once('/')?; - let root = parent.is_empty() - || (self.platform == "windows" - && (parent.len() == 2 && parent.ends_with(':') - || parent.starts_with("//") && parent[2..].split('/').count() <= 2)); - if root { - return None; - } - paths::normalize(parent, &self.platform, true) + // `/app` leaves an empty parent and `D:/app` leaves `D:`, neither of which + // normalizes; a UNC share root normalizes with its trailing separator. + paths::normalize(parent, &self.platform, true).filter(|parent| !paths::is_root(parent)) } } @@ -291,12 +327,17 @@ pub(crate) fn state(input: &Value) -> Validation { Ok(response) } -/// Merges confirmed tool edits and one explicit machine-local workspace trust decision, -/// preserving dormant registrations and the other trust decisions. +/// Merges confirmed tool edits, one explicit machine-local workspace trust decision +/// and trusted location changes, preserving dormant registrations and the other +/// trust decisions. pub(crate) fn edit(input: &Value) -> Validation { let request: EditRequest = serde_json::from_value(input.clone()).map_err(|_| invalid("input"))?; - if (request.edits.is_empty() && request.workspace_trust.is_none()) || request.edits.len() > 64 { + if (request.edits.is_empty() + && request.workspace_trust.is_none() + && request.trusted_locations.is_none()) + || request.edits.len() > 64 + { return Err(invalid("edits")); } let source = Request { @@ -355,19 +396,41 @@ pub(crate) fn edit(input: &Value) -> Validation { locations.entry(key).or_insert(location); catalog.trusted_locations = locations.into_values().collect(); } - if [ - trusted.len(), - distrusted.len(), - catalog.trusted_locations.len(), - ] - .iter() - .any(|len| *len > MAX_TRUST_ENTRIES) - { - return Err(invalid("workspaceTrust")); - } catalog.trusted_workspaces = trusted.into_values().collect(); catalog.distrusted_workspaces = distrusted.into_values().collect(); } + if let Some(change) = request.trusted_locations { + if change.add.is_empty() && change.remove.is_empty() { + return Err(invalid("trustedLocations")); + } + let add = source.trust_keys(&change.add, "trustedLocations.add")?; + let remove = source.trust_keys(&change.remove, "trustedLocations.remove")?; + if add.values().any(|location| paths::is_root(location)) { + return Err(root_location("trustedLocations.add")); + } + // Adding and removing one folder at once has no single meaning. + if add.keys().any(|key| remove.contains_key(key)) { + return Err(invalid("trustedLocations")); + } + let mut locations = source.trust_keys(&catalog.trusted_locations, "trustedLocations")?; + for key in remove.keys() { + locations.remove(key); + } + for (key, location) in add { + // A folder already trusted keeps its recorded spelling. + locations.entry(key).or_insert(location); + } + catalog.trusted_locations = locations.into_values().collect(); + } + for (len, field) in [ + (catalog.trusted_workspaces.len(), "trustedWorkspaces"), + (catalog.distrusted_workspaces.len(), "distrustedWorkspaces"), + (catalog.trusted_locations.len(), "trustedLocations"), + ] { + if len > MAX_TRUST_ENTRIES { + return Err(trust_list_full(field)); + } + } let changed = catalog != original; let document = if changed { let text = serde_json::to_string_pretty(&catalog).map_err(|_| invalid("document"))? + "\n"; @@ -660,4 +723,203 @@ mod tests { })) .is_err()); } + + /// The code and field of a refused request. + fn refusal(result: Validation) -> (&'static str, String) { + let rejection = result.expect_err("refused"); + (rejection.code, rejection.field.unwrap_or_default()) + } + + // The settings page adds and removes folders without a workspace: paths are + // normalized, a folder is matched whatever its spelling, adding a folder already + // trusted or removing an absent one changes nothing, and registrations and + // workspace decisions stay. + #[test] + fn trusted_locations_are_added_and_removed_on_their_own() { + for (platform, folder, spelling, other, absent, distrusted) in [ + ( + "macos", + "/Users/dev/code/", + "/Users/dev/code", + "/Volumes/Work/src", + "/Users/dev/absent", + "/Users/dev/code/app", + ), + ( + "windows", + r"C:\Code\", + "c:/code", + r"\\server\share\src", + r"D:\Absent", + r"C:\code\App", + ), + ] { + let normalized = |path: &str| paths::normalize(path, platform, true).unwrap(); + let document = json!({ + "version": 1, + "tools": {"vm": {"homes": [other]}}, + "distrustedWorkspaces": [distrusted] + }) + .to_string(); + let added = edit(&json!({ + "document": document, + "platform": platform, + "trustedLocations": {"add": [folder, other]} + })) + .unwrap(); + assert_eq!(added["changed"], true, "{platform}"); + let mut locations: Vec = + serde_json::from_value(added["catalog"]["trustedLocations"].clone()).unwrap(); + locations.sort(); + let mut expected = vec![normalized(folder), normalized(other)]; + expected.sort(); + assert_eq!(locations, expected, "{platform}"); + assert_eq!( + added["catalog"]["tools"]["vm"]["homes"], + json!([normalized(other)]), + "{platform}" + ); + // A workspace kept in safe mode stays there inside a new location. + assert_eq!( + trust(&added["document"], platform, distrusted)["state"], + "distrusted", + "{platform}" + ); + + let unchanged = edit(&json!({ + "document": added["document"], + "platform": platform, + "trustedLocations": {"add": [spelling], "remove": [absent]} + })) + .unwrap(); + assert_eq!(unchanged["changed"], false, "{platform}"); + assert_eq!(unchanged["document"], Value::Null, "{platform}"); + + let removed = edit(&json!({ + "document": added["document"], + "platform": platform, + "trustedLocations": {"remove": [spelling]} + })) + .unwrap(); + assert_eq!( + removed["catalog"]["trustedLocations"], + json!([normalized(other)]), + "{platform}" + ); + assert_eq!( + removed["catalog"]["distrustedWorkspaces"], + json!([normalized(distrusted)]), + "{platform}" + ); + } + } + + // A filesystem root as a location would trust every project on the volume: no + // edit adds one, even next to a valid folder, and a document naming one, written + // by hand, is refused so its workspaces stay in safe mode. + #[test] + fn a_filesystem_root_is_never_added_or_read_as_a_location() { + for (platform, root, folder) in [ + ("macos", "/", "/Users/dev/code"), + ("linux", "//", "/srv/code"), + ("windows", r"D:\", r"D:\Code"), + ("windows", "c:/", r"C:\Code"), + ("windows", r"\\server\share", r"\\server\share\code"), + ("windows", r"\\server\share\", r"\\server\share\code"), + ] { + for add in [json!([root]), json!([folder, root])] { + assert_eq!( + refusal(edit(&json!({ + "document": null, + "platform": platform, + "trustedLocations": {"add": add} + }))), + ( + "plugin.toolchain.rootLocation", + "trustedLocations.add".into() + ), + "{platform} {add}" + ); + } + let document = json!({"version": 1, "tools": {}, "trustedLocations": [root]}); + assert_eq!( + refusal(state(&json!({ + "document": document.to_string(), + "platform": platform, + "workspaceRoot": folder + }))), + ( + "plugin.toolchain.invalidDocument", + "trustedLocations".into() + ), + "{platform} {root}" + ); + } + } + + #[test] + fn a_trusted_locations_edit_must_name_one_meaning_per_folder() { + for change in [ + json!({}), + json!({"add": [], "remove": []}), + json!({"add": ["/srv/code"], "remove": ["/srv/code/"]}), + json!({"add": ["/srv/code", "/srv/code/"]}), + json!({"add": ["srv/code"]}), + json!({"add": ["/srv/../code"]}), + json!({"add": ["/srv/code"], "parents": true}), + ] { + assert_eq!( + refusal(edit(&json!({ + "document": null, + "platform": "linux", + "trustedLocations": change + }))) + .0, + "plugin.toolchain.invalidDocument", + "{change}" + ); + } + } + + // Each trust list stops at its bound with its own code, so a host can say the + // list is full rather than that the document is invalid; removing one folder + // in the same edit makes room for another. + #[test] + fn a_trust_list_never_grows_past_its_bound() { + let full: Vec = (0..MAX_TRUST_ENTRIES) + .map(|index| format!("/srv/{index:03}")) + .collect(); + let locations = json!({"version": 1, "tools": {}, "trustedLocations": full}).to_string(); + assert_eq!( + refusal(edit(&json!({ + "document": locations, + "platform": "linux", + "trustedLocations": {"add": ["/srv/new"]} + }))), + ("plugin.toolchain.trustListFull", "trustedLocations".into()) + ); + let swapped = edit(&json!({ + "document": locations, + "platform": "linux", + "trustedLocations": {"add": ["/srv/new"], "remove": ["/srv/000"]} + })) + .unwrap(); + assert_eq!( + swapped["catalog"]["trustedLocations"] + .as_array() + .unwrap() + .len(), + MAX_TRUST_ENTRIES + ); + + let workspaces = json!({"version": 1, "tools": {}, "trustedWorkspaces": full}).to_string(); + assert_eq!( + refusal(edit(&json!({ + "document": workspaces, + "platform": "linux", + "workspaceTrust": {"workspace": "/srv/new", "trusted": true} + }))), + ("plugin.toolchain.trustListFull", "trustedWorkspaces".into()) + ); + } } diff --git a/rust/crates/toolchain/src/paths.rs b/rust/crates/toolchain/src/paths.rs index 105d21c6..7667ac5b 100644 --- a/rust/crates/toolchain/src/paths.rs +++ b/rust/crates/toolchain/src/paths.rs @@ -72,6 +72,13 @@ pub fn normalize(path: &str, platform: &str, case_sensitive: bool) -> Option bool { + normalized.ends_with('/') +} + /// Compares complete native path components with target-platform case rules. pub fn within(path: &str, root: &str, platform: &str, case_sensitive: bool) -> bool { let Some(path) = normalize(path, platform, case_sensitive) else { diff --git a/rust/fixtures/toolchain-global-catalog.json b/rust/fixtures/toolchain-global-catalog.json index cd903307..595ec4df 100644 --- a/rust/fixtures/toolchain-global-catalog.json +++ b/rust/fixtures/toolchain-global-catalog.json @@ -176,6 +176,90 @@ } } } + }, + { + "name": "trusted-location-added-and-absent-one-removed-without-a-workspace", + "command": "toolchains.editCatalog", + "input": { + "document": "{\"version\":1,\"tools\":{},\"trustedWorkspaces\":[\"/Users/dev/app\"]}", + "platform": "macos", + "trustedLocations": { + "add": [ + "/Users/dev/code/" + ], + "remove": [ + "/Users/dev/old" + ] + } + }, + "expected": { + "status": "ok", + "edit": { + "changed": true, + "document": "{\n \"version\": 1,\n \"tools\": {},\n \"trustedWorkspaces\": [\n \"/Users/dev/app\"\n ],\n \"trustedLocations\": [\n \"/Users/dev/code\"\n ]\n}\n", + "catalog": { + "version": 1, + "tools": {}, + "trustedWorkspaces": [ + "/Users/dev/app" + ], + "trustedLocations": [ + "/Users/dev/code" + ] + } + } + } + }, + { + "name": "trusted-location-removed-by-platform-identity", + "command": "toolchains.editCatalog", + "input": { + "document": "{\"version\":1,\"tools\":{},\"trustedLocations\":[\"C:/Code\",\"D:/Work\"]}", + "platform": "windows", + "trustedLocations": { + "remove": [ + "c:\\code\\" + ] + } + }, + "expected": { + "status": "ok", + "edit": { + "changed": true, + "document": "{\n \"version\": 1,\n \"tools\": {},\n \"trustedLocations\": [\n \"D:/Work\"\n ]\n}\n", + "catalog": { + "version": 1, + "tools": {}, + "trustedLocations": [ + "D:/Work" + ] + } + } + } + }, + { + "name": "trusted-location-filesystem-root-refused", + "command": "toolchains.editCatalog", + "input": { + "document": null, + "platform": "windows", + "trustedLocations": { + "add": [ + "D:\\" + ] + } + }, + "error": "plugin.toolchain.rootLocation" + }, + { + "name": "hand-written-root-location-refused", + "command": "toolchains.catalogState", + "input": { + "document": "{\"version\":1,\"tools\":{},\"trustedLocations\":[\"/\"]}", + "platform": "macos", + "workspaceRoot": "/Users/dev/app" + }, + "error": "plugin.toolchain.invalidDocument" } ] }