Skip to main content

lean_ctx/lsp/
editor_bridge.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Editor semantic bridges (VS Code, Cursor, Windsurf, …).
3//!
4//! The lean-ctx editor extension serves the JetBrains plugin's loopback HTTP
5//! protocol (`/health`, `/definition`, `/declaration`, `/references`,
6//! `/implementations`, `/type_hierarchy`) from the editor's own language
7//! features, and announces itself with one JSON file per workspace folder in
8//! [`bridge_dir`]. A bridge is matched by its `project_root`, canonicalized
9//! here — not by a hash both sides would have to compute identically.
10//!
11//! Bridges answer read-only semantic queries when no language server of the
12//! router is live and no JetBrains IDE is attached. They never start anything
13//! and `ctx_refactor` never routes edits to them.
14
15use std::collections::HashMap;
16use std::path::{Path, PathBuf};
17use std::sync::{LazyLock, Mutex, PoisonError};
18use std::time::{Duration, Instant};
19
20use serde::Deserialize;
21
22use super::jetbrains_backend::JetBrainsHttpBackend;
23use super::port_discovery::pid_alive;
24
25/// How long a discovery result (found or not) is reused.
26const DISCOVERY_TTL: Duration = Duration::from_secs(10);
27/// A bridge file is a few hundred bytes; anything far larger is not one.
28const MAX_BRIDGE_FILE_BYTES: u64 = 64 * 1024;
29
30/// One announced bridge (the extension's JSON file).
31#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
32pub struct BridgeFile {
33    pub port: u16,
34    pub token: String,
35    pub pid: u32,
36    pub project_root: String,
37    /// Editor id (`vscode`, `cursor`, `windsurf`, …).
38    pub editor: String,
39    #[serde(default)]
40    pub editor_version: String,
41    /// Digest of the installed extensions (and so of the language providers
42    /// that answer): part of the backend identity, so cached answers retire
43    /// when a language extension is updated while the editor version is not.
44    #[serde(default)]
45    pub provider_fingerprint: String,
46}
47
48impl BridgeFile {
49    /// Version part of the identity: editor version plus provider digest.
50    fn version(&self) -> String {
51        let fingerprint: String = self
52            .provider_fingerprint
53            .chars()
54            .filter(char::is_ascii_alphanumeric)
55            .take(12)
56            .collect();
57        if fingerprint.is_empty() {
58            self.editor_version.clone()
59        } else {
60            format!("{}+{fingerprint}", self.editor_version)
61        }
62    }
63
64    /// A backend speaking to this bridge for `project_root`.
65    pub fn backend(&self, project_root: &str) -> JetBrainsHttpBackend {
66        JetBrainsHttpBackend::editor(
67            self.port,
68            self.token.clone(),
69            project_root,
70            self.pid,
71            &self.editor,
72            &self.version(),
73        )
74    }
75
76    /// Backend identity, as cached semantic answers record it.
77    pub fn identity(&self, project_root: &str) -> String {
78        use super::backend::LspBackend;
79        self.backend(project_root).backend_info().identity()
80    }
81}
82
83/// Where extensions announce bridges: `<data dir>/editor-bridges`.
84pub fn bridge_dir() -> Option<PathBuf> {
85    crate::core::data_dir::lean_ctx_data_dir()
86        .ok()
87        .map(|d| d.join("editor-bridges"))
88}
89
90/// [`bridge_dir`], created owner-only — for `lean-ctx editor-bridge dir`.
91/// Fails rather than hand out a directory others could write to.
92pub fn ensure_bridge_dir() -> Result<PathBuf, String> {
93    let dir = bridge_dir().ok_or("cannot resolve the lean-ctx data directory")?;
94    std::fs::create_dir_all(&dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
95    crate::core::secure_fs::restrict_to_owner(&dir)
96        .map_err(|e| format!("restrict {}: {e}", dir.display()))?;
97    if !private_to_user(&dir, true) {
98        return Err(format!(
99            "{} is not a directory private to the current user",
100            dir.display()
101        ));
102    }
103    Ok(dir)
104}
105
106/// Whether `path` is a real directory (`dir`) or regular file — not a
107/// symlink — owned by the current user and writable by nobody else. An
108/// announcement carries a token and names an endpoint lean-ctx will trust,
109/// so one another local user could have planted or edited is ignored. On
110/// Windows the data directory lives in the user's profile, protected by its
111/// ACL; only the symlink check applies.
112fn private_to_user(path: &Path, dir: bool) -> bool {
113    let Ok(meta) = std::fs::symlink_metadata(path) else {
114        return false;
115    };
116    let kind_ok = if dir { meta.is_dir() } else { meta.is_file() };
117    #[cfg(unix)]
118    {
119        use std::os::unix::fs::MetadataExt;
120        // SAFETY: geteuid has no preconditions and cannot fail.
121        let me = unsafe { libc::geteuid() };
122        kind_ok && meta.uid() == me && meta.mode() & 0o022 == 0
123    }
124    #[cfg(not(unix))]
125    {
126        kind_ok
127    }
128}
129
130fn read_bridge_file(path: &Path) -> Option<BridgeFile> {
131    use std::io::Read;
132    let mut text = String::new();
133    std::fs::File::open(path)
134        .ok()?
135        .take(MAX_BRIDGE_FILE_BYTES + 1)
136        .read_to_string(&mut text)
137        .ok()?;
138    if text.len() as u64 > MAX_BRIDGE_FILE_BYTES {
139        return None;
140    }
141    serde_json::from_str(&text).ok()
142}
143
144fn canonical(path: &str) -> PathBuf {
145    crate::core::pathutil::canonicalize_secure_or_self(Path::new(path))
146}
147
148/// Bridge files in `dir` announcing `project_root`, newest first.
149fn candidates(dir: &Path, project_root: &str) -> Vec<BridgeFile> {
150    let root = canonical(project_root);
151    if !private_to_user(dir, true) {
152        return Vec::new();
153    }
154    let Ok(entries) = std::fs::read_dir(dir) else {
155        return Vec::new();
156    };
157    let mut found: Vec<(std::time::SystemTime, String, BridgeFile)> = entries
158        .flatten()
159        .map(|e| e.path())
160        .filter(|p| p.extension().is_some_and(|e| e == "json"))
161        .filter(|p| private_to_user(p, false))
162        .filter_map(|p| {
163            let bridge = read_bridge_file(&p)?;
164            (canonical(&bridge.project_root) == root).then(|| {
165                let modified = p
166                    .metadata()
167                    .and_then(|m| m.modified())
168                    .unwrap_or(std::time::UNIX_EPOCH);
169                (modified, p.to_string_lossy().into_owned(), bridge)
170            })
171        })
172        .collect();
173    // Newest first; the path breaks ties deterministically.
174    found.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1)));
175    found.into_iter().map(|(_, _, b)| b).collect()
176}
177
178/// `GET /health` answers with the bridge's own identity — not merely some
179/// 2xx from whatever now listens on that port.
180fn answers_as_announced(bridge: &BridgeFile) -> bool {
181    let url = format!("http://127.0.0.1:{}/health", bridge.port);
182    let Ok(resp) = ureq::get(&url)
183        .config()
184        .timeout_global(Some(Duration::from_millis(300)))
185        .build()
186        .header("X-LeanCtx-Token", &bridge.token)
187        .call()
188    else {
189        return false;
190    };
191    let Ok(text) = resp.into_body().read_to_string() else {
192        return false;
193    };
194    serde_json::from_str::<serde_json::Value>(&text).is_ok_and(|v| {
195        v.get("status").and_then(|s| s.as_str()) == Some("ok")
196            && v.get("editor").and_then(|e| e.as_str()) == Some(bridge.editor.as_str())
197    })
198}
199
200/// Discovery results per canonical project root: `(bridge, checked at)`.
201static DISCOVERED: LazyLock<Mutex<HashMap<PathBuf, (Option<BridgeFile>, Instant)>>> =
202    LazyLock::new(|| Mutex::new(HashMap::new()));
203
204/// The live bridge announced for `project_root`: its process alive and its
205/// `/health` answering. Answers are reused for `DISCOVERY_TTL` (10 s).
206pub fn discover(project_root: &str) -> Option<BridgeFile> {
207    let key = canonical(project_root);
208    if let Some((bridge, at)) = DISCOVERED
209        .lock()
210        .unwrap_or_else(PoisonError::into_inner)
211        .get(&key)
212        && at.elapsed() < DISCOVERY_TTL
213    {
214        return bridge.clone();
215    }
216    let bridge = bridge_dir().and_then(|dir| {
217        candidates(&dir, project_root)
218            .into_iter()
219            .find(|b| pid_alive(b.pid) && answers_as_announced(b))
220    });
221    let mut cache = DISCOVERED.lock().unwrap_or_else(PoisonError::into_inner);
222    cache.retain(|_, (_, at)| at.elapsed() < DISCOVERY_TTL);
223    cache.insert(key, (bridge.clone(), Instant::now()));
224    bridge
225}
226
227/// Drops the cached discovery for `project_root` (a call to the bridge
228/// failed — the editor may have closed).
229pub fn forget(project_root: &str) {
230    DISCOVERED
231        .lock()
232        .unwrap_or_else(PoisonError::into_inner)
233        .remove(&canonical(project_root));
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    /// Sets `path` to `mode`: fixtures must not depend on the caller's umask,
241    /// since `private_to_user` refuses group-writable entries (#2273).
242    #[cfg(unix)]
243    fn set_mode(path: &Path, mode: u32) {
244        use std::os::unix::fs::PermissionsExt;
245        std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
246    }
247
248    /// A temporary directory that is private to this user under any umask.
249    fn private_tempdir() -> tempfile::TempDir {
250        let dir = tempfile::tempdir().unwrap();
251        #[cfg(unix)]
252        set_mode(dir.path(), 0o700);
253        dir
254    }
255
256    fn write_bridge(dir: &Path, name: &str, root: &str, editor: &str) {
257        let path = dir.join(name);
258        std::fs::write(
259            &path,
260            serde_json::json!({
261                "port": 1, "token": "t", "pid": 1,
262                "project_root": root, "editor": editor, "editor_version": "1.0",
263            })
264            .to_string(),
265        )
266        .unwrap();
267        #[cfg(unix)]
268        set_mode(&path, 0o600);
269    }
270
271    /// A bridge is found by its canonical project root — another spelling of
272    /// the same directory matches, another project or a stray file does not.
273    #[test]
274    fn bridges_match_by_canonical_project_root() {
275        let dir = private_tempdir();
276        let project = tempfile::tempdir().unwrap();
277        let other = tempfile::tempdir().unwrap();
278        let root = project.path().to_string_lossy().to_string();
279        write_bridge(dir.path(), "a.json", &format!("{root}/"), "vscode");
280        write_bridge(
281            dir.path(),
282            "b.json",
283            &other.path().to_string_lossy(),
284            "cursor",
285        );
286        std::fs::write(dir.path().join("c.json"), "not json").unwrap();
287        std::fs::write(dir.path().join("d.txt"), "{}").unwrap();
288
289        let found = candidates(dir.path(), &root);
290        assert_eq!(found.len(), 1);
291        assert_eq!(found[0].editor, "vscode");
292        {
293            let found = &candidates(dir.path(), "/nonexistent/project");
294            assert!(found.is_empty(), "{found:?}");
295        }
296    }
297
298    /// An announcement names an endpoint lean-ctx trusts: one that another
299    /// user could have planted or redirected — a symlink, a file or directory
300    /// writable by others — is ignored.
301    #[cfg(unix)]
302    #[test]
303    fn announcements_others_could_write_are_ignored() {
304        let project = tempfile::tempdir().unwrap();
305        let root = project.path().to_string_lossy().to_string();
306
307        let dir = private_tempdir();
308        let elsewhere = private_tempdir();
309        write_bridge(elsewhere.path(), "real.json", &root, "vscode");
310        std::os::unix::fs::symlink(
311            elsewhere.path().join("real.json"),
312            dir.path().join("link.json"),
313        )
314        .unwrap();
315        write_bridge(dir.path(), "shared.json", &root, "cursor");
316        set_mode(&dir.path().join("shared.json"), 0o666);
317        assert!(
318            candidates(dir.path(), &root).is_empty(),
319            "symlink and group-writable file"
320        );
321
322        set_mode(&dir.path().join("shared.json"), 0o600);
323        assert_eq!(candidates(dir.path(), &root).len(), 1);
324        set_mode(dir.path(), 0o777);
325        assert!(
326            candidates(dir.path(), &root).is_empty(),
327            "world-writable directory"
328        );
329        set_mode(dir.path(), 0o700);
330    }
331}