//! API 1.21 `code.semantics`: read-only LSP semantic queries require capability & trust //! and confine non-virtual target locations to workspace roots. mod common; use ide_core::error::ErrorKind; use ide_host::plugins::{Consent, HostWorkspace, PluginHost}; use ide_host::{Host, HostConfig, ops}; use ide_jsonrpc::{Handler, Peer}; use ide_plugin::{Invocation, Limits}; use parking_lot::Mutex; use serde_json::{Value, json}; use std::{ path::{Path, PathBuf}, sync::Arc, time::Duration, }; use url::Url; const ID: &str = "test.code-semantics"; fn fixture() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/code-semantics") } struct SemanticServer { target_uri: String, outside_uri: String, } impl Handler for SemanticServer { fn on_notification(&self, _: &str, _: Value) {} fn on_request(&self, method: &str, _: Value) -> Result { let range = json!({ "start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 3} }); Ok(match method { "initialize" => json!({"capabilities": { "textDocumentSync": {"openClose": true, "change": 1}, "definitionProvider": true, "hoverProvider": true, "documentSymbolProvider": true }}), "textDocument/definition" => json!([ {"uri": self.target_uri, "range": range}, {"uri": self.outside_uri, "range": range} ]), "textDocument/hover" => json!({"contents": {"kind": "markdown", "value": "type: Sym"}}), "textDocument/documentSymbol" => json!([{ "name": "Sym", "kind": 5, "range": range, "selectionRange": range }]), _ => Value::Null, }) } } #[tokio::test(flavor = "multi_thread")] async fn code_semantics_enforces_capability_trust_and_location_confinement() { let tmp = tempfile::tempdir().unwrap(); let base = dunce::canonicalize(tmp.path()).unwrap(); let root = base.join("project"); let outside = base.join("outside.txt"); std::fs::create_dir(&root).unwrap(); let main_file = root.join("main.txt"); let target_file = root.join("target.txt"); std::fs::write(&main_file, "sym\n").unwrap(); std::fs::write(&target_file, "sym\n").unwrap(); std::fs::write(&outside, "secret\n").unwrap(); let host = Arc::new(Host::new(HostConfig { local_data_dir: tmp.path().join("local"), ..common::host_config(tmp.path()) })); host.open_project("main", &root).unwrap(); let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap(); let port = listener.local_addr().unwrap().port(); let server = Arc::new(SemanticServer { target_uri: Url::from_file_path(&target_file).unwrap().to_string(), outside_uri: Url::from_file_path(&outside).unwrap().to_string(), }); let peers = Arc::new(Mutex::new(Vec::::new())); let (accepted, state) = (peers.clone(), server.clone()); tokio::spawn(async move { while let Ok((stream, _)) = listener.accept().await { let (r, w) = stream.into_split(); accepted.lock().push(Peer::connect(r, w, state.clone())); } }); let cfg: ide_language::LanguageServerConfig = toml::from_str(&format!("name='text-server'\ncommand='no-process-required'\nconnect='127.0.0.1:{port}'")) .unwrap(); let project = host.project("main").unwrap(); project.lsp.set_servers_hook(Box::new(move |_, _| vec![cfg.clone()])); let inv = || Invocation { client: Some("main".into()), workspace_root: Some(root.clone()), ..Default::default() }; // 1. Denied when capability is not granted (even in trusted workspace). ops::project::project_trust_set(&host, root.clone(), true, false).await.unwrap(); let _doc = ops::doc::doc_open(&host, "main", main_file.clone()).await.unwrap(); let denied_plugins = Arc::new( PluginHost::new( tmp.path().join("plugins-denied"), Arc::new(|_: Option<&str>, _| {}), Limits { timeout: Duration::from_secs(5), ..Default::default() }, ) .unwrap(), ); denied_plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host))))); denied_plugins.install_from_dir(&fixture(), &Consent { optional: vec![], signer_change: true }).unwrap(); let p = denied_plugins.clone(); let i = inv(); let err = tokio::task::spawn_blocking(move || p.run_command(ID, "hover", Some("main.txt"), i)) .await .unwrap() .unwrap_err(); assert_eq!(err.kind, ErrorKind::PermissionDenied); // 2. Denied in untrusted project even with Consent::all(). let granted_plugins = Arc::new( PluginHost::new( tmp.path().join("plugins-granted"), Arc::new(|_: Option<&str>, _| {}), Limits { timeout: Duration::from_secs(5), ..Default::default() }, ) .unwrap(), ); granted_plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host))))); granted_plugins.install_from_dir(&fixture(), &Consent::all()).unwrap(); ops::project::project_trust_set(&host, root.clone(), false, false).await.unwrap(); let p = granted_plugins.clone(); let i = inv(); let untrusted = tokio::task::spawn_blocking(move || p.run_command(ID, "hover", Some("main.txt"), i)) .await .unwrap() .unwrap_err(); assert_eq!(untrusted.kind, ErrorKind::PermissionDenied); // 3. Trusted + granted: returns definition (excluding out-of-root target), hover, and symbols. ops::project::project_trust_set(&host, root.clone(), true, false).await.unwrap(); let p = granted_plugins.clone(); let i = inv(); let def = tokio::task::spawn_blocking(move || p.run_command(ID, "definition", Some("main.txt"), i)) .await .unwrap() .unwrap() .unwrap(); assert!(def.contains("target.txt"), "expected target.txt in {def:?}"); assert!(!def.contains("outside.txt"), "outside.txt should be confined: {def:?}"); let p = granted_plugins.clone(); let i = inv(); let hover = tokio::task::spawn_blocking(move || p.run_command(ID, "hover", Some("main.txt"), i)).await.unwrap().unwrap(); assert_eq!(hover.as_deref(), Some("type: Sym")); let p = granted_plugins.clone(); let i = inv(); let symbols = tokio::task::spawn_blocking(move || p.run_command(ID, "symbols", Some("main.txt"), i)).await.unwrap().unwrap(); assert_eq!(symbols.as_deref(), Some("class:Sym")); }